💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Isolate albums app from shared web packages
Anand Baburajan550138dc9506
diff --git a/web/apps/albums/next.config.js b/web/apps/albums/next.config.jsindex 5a52794ab2..28256d7c10 100644--- a/web/apps/albums/next.config.js+++ b/web/apps/albums/next.config.js@@ -1 +1,44 @@-module.exports = require("ente-base/next.config.base.js");+// @ts-check++const cp = require("child_process");+const path = require("path");++const gitSHA = (() => {+ const result = cp+ .execSync("git rev-parse --short HEAD 2>/dev/null || true", {+ cwd: __dirname,+ encoding: "utf8",+ })+ .trimEnd();+ return result || undefined;+})();++const appName = path.basename(process.cwd());++/** @type {import("next").NextConfig} */+module.exports = {+ output: "export",+ devIndicators: false,+ compiler: { emotion: true },+ env: {+ gitSHA,+ appName,+ isDesktop: "",+ desktopAppVersion: undefined,+ },+ webpack: (config, { isServer }) => {+ if (!isServer) {+ config.resolve.fallback.fs = false;+ }++ config.ignoreWarnings = [{ module: /libheif-js/ }];+ config.experiments = { ...config.experiments, asyncWebAssembly: true };+ config.output = config.output || {};+ config.output.environment = {+ ...(config.output.environment || {}),+ asyncFunction: true,+ };++ return config;+ },+};diff --git a/web/apps/albums/package.json b/web/apps/albums/package.jsonindex 43ac9f2489..78204c6ce0 100644--- a/web/apps/albums/package.json+++ b/web/apps/albums/package.json@@ -3,21 +3,48 @@"version": "0.0.0","private": true,"dependencies": {+ "@emotion/react": "^11.14.0",+ "@emotion/styled": "^11.14.1",+ "@ffmpeg/ffmpeg": "^0.12.15",+ "@fontsource-variable/inter": "^5.2.8","@hugeicons/core-free-icons": "^1.1.0","@hugeicons/react": "^1.1.4",+ "@mui/icons-material": "^7.3.4",+ "@mui/material": "^7.3.4",+ "@mui/system": "^7.3.3",+ "@mui/x-date-pickers": "^8.14.0",+ "bip39": "^3.1.0",+ "bs58": "^6.0.0","chrono-node": "^2.9.0",+ "comlink": "^4.4.2",+ "dayjs": "^1.11.18","debounce": "^2.2.0",- "ente-accounts": "*",- "ente-base": "*",- "ente-gallery": "*",- "ente-media": "*",- "ente-new": "*",- "ente-wasm": "*",+ "exifreader": "^4.32.0",+ "fast-srp-hap": "^2.0.4",+ "file-type": "21.3.1",+ "formik": "^2.4.6",+ "get-user-locale": "^3.0.0",+ "heic-convert": "^2.1.0",+ "hls-video-element": "^1.5.8",+ "i18next": "^25.6.0",+ "i18next-resources-to-backend": "^1.2.1",+ "idb": "^8.0.3",+ "jszip": "^3.10.1",+ "leaflet": "^1.9.4",+ "leaflet-defaulticon-compatibility": "^0.1.2",+ "libsodium-wrappers-sumo": "^0.7.15",+ "localforage": "^1.10.0",+ "media-chrome": "^4.14.0","memoize-one": "^6.0.0","ml-matrix": "^6.12.1",+ "nanoid": "^5.1.6",+ "next": "^15.5.9","p-debounce": "^5.0.0",+ "photoswipe": "^5.4.4","react": "^19.2.0","react-dom": "^19.2.0",+ "react-dropzone": "14.2.10",+ "react-i18next": "^16.0.1","react-leaflet": "^5.0.0","react-select": "^5.10.2","react-top-loading-bar": "^3.0.2",@@ -25,13 +52,17 @@"react-window": "^1.8.11","sanitize-filename": "^1.6.3","similarity-transformation": "^0.0.1",- "supercluster": "^8.0.1"+ "supercluster": "^8.0.1",+ "uuid": "^13.0.0",+ "zod": "^4.1.12"},"devDependencies": {+ "@types/heic-convert": "^2.1.0",+ "@types/leaflet": "^1.9.21",+ "@types/libsodium-wrappers-sumo": "^0.7.8","@types/node": "^22.15.32","@types/react": "^19.2.2","@types/react-dom": "^19.2.2",- "@types/react-window": "^1.8.8",- "ente-build-config": "*"+ "@types/react-window": "^1.8.8"}}diff --git a/web/apps/albums/src/pages/_app.tsx b/web/apps/albums/src/pages/_app.tsxindex cfcd8896b4..460a644f47 100644--- a/web/apps/albums/src/pages/_app.tsx+++ b/web/apps/albums/src/pages/_app.tsx@@ -1 +1,96 @@-export { default } from "../../../photos/src/pages/_app";+import "@fontsource-variable/inter";+import { CssBaseline } from "@mui/material";+import { ThemeProvider } from "@mui/material/styles";+import { useNotification } from "components/utils/hooks-app";+import { staticAppTitle } from "ente-base/app";+import { CustomHeadPhotosOrAlbums } from "ente-base/components/Head";+import {+ LoadingIndicator,+ TranslucentLoadingOverlay,+} from "ente-base/components/loaders";+import { AttributedMiniDialog } from "ente-base/components/MiniDialog";+import { useAttributedMiniDialog } from "ente-base/components/utils/dialog";+import {+ useIsRouteChangeInProgress,+ useSetupI18n,+ useSetupLogs,+} from "ente-base/components/utils/hooks-app";+import { photosTheme } from "ente-base/components/utils/theme";+import { BaseContext, deriveBaseContext } from "ente-base/context";+import { Notification } from "ente-new/photos/components/Notification";+import { ThemedLoadingBar } from "ente-new/photos/components/ThemedLoadingBar";+import { useLoadingBar } from "ente-new/photos/components/utils/use-loading-bar";+import { PhotosAppContext } from "ente-new/photos/types/context";+import { t } from "i18next";+import type { AppProps } from "next/app";+import { useMemo, useState } from "react";++import "photoswipe/dist/photoswipe.css";+import "styles/global.css";+import "styles/photoswipe.css";++type AlbumsAppProps = AppProps<Record<string, unknown>>;++const App: React.FC<AlbumsAppProps> = ({ Component, pageProps }) => {+ useSetupLogs();++ const isI18nReady = useSetupI18n();+ const isChangingRoute = useIsRouteChangeInProgress();+ const { showMiniDialog, miniDialogProps } = useAttributedMiniDialog();+ const { showNotification, notificationProps } = useNotification();+ const { loadingBarRef, showLoadingBar, hideLoadingBar } = useLoadingBar();+ const [watchFolderView, setWatchFolderView] = useState(false);++ const baseContext = useMemo(+ () =>+ deriveBaseContext({+ logout: () => {},+ showMiniDialog,+ }),+ [showMiniDialog],+ );+ const appContext = useMemo(+ () => ({+ showLoadingBar,+ hideLoadingBar,+ watchFolderView,+ setWatchFolderView,+ showNotification,+ }),+ [+ showLoadingBar,+ hideLoadingBar,+ watchFolderView,+ setWatchFolderView,+ showNotification,+ ],+ );++ const title = isI18nReady ? t("title_photos") : staticAppTitle;++ return (+ <ThemeProvider theme={photosTheme}>+ <CustomHeadPhotosOrAlbums {...{ title }} />+ <CssBaseline enableColorScheme />++ <ThemedLoadingBar ref={loadingBarRef} />+ <AttributedMiniDialog {...miniDialogProps} />+ <Notification {...notificationProps} />++ <BaseContext value={baseContext}>+ <PhotosAppContext value={appContext}>+ {!isI18nReady ? (+ <LoadingIndicator />+ ) : (+ <>+ {isChangingRoute && <TranslucentLoadingOverlay />}+ <Component {...pageProps} />+ </>+ )}+ </PhotosAppContext>+ </BaseContext>+ </ThemeProvider>+ );+};++export default App;diff --git a/web/apps/albums/tsconfig.json b/web/apps/albums/tsconfig.jsonindex dad3f93a38..95895cf067 100644--- a/web/apps/albums/tsconfig.json+++ b/web/apps/albums/tsconfig.json@@ -1,18 +1,49 @@{- "extends": "ente-build-config/tsconfig-next.json","compilerOptions": {- "baseUrl": "../photos/src"+ "noEmit": true,+ "lib": ["ESnext", "DOM", "DOM.Iterable", "WebWorker"],+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "jsx": "preserve",+ "isolatedModules": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "verbatimModuleSyntax": true,+ "resolveJsonModule": true,+ "strict": true,+ "noImplicitReturns": true,+ "noUnusedParameters": true,+ "noUnusedLocals": true,+ "noFallthroughCasesInSwitch": true,+ "noUncheckedIndexedAccess": true,+ "exactOptionalPropertyTypes": false,+ "allowJs": true,+ "incremental": true,+ "baseUrl": ".",+ "paths": {+ "components/*": ["vendor/photos/components/*"],+ "hooks/*": ["vendor/photos/hooks/*"],+ "services/*": ["vendor/photos/services/*"],+ "utils/*": ["vendor/photos/utils/*"],+ "styles/*": ["vendor/photos/styles/*"],+ "ente-accounts/*": ["vendor/ente-accounts/*"],+ "ente-base/*": ["vendor/ente-base/*"],+ "ente-gallery/*": ["vendor/ente-gallery/*"],+ "ente-media/*": ["vendor/ente-media/*"],+ "ente-new/*": ["vendor/ente-new/*"],+ "ente-utils/*": ["vendor/ente-utils/*"]+ }},"include": ["next-env.d.ts","src/**/*.ts","src/**/*.tsx","src/**/*.js",- "../photos/src/**/*.ts",- "../photos/src/**/*.tsx",- "../photos/src/**/*.js",- "../../packages/base/components/utils/mui-theme.d.ts",- "../../packages/base/global-electron.d.ts"+ "vendor/**/*.ts",+ "vendor/**/*.tsx",+ "vendor/**/*.js",+ "vendor/**/*.d.ts"],"exclude": ["node_modules", "out", ".next", ".next-desktop"]}diff --git a/web/apps/albums/vendor/ente-accounts/components/layouts/centered-paper.tsx b/web/apps/albums/vendor/ente-accounts/components/layouts/centered-paper.tsxnew file mode 100644index 0000000000..521707f864--- /dev/null+++ b/web/apps/albums/vendor/ente-accounts/components/layouts/centered-paper.tsx@@ -0,0 +1,88 @@+import { Paper, Stack, styled, Typography } from "@mui/material";+import { CenteredFill } from "ente-base/components/containers";+import { EnteLogo } from "ente-base/components/EnteLogo";+import { NavbarBase } from "ente-base/components/Navbar";++/**+ * An ad-hoc component that abstracts the layout common to many of the pages+ * exported by the the accounts package.+ *+ * The layout is roughly:+ * - Set height to 100vh+ * - An app bar at the top+ * - Center a {@link Paper} in the rest of the space.+ * - The children passed to this component go within this {@link Paper}.+ *+ * {@link AccountsPageTitle} and {@link AccountsPageFooter} are meant to be used+ * in tandem with, as children of, {@link AccountsPageContents}.+ */+export const AccountsPageContents: React.FC<React.PropsWithChildren> = ({+ children,+}) => (+ <Stack+ sx={[+ { minHeight: "100svh", bgcolor: "secondary.main" },+ (theme) =>+ theme.applyStyles("dark", { bgcolor: "background.default" }),+ ]}+ >+ <NavbarBase+ sx={{+ boxShadow: "none",+ borderBottom: "none",+ bgcolor: "transparent",+ }}+ >+ <EnteLogo />+ </NavbarBase>+ <CenteredFill+ sx={[+ { bgcolor: "secondary.main" },+ (theme) =>+ theme.applyStyles("dark", {+ bgcolor: "background.default",+ }),+ ]}+ >+ <AccountsPagePaper>{children}</AccountsPagePaper>+ </CenteredFill>+ </Stack>+);++const AccountsPagePaper = styled(Paper)(({ theme }) => ({+ marginBlock: theme.spacing(2),+ padding: theme.spacing(5, 3),+ [theme.breakpoints.up("sm")]: { padding: theme.spacing(5) },+ width: "min(420px, 85vw)",+ minHeight: "375px",+ display: "flex",+ flexDirection: "column",+ gap: theme.spacing(4),+ boxShadow: "none",+ borderRadius: "20px",+}));++export const AccountsPageTitle: React.FC<React.PropsWithChildren> = ({+ children,+}) => (+ <Typography variant="h3" sx={{ flex: 1 }}>+ {children}+ </Typography>+);++export const AccountsPageFooter: React.FC<React.PropsWithChildren> = ({+ children,+}) => (+ <Stack+ direction="row"+ sx={{+ mx: "4px",+ // Put the items to the side,+ justifyContent: "space-between",+ // Unless there is just one, in which case center it.+ "& :only-child": { marginInline: "auto" },+ }}+ >+ {children}+ </Stack>+);diff --git a/web/apps/albums/vendor/ente-accounts/services/accounts-db.ts b/web/apps/albums/vendor/ente-accounts/services/accounts-db.tsnew file mode 100644index 0000000000..a1b6214674--- /dev/null+++ b/web/apps/albums/vendor/ente-accounts/services/accounts-db.ts@@ -0,0 +1,460 @@+/**+ * @file [Note: Accounts DB]+ *+ * The accounts package stores various state both during the login / signup+ * flow, and post login to identify the logged in user.+ *+ * This state is stored in local storage.+ *+ * Most of this state is meant to be transitory - various bits and bobs that we+ * accumulate and want to persist as the user goes through the login or signup+ * flow. One the user is successfully logged in and the first pull has+ * completed, then only a few of these are expected to remain:+ *+ * - "user"+ * - "keyAttributes"+ * - "originalKeyAttributes"+ * - "srpAttributes"+ */++import { savedAuthToken } from "ente-base/token";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";+import {+ RemoteSRPAttributes,+ SRPSetupAttributes,+ type SRPAttributes,+} from "./srp";+import {+ RemoteKeyAttributes,+ type KeyAttributes,+ type LocalUser,+} from "./user";++/**+ * The local storage data about the user before login or signup is complete.+ *+ * [Note: Partial local user]+ *+ * During login or signup, the user object exists in various partial states in+ * local storage.+ *+ * - Initially, there is no user object in local storage.+ *+ * - When the user enters their email, the email property of the stored object+ * is set, but nothing else.+ *+ * - After they verify their password, we have two cases: if second factor+ * verification is not set, and when it is set.+ *+ * - If second factor verification is not set, then after verifying their+ * password their {@link id} and {@link encryptedToken} will get filled in,+ * and {@link isTwoFactorEnabled} will be set to false.+ *+ * - If they have second factor verification set, then after verifying their+ * password {@link isTwoFactorEnabled} and {@link twoFactorSessionID} will+ * also get filled in. Once they verify their TOTP based second factor, their+ * {@link id} and {@link encryptedToken} will also get filled in.+ *+ * - If they have a passkey set as a second factor set, then after verifying+ * their password the {@link passkeySessionID} will be set.+ *+ * - As the login or signup sequence completes, a {@link token} obtained from+ * the {@link encryptedToken} will be written out, and the+ * {@link encryptedToken} cleared since it is not needed anymore.+ *+ * So while the underlying storage is the same, we offer two APIs for code to+ * obtain the user:+ *+ * - Before login is complete, or when it is unknown if login is complete or+ * not, then {@link savedPartialLocalUser} can be used to obtain a+ * {@link PartialLocalUser} with all of its properties set to be optional (and+ * some additional properties not available in the regular user object).+ *+ * - When we know that the login has completed, we can use either+ * {@link savedLocalUser} (which returns `undefined` if our assumption is+ * false) or {@link ensureSavedLocalUser} (which throws if our assumption is+ * false) to obtain an object with all the properties expected to be present+ * for a locally persisted user set to be required.+ */+export interface PartialLocalUser {+ id?: number;+ email?: string;+ token?: string;+ encryptedToken?: string;+ isTwoFactorEnabled?: boolean;+ twoFactorSessionID?: string;+ passkeySessionID?: string;+}++const PartialLocalUser = z.object({+ id: z.number().nullish().transform(nullToUndefined),+ email: z.string().nullish().transform(nullToUndefined),+ token: z.string().nullish().transform(nullToUndefined),+ encryptedToken: z.string().nullish().transform(nullToUndefined),+ isTwoFactorEnabled: z.boolean().nullish().transform(nullToUndefined),+ twoFactorSessionID: z.string().nullish().transform(nullToUndefined),+ passkeySessionID: z.string().nullish().transform(nullToUndefined),+});++/**+ * Zod schema for the {@link LocalUser} TypeScript type.+ *+ * The type itself is in `user.ts`.+ */+const LocalUser = z.object({+ id: z.number(),+ email: z.string(),+ token: z.string(),+ isTwoFactorEnabled: z.boolean().nullish().transform(nullToUndefined),+});++/**+ * Return the local storage value of the user's data.+ *+ * This function is meant to be called during the login or signup sequence.+ * After the user is logged in, use {@link savedLocalUser} or+ * {@link ensureLocalUser} instead.+ *+ * Use {@link replaceSavedLocalUser} to updated the saved value.+ */+export const savedPartialLocalUser = (): PartialLocalUser | undefined => {+ const jsonString = localStorage.getItem("user");+ if (!jsonString) return undefined;+ const result = PartialLocalUser.parse(JSON.parse(jsonString));+ void ensureTokensMatch(result);+ return result;+};++/**+ * Save the users data as we accrue it during the signup or login flow.+ *+ * See: [Note: Partial local user].+ *+ * This method replaces the existing data. Use {@link updateSavedLocalUser} to+ * update selected fields while keeping the other fields as it is.+ */+export const replaceSavedLocalUser = (partialLocalUser: PartialLocalUser) =>+ localStorage.setItem("user", JSON.stringify(partialLocalUser));++/**+ * Partially update the saved user data.+ *+ * This is a delta variant of {@link replaceSavedLocalUser}, which replaces the+ * entire saved object, while this function spreads the provided {@link updates}+ * onto the currently saved value.+ *+ * @param updates A subset of {@link PartialLocalUser} fields that we'd like to+ * update. The other fields, if present in local storage, remain unchanged.+ */+export const updateSavedLocalUser = (updates: Partial<PartialLocalUser>) =>+ replaceSavedLocalUser({ ...savedPartialLocalUser(), ...updates });++/**+ * Return data about the logged-in user, if someone is indeed logged in.+ * Otherwise return `undefined`.+ *+ * The user's data is stored in the browser's localStorage. Thus, this function+ * only works from the main thread, not from web workers since local storage is+ * not accessible to web workers.+ *+ * There is no setter corresponding to this function since this is only a view+ * on data saved using {@link replaceSavedLocalUser} or+ * {@link updateSavedLocalUser}.+ *+ * See: [Note: Partial local user] for more about the whole shebang.+ */+export const savedLocalUser = (): LocalUser | undefined => {+ const jsonString = localStorage.getItem("user");+ if (!jsonString) return undefined;+ // We might have some data, but not all of it. So do a non-throwing parse.+ const { success, data } = LocalUser.safeParse(JSON.parse(jsonString));+ if (success) void ensureTokensMatch(data);+ return success ? data : undefined;+};++/**+ * Sanity check to ensure that KV token and local storage token are the same.+ *+ * TODO: Added July 2025, can just be removed soon, there is already a sanity+ * check `isLocalStorageAndIndexedDBMismatch` on app start (tag: Migration).+ */+export const ensureTokensMatch = async (user: PartialLocalUser | undefined) => {+ if (user?.token !== (await savedAuthToken())) {+ throw new Error("Token mismatch");+ }+};++/**+ * Return true if the user's data is in local storage but not in IndexedDB.+ *+ * This acts a sanity check on IndexedDB by ensuring that if the user has a+ * token in local storage, then it should also be present in IndexedDB.+ */+export const isLocalStorageAndIndexedDBMismatch = async () =>+ savedPartialLocalUser()?.token && !(await savedAuthToken());++/**+ * Return the user's {@link KeyAttributes} if they are present in local storage.+ *+ * The key attributes are stored in the browser's localStorage. Thus, this+ * function only works from the main thread, not from web workers (local storage+ * is not accessible to web workers).+ *+ * See also: [Note: Original vs interactive key attributes]+ */+export const savedKeyAttributes = (): KeyAttributes | undefined => {+ const jsonString = localStorage.getItem("keyAttributes");+ if (!jsonString) return undefined;+ return RemoteKeyAttributes.parse(JSON.parse(jsonString));+};++/**+ * Save the user's {@link KeyAttributes} in local storage.+ *+ * Use {@link savedKeyAttributes} to retrieve them.+ */+export const saveKeyAttributes = (keyAttributes: KeyAttributes) =>+ localStorage.setItem("keyAttributes", JSON.stringify(keyAttributes));++/**+ * Return the user's original {@link KeyAttributes} if they are present in local+ * storage.+ *+ * [Note: Original vs interactive key attributes]+ *+ * This function is similar to {@link savedKeyAttributes} except it returns the+ * user's "original" key attributes. These are the key attributes that were+ * either freshly generated (if the user signed up on this client) or were+ * fetched from remote (otherwise).+ *+ * > NOTE: Currently the code does not guarantee that savedOriginalKeyAttributes+ * > will always be set when savedKeyAttributes is set.+ *+ * In contrast, the regular key attributes get overwritten by the local only+ * interactive key attributes for the user's convenience. See the documentation+ * of {@link generateAndSaveInteractiveKeyAttributes} for more details.+ */+export const savedOriginalKeyAttributes = (): KeyAttributes | undefined => {+ const jsonString = localStorage.getItem("originalKeyAttributes");+ if (!jsonString) return undefined;+ return RemoteKeyAttributes.parse(JSON.parse(jsonString));+};++/**+ * Save the user's {@link KeyAttributes} in local storage.+ *+ * Once saved, these values are not replaced (in contrast with the regular key+ * attributes which can get overwritten with interactive ones).+ *+ * Use {@link savedOriginalKeyAttributes} to retrieve them.+ */+export const saveOriginalKeyAttributes = (keyAttributes: KeyAttributes) =>+ localStorage.setItem(+ "originalKeyAttributes",+ JSON.stringify(keyAttributes),+ );++/**+ * Return the user's {@link SRPAttributes} if they are present in local storage.+ *+ * Like key attributes, SRP attributes are also stored in the browser's local+ * storage so will not be accessible to web workers.+ */+export const savedSRPAttributes = (): SRPAttributes | undefined => {+ const jsonString = localStorage.getItem("srpAttributes");+ if (!jsonString) return undefined;+ return RemoteSRPAttributes.parse(JSON.parse(jsonString));+};++/**+ * Save the user's {@link SRPAttributes} in local storage.+ *+ * Use {@link savedSRPAttributes} to retrieve them.+ */+export const saveSRPAttributes = (srpAttributes: SRPAttributes) =>+ localStorage.setItem("srpAttributes", JSON.stringify(srpAttributes));++/**+ * Save {@link SRPSetupAttributes} in local storage for later use via+ * {@link unstashAfterUseSRPSetupAttributes}.+ *+ * See: [Note: SRP setup attributes]+ */+export const stashSRPSetupAttributes = (+ srpSetupAttributes: SRPSetupAttributes,+) =>+ localStorage.setItem(+ "srpSetupAttributes",+ JSON.stringify(srpSetupAttributes),+ );++/**+ * Retrieve the {@link SRPSetupAttributes}, if any, that were stashed by a+ * previous call to {@link stashSRPSetupAttributes}.+ *+ * - If they are found, then invoke the provided callback ({@link cb}) with the+ * value. If the promise returned by the callback fulfills, then remove the+ * stashed value from local storage.+ *+ * - If they are not found, then the callback is not invoked.+ */+export const unstashAfterUseSRPSetupAttributes = async (+ cb: (srpSetupAttributes: SRPSetupAttributes) => Promise<void>,+) => {+ const jsonString = localStorage.getItem("srpSetupAttributes");+ if (!jsonString) return;+ const srpSetupAttributes = SRPSetupAttributes.parse(JSON.parse(jsonString));+ await cb(srpSetupAttributes);+ localStorage.removeItem("srpSetupAttributes");+};++/**+ * Zod schema for the legacy format in which the {@link savedIsFirstLogin} and+ * {@link savedJustSignedUp} flags were saved in local storage.+ *+ * Starting 1.7.15-beta (July 2025), we started saving the booleans directly,+ * but when reading we fallback to the old format if needed. This fallback can+ * be removed, and soonish, since these are transient flags that are saved+ * during the login / signup sequence and wouldn't be expected to remain in the+ * user's local storage for long anyway. (tag: Migration).+ */+const LocalLegacyBooleanFlag = z.object({+ status: z.boolean().nullish().transform(nullToUndefined),+});++/**+ * Return `true` if it is the user's first login on this client.+ *+ * The {@link savedIsFirstLogin} flag is saved in local storage (using+ * {@link saveIsFirstLogin}) if we determine during the login flow that it a+ * fresh login on this client. If so, we+ *+ * - Generate interactive key attributes for them, and+ *+ * - Display them a special indicator post login to notify them that the first+ * load might take extra time. At this point, we also clear the flag (the read+ * and clear is done by the same {@link getAndClearIsFirstLogin} function).+ */+export const savedIsFirstLogin = () => {+ const jsonString = localStorage.getItem("isFirstLogin");+ if (!jsonString) return false;+ try {+ return z.boolean().parse(JSON.parse(jsonString));+ } catch {+ return (+ LocalLegacyBooleanFlag.parse(JSON.parse(jsonString)).status ?? false+ );+ }+};++/**+ * Save a flag in local storage to indicate that this is the user's first login+ * on this client.+ *+ * This is the setter corresponding to {@link savedIsFirstLogin}.+ */+export const saveIsFirstLogin = () => {+ localStorage.setItem("isFirstLogin", JSON.stringify({ status: true }));+};++/**+ * Get the saved value of the local storage flag that indicates that this is the+ * user' first login on this client. Also remove the flag after reading.+ *+ * The flag can be set by using {@link saveIsFirstLogin}, and can be read+ * without clearing it by using {@link savedIsFirstLogin}.+ */+export const getAndClearIsFirstLogin = () => {+ // Completely unrelated, but since this code runs on each /gallery load, use+ // this as a chance to remove the unused "showBackButton" property saved in+ // local storage. This code was added 1.7.15-beta (July 2025) and can be+ // removed after a while, soonish (tag: Migration).+ localStorage.removeItem("showBackButton");++ const result = savedIsFirstLogin();+ localStorage.removeItem("isFirstLogin");+ return result;+};++/**+ * Return `true` if the user created a new account on this client during the+ * current (in-progress) or just completed login / signup sequence.+ */+export const savedJustSignedUp = () => {+ const jsonString = localStorage.getItem("justSignedUp");+ if (!jsonString) return false;+ try {+ return z.boolean().parse(JSON.parse(jsonString));+ } catch {+ return (+ LocalLegacyBooleanFlag.parse(JSON.parse(jsonString)).status ?? false+ );+ }+};++/**+ * Save a flag in local storage to indicate that the user signed up for a+ * new Ente account during the current login / signup sequence.+ *+ * This is the setter corresponding to {@link savedJustSignedUp}.+ */+export const saveJustSignedUp = () => {+ localStorage.setItem("justSignedUp", JSON.stringify({ status: true }));+};++/**+ * Get the saved value of the local storage flag that indicates that the user just+ * signed up. Also remove the flag from local storage after reading.+ *+ * The flag can be set by using {@link saveJustSignedUp}, and can be read+ * without clearing it by using {@link savedJustSignedUp}.+ */+export const getAndClearJustSignedUp = () => {+ const result = savedJustSignedUp();+ localStorage.removeItem("justSignedUp");+ return result;+};++/**+ * Zod schema for the format in which the {@link stashReferralSource} used to+ * saved the referral source in local storage.+ *+ * Starting 1.7.15-beta (July 2025), we started saving the string directly, but+ * when reading we fallback to the old format if needed. This fallback can be+ * removed, and soonish, since these is a transient value that isn't expected to+ * remain in the user's local storage for long anyway. (tag: Migration).+ */+const LocalLegacyReferralSource = z.object({ source: z.string() });++/**+ * Save the referral source entered by the user on the signup screen in local+ * storage.+ *+ * The saved value can be retrieved post email verification using+ * {@link unstashReferralSource}.+ */+export const stashReferralSource = (referralSource: string) => {+ localStorage.setItem("referralSource", referralSource);+};++/**+ * Retrieve the previously saved referral source (using+ * {@link stashReferralSource}), returning the saved value and also clearing it+ * from local storage.+ */+export const unstashReferralSource = () => {+ const jsonString = localStorage.getItem("referralSource");+ if (!jsonString) return undefined;+ localStorage.removeItem("referralSource");+ try {+ // Try the old format first. The trim is also a legacy expectation and+ // can be removed when we remove this fallfront.+ return LocalLegacyReferralSource.parse(+ JSON.parse(jsonString),+ ).source.trim();+ } catch {+ // Otherwise try the new format.+ return jsonString;+ }+};diff --git a/web/apps/albums/vendor/ente-accounts/services/passkey.ts b/web/apps/albums/vendor/ente-accounts/services/passkey.tsnew file mode 100644index 0000000000..c2803d4d70--- /dev/null+++ b/web/apps/albums/vendor/ente-accounts/services/passkey.ts@@ -0,0 +1,280 @@+import {+ saveKeyAttributes,+ updateSavedLocalUser,+} from "ente-accounts/services/accounts-db";+import {+ resetSavedLocalUserTokens,+ TwoFactorAuthorizationResponse,+} from "ente-accounts/services/user";+import { clientPackageName, isDesktop } from "ente-base/app";+import { encryptBox, generateKey } from "ente-base/crypto";+import {+ authenticatedRequestHeaders,+ ensureOk,+ HTTPError,+ publicRequestHeaders,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { z } from "zod";+import { getUserRecoveryKey } from "./recovery-key";+import { unstashRedirect } from "./redirect";++/**+ * Construct a redirect URL to take the user to Ente accounts app to+ * authenticate using their second factor, a passkey they've configured.+ *+ * On successful verification, the accounts app will redirect back to our+ * `/passkeys/finish` page.+ *+ * @param accountsURL The URL for the accounts app (provided to us by remote in+ * the email or SRP verification response).+ *+ * @param passkeySessionID An identifier provided by museum for this passkey+ * verification session.+ */+export const passkeyVerificationRedirectURL = (+ accountsURL: string,+ passkeySessionID: string,+) => {+ const clientPackage = clientPackageName;+ // Using `window.location.origin` will work both when we're running in a web+ // browser, and in our desktop app. See: [Note: Using deeplinks to navigate+ // in desktop app]+ const redirect = `${window.location.origin}/passkeys/finish`;+ // See: [Note: Conditional passkey recover option on accounts]+ const recoverOption: Record<string, string> = isDesktop+ ? {}+ : { recover: `${window.location.origin}/passkeys/recover` };+ const params = new URLSearchParams({+ clientPackage,+ passkeySessionID,+ redirect,+ ...recoverOption,+ });+ return `${accountsURL}/passkeys/verify?${params.toString()}`;+};++interface OpenPasskeyVerificationURLOptions {+ /**+ * The passkeySessionID for which we are redirecting.+ *+ * This is compared to the saved session id in the browser's session storage+ * to allow us to ignore redirects to the passkey flow finish page except+ * the ones for this specific session we're awaiting.+ */+ passkeySessionID: string;+ /** The URL to redirect to or open in the system browser. */+ url: string;+}++/**+ * Open or redirect to a passkey verification URL previously constructed using+ * {@link passkeyVerificationRedirectURL}.+ *+ * [Note: Passkey verification in the desktop app]+ *+ * Our desktop app bundles the web app and serves it over a custom protocol.+ * Passkeys are tied to origins, and will not work with this custom protocol+ * even if we move the passkey creation and authentication inline to within the+ * Photos web app.+ *+ * Thus, passkey creation and authentication in the desktop app works the same+ * way it works in the mobile app - the system browser is invoked to open+ * accounts.ente.io.+ *+ * - For passkey creation, this is a one-way open. Passkeys get created at+ * accounts.ente.io, and that's it.+ *+ * - For passkey verification, the flow is two-way. We register a custom+ * protocol and provide that as a return path redirect. Passkey authentication+ * happens at accounts.ente.io, and on success there is redirected back to the+ * desktop app.+ */+export const openPasskeyVerificationURL = ({+ passkeySessionID,+ url,+}: OpenPasskeyVerificationURLOptions) => {+ sessionStorage.setItem("inflightPasskeySessionID", passkeySessionID);++ if (globalThis.electron) window.open(url);+ else window.location.href = url;+};++/**+ * Open a new window showing a page on the Ente accounts app where the user can+ * see and their manage their passkeys.+ */+export const openAccountsManagePasskeysPage = async () => {+ // Check if the user has passkey recovery enabled.+ const { isPasskeyRecoveryEnabled } = await getTwoFactorRecoveryStatus();+ if (!isPasskeyRecoveryEnabled) {+ // If not, enable it for them by creating the necessary recovery+ // information to prevent them from getting locked out.+ const resetSecret = await generateKey();+ const { encryptedData, nonce } = await encryptBox(+ resetSecret,+ await getUserRecoveryKey(),+ );+ await configurePasskeyRecovery(resetSecret, encryptedData, nonce);+ }++ // Redirect to the Ente Accounts app where they can view and add and manage+ // their passkeys.+ const { accountsToken: token, accountsUrl: accountsURL } =+ await getAccountsTokenAndURL();+ const params = new URLSearchParams({ token });++ window.open(`${accountsURL}/passkeys?${params.toString()}`);+};++const TwoFactorRecoveryStatus = z.object({+ /**+ * `true` if the passkey recovery setup has been completed.+ */+ isPasskeyRecoveryEnabled: z.boolean(),+});++/**+ * Obtain the second factor recovery status from remote.+ */+export const getTwoFactorRecoveryStatus = async () => {+ const res = await fetch(await apiURL("/users/two-factor/recovery-status"), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return TwoFactorRecoveryStatus.parse(await res.json());+};++/**+ * Allow the user to bypass their passkeys by saving the provided recovery+ * credentials on remote.+ */+const configurePasskeyRecovery = async (+ secret: string,+ userSecretCipher: string,+ userSecretNonce: string,+) =>+ ensureOk(+ await fetch(+ await apiURL("/users/two-factor/passkeys/configure-recovery"),+ {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({+ secret,+ userSecretCipher,+ userSecretNonce,+ }),+ },+ ),+ );++/**+ * Fetch an Ente Accounts specific JWT token.+ *+ * This token can be used to authenticate with the Ente accounts app running at+ * accountsURL (the result contains both pieces of information).+ */+const getAccountsTokenAndURL = async () => {+ const res = await fetch(await apiURL("/users/accounts-token"), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return z+ .object({+ // The origin that serves the accounts app.+ accountsUrl: z.string(),+ // A token that can be used to authenticate with the accounts app.+ accountsToken: z.string(),+ })+ .parse(await res.json());+};++/**+ * The passkey session whose status we are trying to check has already expired.+ * The user should attempt to login again.+ */+export const passkeySessionExpiredErrorMessage = "Passkey session has expired";++/**+ * Check if the user has already authenticated using their passkey for the given+ * session.+ *+ * This is useful in case the automatic redirect back from accounts.ente.io to+ * the desktop app does not work for some reason. In such cases, the user can+ * press the "Check status" button: we'll make an API call to see if the+ * authentication has already completed, and if so, get the same "response"+ * object we'd have gotten as a query parameter in a redirect in+ * {@link saveCredentialsAndNavigateTo} on the "/passkeys/finish" page.+ *+ * @param sessionID The passkey session whose session we wish to check the+ * status of.+ *+ * @returns A {@link TwoFactorAuthorizationResponse} if the passkey+ * authentication has completed, and `undefined` otherwise.+ *+ * @throws In addition to arbitrary errors, it throws errors with the message+ * {@link passkeySessionExpiredErrorMessage}.+ */+export const checkPasskeyVerificationStatus = async (+ sessionID: string,+): Promise<TwoFactorAuthorizationResponse | undefined> => {+ const res = await fetch(+ await apiURL("/users/two-factor/passkeys/get-token", { sessionID }),+ { headers: publicRequestHeaders() },+ );+ if (!res.ok) {+ if (res.status == 404 || res.status == 410)+ throw new Error(passkeySessionExpiredErrorMessage);+ if (res.status == 400) return undefined; /* verification pending */+ throw new HTTPError(res);+ }+ return TwoFactorAuthorizationResponse.parse(await res.json());+};++/**+ * Extract credentials from a successful passkey verification response and save+ * them to local storage for use by subsequent steps (or normal functioning) of+ * the app.+ *+ * @param response The result of a successful+ * {@link checkPasskeyVerificationStatus}.+ *+ * @returns the slug that we should navigate to now.+ */+export const saveCredentialsAndNavigateTo = async (+ response: TwoFactorAuthorizationResponse,+) => {+ // [Note: Ending the passkey flow]+ //+ // The implementation of this function is similar to that of the+ // `saveQueryCredentialsAndNavigateTo` on the "/passkeys/finish" page.+ //+ // This one, `saveCredentialsAndNavigateTo`, is used when the user presses+ // the check verification status button on the page that triggered the+ // passkey flow (when they're using the desktop app).+ //+ // The other one, `saveQueryCredentialsAndNavigateTo`, is used when the user+ // goes through the passkey flow in the browser itself (when they are using+ // the web app).++ clearInflightPasskeySessionID();++ const { id, encryptedToken, keyAttributes } = response;++ await resetSavedLocalUserTokens(id, encryptedToken);+ updateSavedLocalUser({ passkeySessionID: undefined });+ saveKeyAttributes(keyAttributes);++ return unstashRedirect() ?? "/credentials";+};++/**+ * Remove the inflight passkey session ID, if any, present in session storage.+ *+ * This should be called whenever we get back control from the passkey app to+ * clean up after ourselves.+ */+export const clearInflightPasskeySessionID = () => {+ sessionStorage.removeItem("inflightPasskeySessionID");+};diff --git a/web/apps/albums/vendor/ente-accounts/services/recovery-key.ts b/web/apps/albums/vendor/ente-accounts/services/recovery-key.tsnew file mode 100644index 0000000000..3f2648ee6a--- /dev/null+++ b/web/apps/albums/vendor/ente-accounts/services/recovery-key.ts@@ -0,0 +1,116 @@+import * as bip39 from "bip39";+import { savedKeyAttributes } from "ente-accounts/services/accounts-db";+import {+ decryptBox,+ encryptBox,+ fromHex,+ generateKey,+ toHex,+} from "ente-base/crypto";+import { ensureMasterKeyFromSession } from "ente-base/session";+import { saveKeyAttributes } from "./accounts-db";+import { putUserRecoveryKeyAttributes, type KeyAttributes } from "./user";++// Mobile client library only supports English.+bip39.setDefaultWordlist("english");++/**+ * Convert the provided BIP-39 mnemonic string into its base64 representation.+ *+ * @param recoveryKeyMnemonicOrHex The BIP-39 mnemonic (24 word) string+ * representing the recovery key. For legacy compatibility, the function also+ * works if provided the hex representation of the recovery key.+ *+ * @returns A base64 string representing the underlying bytes of the recovery key.+ */+export const recoveryKeyFromMnemonic = (recoveryKeyMnemonicOrHex: string) => {+ const trimmedInput = recoveryKeyMnemonicOrHex+ .trim()+ .split(" ")+ .map((part) => part.trim())+ .filter((part) => !!part)+ .join(" ");++ let recoveryKeyHex: string;+ // Check if user is entering mnemonic recovery key.+ if (trimmedInput.indexOf(" ") > 0) {+ if (trimmedInput.split(" ").length != 24) {+ throw new Error("recovery code should have 24 words");+ }+ recoveryKeyHex = bip39.mnemonicToEntropy(trimmedInput);+ } else {+ recoveryKeyHex = trimmedInput;+ }++ return fromHex(recoveryKeyHex);+};++/**+ * Convert the provided base64 encoded recovery key into its BIP-39 mnemonic.+ *+ * @param recoveryKey The base64 encoded recovery key to mnemonize.+ *+ * @returns A 24-word mnemonic that serves as the user visible recovery key.+ */+export const recoveryKeyToMnemonic = async (recoveryKey: string) =>+ bip39.entropyToMnemonic(await toHex(recoveryKey));++/**+ * Return the (decrypted) recovery key of the logged in user, reading it from+ * local storage.+ *+ * As a fallback for old accounts that generated recovery keys on first view,+ * this function will also generate a new recovery key if needed.+ *+ * @returns The user's base64 encoded recovery key.+ */+export const getUserRecoveryKey = async () => {+ const masterKey = await ensureMasterKeyFromSession();++ const keyAttributes = savedKeyAttributes()!;+ const { recoveryKeyEncryptedWithMasterKey, recoveryKeyDecryptionNonce } =+ keyAttributes;++ if (recoveryKeyEncryptedWithMasterKey && recoveryKeyDecryptionNonce) {+ return decryptBox(+ {+ encryptedData: recoveryKeyEncryptedWithMasterKey,+ nonce: recoveryKeyDecryptionNonce,+ },+ masterKey,+ );+ } else {+ return createNewRecoveryKey(masterKey, keyAttributes);+ }+};++/**+ * Generate a new recovery key, tell remote about it, update our local state,+ * and then return it.+ *+ * This function is meant only for (very!) old accounts for whom the app did not+ * generate recovery keys on sign up but instead generated them on first view.+ *+ * @returns a new base64 encoded recovery key.+ */+const createNewRecoveryKey = async (+ masterKey: string,+ existingKeyAttributes: KeyAttributes,+) => {+ const recoveryKey = await generateKey();+ const encryptedMasterKey = await encryptBox(masterKey, recoveryKey);+ const encryptedRecoveryKey = await encryptBox(recoveryKey, masterKey);++ const recoveryKeyAttributes = {+ masterKeyEncryptedWithRecoveryKey: encryptedMasterKey.encryptedData,+ masterKeyDecryptionNonce: encryptedMasterKey.nonce,+ recoveryKeyEncryptedWithMasterKey: encryptedRecoveryKey.encryptedData,+ recoveryKeyDecryptionNonce: encryptedRecoveryKey.nonce,+ };++ await putUserRecoveryKeyAttributes(recoveryKeyAttributes);++ saveKeyAttributes({ ...existingKeyAttributes, ...recoveryKeyAttributes });++ return recoveryKey;+};diff --git a/web/apps/albums/vendor/ente-accounts/services/redirect.ts b/web/apps/albums/vendor/ente-accounts/services/redirect.tsnew file mode 100644index 0000000000..5b601c08a5--- /dev/null+++ b/web/apps/albums/vendor/ente-accounts/services/redirect.ts@@ -0,0 +1,35 @@+import { appName } from "ente-base/app";++/**+ * The default page ("home route") for each of our apps.+ *+ * This is where we redirect to after successful authentication.+ */+export const appHomeRoute: string = {+ accounts: "/passkeys",+ albums: "/",+ auth: "/auth",+ cast: "/" /* The cast app doesn't use this, this is an arbitrary value. */,+ embed: "/" /* The embed app doesn't use this either. */,+ share: "/" /* The locker public app also doesn't use this. */,+ photos: "/gallery",+ ensu: "/",+ locker: "/locker",+}[appName];++let _stashedRedirect: string | undefined;++/**+ * An in-memory redirect saved during the login flow (mostly).+ */+export const stashedRedirect = () => _stashedRedirect;++export const stashRedirect = (r: string) => (_stashedRedirect = r);++export const unstashRedirect = () => {+ const r = _stashedRedirect;+ _stashedRedirect = undefined;+ return r;+};++export const clearStashedRedirect = () => (_stashedRedirect = undefined);diff --git a/web/apps/albums/vendor/ente-accounts/services/srp.ts b/web/apps/albums/vendor/ente-accounts/services/srp.tsnew file mode 100644index 0000000000..20f58f5b83--- /dev/null+++ b/web/apps/albums/vendor/ente-accounts/services/srp.ts@@ -0,0 +1,624 @@+import {+ deriveSubKeyBytes,+ generateDeriveKeySalt,+ toB64,+} from "ente-base/crypto";+import {+ authenticatedRequestHeaders,+ ensureOk,+ publicRequestHeaders,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { ensure } from "ente-utils/ensure";+import { SRP, SrpClient } from "fast-srp-hap";+import { v4 as uuidv4 } from "uuid";+import { z } from "zod";+import { saveSRPAttributes } from "./accounts-db";+import {+ RemoteSRPVerificationResponse,+ type EmailOrSRPVerificationResponse,+} from "./user";++/**+ * The SRP attributes for a user.+ *+ * These are created by a client on signup, saved to remote. During logins, they+ * are fetched from remote. In both cases they are also persisted in local+ * storage (both network ops and local storage use the same schema).+ *+ * [Note: SRP]+ *+ * The SRP (Secure Remote Password) protocol is a modified Diffie-Hellman key+ * exchange that allows the remote to verify the user's possession of a+ * password, and the user to ensure that remote is not being impersonated,+ * without the password ever leaving the device.+ *+ * It is used as an (user selectable) alternative to email verification.+ *+ * For more about the what and why, see the announcement blog post+ * https://ente.io/blog/ente-adopts-secure-remote-passwords/+ *+ * Here we do not focus on the math (the above blog post links to reference+ * material, and there is also an RFC), but instead of the various bits of+ * information that get exchanged.+ *+ * Broadly, there are two scenarios: SRP setup, and SRP verification.+ *+ * [Note: SRP setup] -------------------+ *+ * During SRP setup, client generates+ *+ * 01. A SRP user ID (a new UUID-v4)+ * 02. A SRP password (deterministically derived from their regular KEK)+ * 03. A SRP salt (randomly generated)+ *+ * These 3 things are enough to create a SRP verifier and client. The SRP client+ * can just be thought of an ephemeral stateful mechanism to avoid passing all+ * the state accrued so far to each operation. Each time when creating a SRP+ * client, the app generates a new random secret and uses it during init.+ *+ * 04. Compute verifier = computeSRPVerifier({ userID, password, salt })+ * 05. Generates a new (ephemeral and random) clientSecret+ * 06. Create client = new SRPClient({ userID, password, salt, clientSecret })+ *+ * The client (app) then starts the setup ceremony with remote:+ *+ * 07. Use SRP client to conjure secret `a` and use that to compute a public A+ * 08. Send { userID, salt, verifier, A } to remote ("/users/srp/setup")+ *+ * Remote then:+ *+ * 09. Generates a new (ephemeral and random) serverSecret+ * 10. Saves { userID, serverSecret, A } into SRP sessions table+ * 11. Creates server = new SRPServer({ verifier, serverSecret })+ * 12. Uses SRP server to conjure secret `b` and use that to compute a public B+ * 13. Stashes { sessionID, userID, salt, verifier } into SRP setups table+ * 14. Returns { setupID, B } to client+ *+ * Client then+ *+ * 15. Tells its SRP client about B+ * 16. Computes SRP M1 (evidence message) using the SRP client+ * 17. Sends { setupID, M1 } to remote ("/users/srp/complete")+ *+ * Remote then+ *+ * 18. Uses setupID to read the stashed { sessionID, verifier }+ * 19. Uses sessionID to read { serverSecret, A }+ * 20. Recreates server = new SRPServer({ verifier, serverSecret })+ * 21. Sets server.A+ * 22. Verifies M1 using the SRP server, obtaining a SRP M2 (evidence message)+ * 23. Returns M2+ *+ * Client then+ *+ * 24. Verifies M2+ *+ * SRP setup is now complete.+ *+ * A similar flow is used when the user changes their password. On password+ * change, a new KEK is generated, thus the SRP password also changes, and so a+ * subset of the steps above are done to update both client and remote.+ *+ * [Note: SRP verification] -----------------------+ *+ * When the user is signing on a new device, the client+ *+ * 01. Fetches SRP attributes for a user to get { (SRP) userID, (SRP) salt }+ * 02. Rederives SRP password from their KEK+ * 03. Generates a new (ephemeral and random) clientSecret+ * 04. Creates client = new SRPClient({ userID, password, salt, clientSecret })+ * 05. Uses SRP client to conjure secret `a` and use that to compute a public A+ * 06. Sends { userID, A } to remote ("/users/srp/create-session")+ *+ * Remote+ *+ * 07. Retrieves { verifier } corresponding to the userID+ * 08. Generates a new (ephemeral and random) serverSecret+ * 09. Saves { userID, serverSecret, A } into SRP sessions table+ * 10. Creates server = new SRPServer({ verifier, serverSecret })+ * 11. Sets server.A+ * 12. Uses SRP server to conjure secret `b` and use that to compute a public B+ * 13. Returns { sessionID, B } to client+ *+ * Client then+ *+ * 14. Sets client.B+ * 15. Computes M1 (evidence message)+ * 16. Sends { userID, sessionID, M1 } to remote ("/users/srp/verify-session")+ *+ * Remote+ *+ * 17. Retrieves { verifier } corresponding to the userID+ * 17. Retrieves { serverSecret, A } using sessionID+ * 18. Recreates server = new SRPServer({ verifier, serverSecret })+ * 19. Sets server.A+ * 20. Verifies M1 using the SRP server, obtaining a SRP M2 (evidence message)+ * 21. Returns M2+ *+ * Client then+ *+ * 22. Verifies M2+ *+ * SRP verification is now complete.+ */+export interface SRPAttributes {+ /**+ * The SRP user ID for the (Ente) user.+ *+ * Each Ente user gets a new randomly generated UUID v4 assigned as their+ * SRP user ID during SRP setup.+ */+ srpUserID: string;+ /**+ * The SRP salt.+ *+ * This is a randomly generated salt created for each SRP user during SRP+ * setup. It is not meant to be secret.+ */+ srpSalt: string;+ /**+ * The mem limit used during the KEK derivation from the password.+ *+ * See also the discussion in {@link kekSalt}.+ */+ memLimit: number;+ /**+ * The ops limit used during the KEK derivation from the password.+ *+ * See also the discussion in {@link kekSalt}.+ */+ opsLimit: number;+ /**+ * The salt used during the KEK derivation from the password.+ *+ * Base64 encoded.+ *+ * This is the same value as the {@link kekSalt} in {@link KeyAttributes},+ * made available by remote also as part of SRP attributes for convenience.+ * See: [Note: KEK three tuple] for more details.+ */+ kekSalt: string;+ /**+ * If true, then the client should use email verification instead of SRP.+ */+ isEmailMFAEnabled: boolean;+}++/**+ * Zod schema for the {@link SRPAttributes} TypeScript type.+ *+ * We retain the SRP attributes response we get from remote verbatim when saving+ * it to local storage, so the same schema describes both the remote type and+ * the local storage type.+ */+export const RemoteSRPAttributes = z.object({+ srpUserID: z.string(),+ srpSalt: z.string(),+ memLimit: z.number(),+ opsLimit: z.number(),+ kekSalt: z.string(),+ isEmailMFAEnabled: z.boolean(),+});++/**+ * Fetch the {@link SRPAttributes} from remote for the Ente user with the+ * provided email.+ *+ * Returns `undefined` if either there is no Ente user with the given+ * {@link email}, or if there is a a user but they've not yet completed the SRP+ * setup ceremony.+ *+ * @param email The email of the user whose SRP attributes we're fetching.+ */+export const getSRPAttributes = async (+ email: string,+): Promise<SRPAttributes | undefined> => {+ const res = await fetch(await apiURL("/users/srp/attributes", { email }), {+ headers: publicRequestHeaders(),+ });+ if (res.status == 404) return undefined;+ ensureOk(res);+ return z.object({ attributes: RemoteSRPAttributes }).parse(await res.json())+ .attributes;+};++/**+ * A local-only structure holding information required for SRP setup.+ *+ * [Note: SRP setup attributes]+ *+ * In some cases, there might be a step between the client having access to the+ * KEK (which we need for generating the SRP attributes, in particular the SRP+ * password) and the time where the client can proceed with the SRP setup (which+ * can only happen once we have an auth token).+ *+ * For example, when the user is signing up for a new account, the client has+ * the KEK on the signup screen since the user just set their password, but then+ * has to redirect to the screen for email verification, and it is only after+ * email verification that the client obtains an auth token and the SRP setup+ * can proceed (at which point it doesn't have access to the password and so+ * cannot derive the KEK).+ *+ * This gap is not just about different screens, but since there is an email+ * verification step involved, it might take time enough for the browser tab to+ * get closed and reopened. So instead of keeping the attributes we need to+ * continue with the SRP setup after email verification in memory, we+ * temporarily stash them in local storage using an object that conforms to the+ * following {@link SRPSetupAttributes} schema.+ */+export const SRPSetupAttributes = z.object({+ srpUserID: z.string(),+ srpSalt: z.string(),+ srpVerifier: z.string(),+ loginSubKey: z.string(),+});++export type SRPSetupAttributes = z.infer<typeof SRPSetupAttributes>;++/**+ * Generate {@link SRPSetupAttributes} from the provided {@link kek}.+ *+ * @param kek The designated key encryption key (base64 encoded) for the user.+ * This will be used to (deterministically) derive a SRP password.+ */+export const generateSRPSetupAttributes = async (+ kek: string,+): Promise<SRPSetupAttributes> => {+ const loginSubKey = await deriveSRPLoginSubKey(kek);++ // Museum schema requires this to be a UUID.+ const srpUserID = uuidv4();+ const srpSalt = await generateDeriveKeySalt();++ const srpVerifier = bufferToB64(+ SRP.computeVerifier(+ SRP.params["4096"],+ b64ToBuffer(srpSalt),+ Buffer.from(srpUserID),+ b64ToBuffer(loginSubKey),+ ),+ );++ return { srpUserID, srpSalt, srpVerifier, loginSubKey };+};++/**+ * Derive a "login sub-key" (which is really an arbitrary binary value, not+ * human generated) for use as the SRP user password by applying a deterministic+ * KDF (Key Derivation Function) to the provided {@link kek}.+ *+ * @param kek The user's KEK (key encryption key) as a base64 string.+ *+ * @returns A base64 encoded key that can be used as the SRP user password.+ */+const deriveSRPLoginSubKey = async (kek: string) => {+ const kekSubKeyBytes = await deriveSubKeyBytes(kek, 32, 1, "loginctx");+ // Use the first 16 bytes (128 bits) of the KEK's KDF subkey as the SRP+ // password (instead of entire 32 bytes).+ return toB64(kekSubKeyBytes.slice(0, 16));+};++const b64ToBuffer = (base64: string) => Buffer.from(base64, "base64");++const bufferToB64 = (buffer: Buffer) => buffer.toString("base64");++/**+ * Use the provided {@link SRPSetupAttributes} to, well, setup SRP.+ *+ * See: [Note: SRP setup]+ *+ * @param srpSetupAttributes SRP setup attributes.+ */+export const setupSRP = async (srpSetupAttributes: SRPSetupAttributes) =>+ srpSetupOrReconfigure(srpSetupAttributes, completeSRPSetup);++/**+ * A function that is called by {@link srpSetupOrReconfigure} to exchange the+ * evidence message M1 for the evidence message M2 from remote.+ *+ * It is passed M1, and is expected to fulfill with M2.+ */+type SRPSetupOrReconfigureExchangeCallback = ({+ setupID,+ srpM1,+}: {+ setupID: string;+ srpM1: string;+}) => Promise<{ srpM2: string }>;++/**+ * Use the provided {@link SRPSetupAttributes} to either setup (afresh) or+ * reconfigure SRP (when the user changes their password).+ *+ * The flow (described in [Note: SRP setup]) is mostly the same except the tail+ * end of the process where we exchange the evidence message M1 for the evidence+ * message M2 from remote. To handle this variance, we provide a callback+ * {@link exchangeCB}) that is invoked at this point in the sequence.+ *+ * @param srpSetupAttributes SRP setup attributes.+ */+const srpSetupOrReconfigure = async (+ { srpSalt, srpUserID, srpVerifier, loginSubKey }: SRPSetupAttributes,+ exchangeCB: SRPSetupOrReconfigureExchangeCallback,+) => {+ const srpClient = await generateSRPClient(srpSalt, srpUserID, loginSubKey);++ const srpA = bufferToB64(srpClient.computeA());++ const { setupID, srpB } = await startSRPSetup({+ srpUserID,+ srpSalt,+ srpVerifier,+ srpA,+ });++ srpClient.setB(b64ToBuffer(srpB));++ const srpM1 = bufferToB64(srpClient.computeM1());++ const { srpM2 } = await exchangeCB({ srpM1, setupID });++ srpClient.checkM2(b64ToBuffer(srpM2));+};++const generateSRPClient = async (+ srpSalt: string,+ srpUserID: string,+ loginSubKey: string,+) =>+ new Promise<SrpClient>((resolve, reject) => {+ SRP.genKey((err, clientKey) => {+ if (err) reject(err);+ resolve(+ new SrpClient(+ SRP.params["4096"],+ b64ToBuffer(srpSalt),+ Buffer.from(srpUserID),+ b64ToBuffer(loginSubKey),+ // The random `clientKey` parameterizes the current instance+ // of the SRP client.+ clientKey!,+ false,+ ),+ );+ });+ });++interface SetupSRPRequest {+ srpUserID: string;+ srpSalt: string;+ srpVerifier: string;+ srpA: string;+}++const SetupSRPResponse = z.object({ setupID: z.string(), srpB: z.string() });++type SetupSRPResponse = z.infer<typeof SetupSRPResponse>;++/**+ * Initiate SRP setup on remote.+ *+ * Part of the [Note: SRP setup] sequence.+ */+const startSRPSetup = async (+ setupSRPRequest: SetupSRPRequest,+): Promise<SetupSRPResponse> => {+ const res = await fetch(await apiURL("/users/srp/setup"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(setupSRPRequest),+ });+ ensureOk(res);+ return SetupSRPResponse.parse(await res.json());+};++interface CompleteSRPSetupRequest {+ setupID: string;+ srpM1: string;+}++const CompleteSRPSetupResponse = z.object({+ setupID: z.string(),+ srpM2: z.string(),+});++type CompleteSRPSetupResponse = z.infer<typeof CompleteSRPSetupResponse>;++/**+ * Complete a previously initiated SRP setup on remote.+ *+ * Part of the [Note: SRP setup] sequence.+ */+const completeSRPSetup = async (+ completeSRPSetupRequest: CompleteSRPSetupRequest,+) => {+ const res = await fetch(await apiURL("/users/srp/complete"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(completeSRPSetupRequest),+ });+ ensureOk(res);+ return CompleteSRPSetupResponse.parse(await res.json());+};++/**+ * Fetch the SRP attributes from remote and use them to update the SRP+ * attributes we have saved locally.+ *+ * This function is intended to be called after {@link srpSetupOrReconfigure} to+ * also update our local state to match remote.+ *+ * @param userEmail The email of the user whose SRP attributes we want to fetch.+ * This should be the email address of the logged in user, or the user who is+ * going through the login / signup sequence currently.+ */+export const getAndSaveSRPAttributes = async (userEmail: string) =>+ saveSRPAttributes(ensure(await getSRPAttributes(userEmail)));++/**+ * The subset of {@link KeyAttributes} that get updated when the user changes+ * their password.+ */+export interface UpdatedKeyAttr {+ kekSalt: string;+ encryptedKey: string;+ keyDecryptionNonce: string;+ opsLimit: number;+ memLimit: number;+}++/**+ * Update the user's affected key and SRP attributes when they change their+ * password.+ *+ * The flow on changing password is similar to the flow on initial SRP setup,+ * with some differences at the tail end of the flow. See: [Note: SRP setup].+ *+ * @param srpSetupAttributes Attributes for the user's updated SRP setup.+ *+ * @param updatedKeyAttr The subset of the user's key attributes which need to+ * be updated to reflect their changed password.+ */+export const updateSRPAndKeyAttributes = (+ srpSetupAttributes: SRPSetupAttributes,+ updatedKeyAttr: UpdatedKeyAttr,+) =>+ srpSetupOrReconfigure(srpSetupAttributes, ({ setupID, srpM1 }) =>+ updateSRPAndKeys({ setupID, srpM1, updatedKeyAttr }),+ );++export interface UpdateSRPAndKeysRequest {+ setupID: string;+ srpM1: string;+ updatedKeyAttr: UpdatedKeyAttr;+ /**+ * If true (default), then all existing sessions for the user will be+ * invalidated.+ */+ logOutOtherDevices?: boolean;+}++const UpdateSRPAndKeysResponse = z.object({+ srpM2: z.string(),+ setupID: z.string(),+});++type UpdateSRPAndKeysResponse = z.infer<typeof UpdateSRPAndKeysResponse>;++/**+ * Update the SRP attributes and a subset of the key attributes on remote.+ *+ * This is invoked during the flow when the user changes their password, and SRP+ * needs to be reconfigured. See: [Note: SRP setup].+ */+const updateSRPAndKeys = async (+ updateSRPAndKeysRequest: UpdateSRPAndKeysRequest,+): Promise<UpdateSRPAndKeysResponse> => {+ const res = await fetch(await apiURL("/users/srp/update"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(updateSRPAndKeysRequest),+ });+ ensureOk(res);+ return UpdateSRPAndKeysResponse.parse(await res.json());+};++/**+ * The message of the {@link Error} that is thrown by {@link verifySRP} if+ * remote fails SRP verification with a HTTP 401.+ *+ * The API contract allows for a SRP verification 401 both because of incorrect+ * credentials or a non existent account.+ */+export const srpVerificationUnauthorizedErrorMessage =+ "SRP verification failed (HTTP 401 Unauthorized)";++/**+ * Log the user in to a new device by performing SRP verification.+ *+ * This function implements the flow described in [Note: SRP verification].+ *+ * @param srpAttributes The user's SRP attributes.+ *+ * @param kek The user's key encryption key as a base64 string.+ *+ * @returns If SRP verification is successful, it returns a+ * {@link EmailOrSRPVerificationResponse}.+ *+ * @throws An Error with {@link srpVerificationUnauthorizedErrorMessage} in case+ * there is no such account, or if the credentials (kek) are incorrect.+ */+export const verifySRP = async (+ { srpUserID, srpSalt }: SRPAttributes,+ kek: string,+): Promise<EmailOrSRPVerificationResponse> => {+ const loginSubKey = await deriveSRPLoginSubKey(kek);+ const srpClient = await generateSRPClient(srpSalt, srpUserID, loginSubKey);++ // Send A, obtain B.+ const { srpB, sessionID } = await createSRPSession({+ srpUserID,+ srpA: bufferToB64(srpClient.computeA()),+ });++ srpClient.setB(b64ToBuffer(srpB));++ // Send M1, obtain M2.+ const { srpM2, ...rest } = await verifySRPSession({+ sessionID,+ srpUserID,+ srpM1: bufferToB64(srpClient.computeM1()),+ });++ srpClient.checkM2(b64ToBuffer(srpM2));++ return rest;+};++interface CreateSRPSessionRequest {+ srpUserID: string;+ srpA: string;+}++const CreateSRPSessionResponse = z.object({+ sessionID: z.string(),+ srpB: z.string(),+});++type CreateSRPSessionResponse = z.infer<typeof CreateSRPSessionResponse>;++const createSRPSession = async (+ createSRPSessionRequest: CreateSRPSessionRequest,+): Promise<CreateSRPSessionResponse> => {+ const res = await fetch(await apiURL("/users/srp/create-session"), {+ method: "POST",+ headers: publicRequestHeaders(),+ body: JSON.stringify(createSRPSessionRequest),+ });+ ensureOk(res);+ return CreateSRPSessionResponse.parse(await res.json());+};++interface VerifySRPSessionRequest {+ sessionID: string;+ srpUserID: string;+ srpM1: string;+}++type SRPVerificationResponse = z.infer<typeof RemoteSRPVerificationResponse>;++const verifySRPSession = async (+ verifySRPSessionRequest: VerifySRPSessionRequest,+): Promise<SRPVerificationResponse> => {+ const res = await fetch(await apiURL("/users/srp/verify-session"), {+ method: "POST",+ headers: publicRequestHeaders(),+ body: JSON.stringify(verifySRPSessionRequest),+ });+ if (res.status == 401) {+ throw new Error(srpVerificationUnauthorizedErrorMessage);+ }+ ensureOk(res);+ return RemoteSRPVerificationResponse.parse(await res.json());+};diff --git a/web/apps/albums/vendor/ente-accounts/services/user.ts b/web/apps/albums/vendor/ente-accounts/services/user.tsnew file mode 100644index 0000000000..e9e4661bef--- /dev/null+++ b/web/apps/albums/vendor/ente-accounts/services/user.ts@@ -0,0 +1,1046 @@+import {+ replaceSavedLocalUser,+ savedKeyAttributes,+ savedLocalUser,+ savedPartialLocalUser,+ saveKeyAttributes,+ saveSRPAttributes,+ updateSavedLocalUser,+} from "ente-accounts/services/accounts-db";+import {+ generateSRPSetupAttributes,+ getAndSaveSRPAttributes,+ getSRPAttributes,+ updateSRPAndKeyAttributes,+ type UpdatedKeyAttr,+} from "ente-accounts/services/srp";+import {+ boxSealOpenBytes,+ decryptBox,+ deriveInteractiveKey,+ deriveSensitiveKey,+ encryptBox,+ generateKey,+ generateKeyPair,+ toB64URLSafe,+} from "ente-base/crypto";+import {+ authenticatedRequestHeaders,+ ensureOk,+ publicRequestHeaders,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { ensureMasterKeyFromSession } from "ente-base/session";+import {+ removeAuthToken,+ saveAuthToken,+ savedAuthToken,+} from "ente-base/token";+import { ensure } from "ente-utils/ensure";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";+import { clearInflightPasskeySessionID } from "./passkey";+import { getUserRecoveryKey, recoveryKeyFromMnemonic } from "./recovery-key";++/**+ * The locally persisted data we have about the user after they've logged in.+ *+ * This type arguably belongs to accounts-db (since that's what persists it and+ * its shadow alias, {@link PartialLocalUser}), but since most code that will+ * need this will need this after login has completed, and will be using the+ * {@link ensureLocalUser} method below, we keep this in the same file to reduce+ * the need to import the type from a separate file.+ */+export interface LocalUser {+ /**+ * The user's ID.+ */+ id: number;+ /**+ * The email associated with the user's Ente account.+ */+ email: string;+ /**+ * The user's (plaintext) auth token.+ *+ * It is used for making API calls on their behalf, by passing this token as+ * the value of the X-Auth-Token header in the HTTP request.+ *+ * Usually you shouldn't be needing to access this property; instead use+ * {@link savedAuthToken()} which is kept in sync with this value, and lives+ * in IndexedDB and thus can also be used in web workers.+ */+ token: string;+ /**+ * `true` if the TOTP based second factor is enabled for the user.+ */+ isTwoFactorEnabled?: boolean;+}++/**+ * Return the currently logged in {@link LocalUser}, throwing it the user is not+ * logged in.+ *+ * This is a wrapper over the {@link savedLocalUser} function that throws if no+ * one is logged in. A more appropriate name for this function, keeping in line+ * with the conventions the other methods follow, would've been+ * {@link ensureSavedLocalUser}. The shorter name is for readability.+ */+export const ensureLocalUser = (): LocalUser =>+ ensureExpectedLoggedInValue(savedLocalUser());++/**+ * A function throws an error if a value that is expected to be truthy when the+ * user is logged in is instead falsey.+ *+ * This is meant as a convenience wrapper to assert that a value we expect when+ * the user is logged in is indeed there.+ */+export const ensureExpectedLoggedInValue = <T>(t: T | undefined): T => {+ if (!t) throw new Error("Not logged in");+ return t;+};++/**+ * The user's various encrypted keys and their related attributes.+ *+ * - Attributes to derive the KEK, the (master) key encryption key.+ * - Encrypted master key (with KEK)+ * - Encrypted master key (with recovery key)+ * - Encrypted recovery key (with master key).+ * - Public key and encrypted private key (with master key).+ *+ * The various "key" attributes are base64 encoded representations of the+ * underlying binary data.+ *+ * [Note: Key attribute mutability]+ *+ * The key attributes contain two subsets:+ *+ * - Attributes that changes when the user changes their password. These are the+ * {@link UpdatedKeyAttr}.+ *+ * - All other attributes never change after initial setup.+ */+export interface KeyAttributes {+ /**+ * The user's master key encrypted with the key encryption key.+ *+ * Base64 encoded.+ *+ * [Note: Key encryption key]+ *+ * The user's master key is encrypted with a "key encryption key" (lovingly+ * called a "KEK" sometimes).+ *+ * The KEK itself is derived from the user's password.+ *+ * 1. User enters password on new device.+ *+ * 2. Client derives KEK from this password (using the {@link kekSalt},+ * {@link opsLimit} and {@link memLimit} as parameters for the+ * derivation).+ *+ * 3. Client use KEK to decrypt the master key from {@link encryptedKey} and+ * {@link keyDecryptionNonce}.+ */+ encryptedKey: string;+ /**+ * The nonce used during the encryption of the master key.+ *+ * Base64 encoded.+ *+ * @see {@link encryptedKey}.+ */+ keyDecryptionNonce: string;+ /**+ * The salt used during the derivation of the KEK.+ *+ * Base64 encoded.+ *+ * [Note: KEK three tuple]+ *+ * The three tuple (kekSalt, opsLimit, memLimit) is needed (along with the+ * user's password) to rederive the KEK when the user logs in on a new+ * client (See: [Note: Key encryption key]).+ *+ * The client can obtain these three by fetching their key attributes from+ * remote, however unless {@link isEmailMFAEnabled} is enabled (which is not+ * by default), then the user's credentials are verified using SRP instead+ * of email verification. So as a convenience for this (majority) flow,+ * remote also provides this exact same three tuple as part of the+ * {@link SRPAttributes} fetched from remote.+ *+ * So on remote the KEK three tuple is the same whether it be part of key+ * attributes or SRP attributes. When the user changes their password, both+ * of them also get updated simulataneously (they use the same storage).+ *+ * However, on the client side these two sets of three tuples might diverge+ * because of the client generating interactive key attributes. When that+ * happens, the locally saved key attributes will be overwritten by the KEK+ * three tuple for the new generated interactive KEK parameters, while the+ * SRP attributes will continue to reflect the "original" KEK three tuple we+ * got from remote.+ */+ kekSalt: string;+ /**+ * The operation limit used during the derivation of the KEK.+ *+ * The {@link opsLimit} and {@link memLimit} are complementary parameters+ * that define the amount of work done by the key derivation function. See+ * the {@link deriveKey}, {@link deriveSensitiveKey} and+ * {@link deriveInteractiveKey} functions for more detail about them.+ *+ * See: [Note: Key encryption key].+ */+ opsLimit: number;+ /**+ * The memory limit used during the derivation of the KEK.+ *+ * See {@link opsLimit} for more details.+ */+ memLimit: number;+ /**+ * The user's public key (part of their public-key keypair, the other half+ * being the {@link encryptedSecretKey}).+ *+ * Base64 encoded.+ */+ publicKey: string;+ /**+ * The user's private key (part of their public-key keypair, the other half+ * being the {@link publicKey}) encrypted with their master key.+ *+ * Base64 encoded.+ *+ * [Note: privateKey and secretKey]+ *+ * The nomenclature for the key pair follows libsodium's conventions+ * (https://doc.libsodium.org/public-key_cryptography/authenticated_encryption#key-pair-generation),+ * who possibly chose public + secret instead of public + private to avoid+ * confusion with shorthand notation (pk).+ *+ * However, the library author later changed their mind on this, so while+ * libsodium itself (the C library) and the documentation uses "secretKey",+ * the JavaScript implementation (libsodium.js) uses "privateKey".+ *+ * This structure uses the term "secretKey" since that is what the remote+ * protocol already was based on. Within the web app codebase, we use+ * "privateKey" since that is what the underlying libsodium.js uses.+ */+ encryptedSecretKey: string;+ /**+ * The nonce used during the encryption of {@link encryptedSecretKey}.+ */+ secretKeyDecryptionNonce: string;+ /**+ * The user's master key after being encrypted with their recovery key.+ *+ * Base64 encoded.+ *+ * This allows the user to recover their master key if they forget their+ * password but still have their recovery key.+ *+ * Note: This value doesn't change after being initially created.+ */+ masterKeyEncryptedWithRecoveryKey?: string;+ /**+ * The nonce used during the encryption of+ * {@link masterKeyEncryptedWithRecoveryKey}.+ *+ * Base64 encoded.+ */+ masterKeyDecryptionNonce?: string;+ /**+ * The user's recovery key after being encrypted with their master key.+ *+ * Base64 encoded.+ *+ * Note: This value doesn't change after being initially created.+ */+ recoveryKeyEncryptedWithMasterKey?: string;+ /**+ * The nonce used during the encryption of+ * {@link recoveryKeyEncryptedWithMasterKey}.+ *+ * Base64 encoded.+ */+ recoveryKeyDecryptionNonce?: string;+}++/**+ * Zod schema for {@link KeyAttributes}.+ */+export const RemoteKeyAttributes = z.object({+ kekSalt: z.string(),+ encryptedKey: z.string(),+ keyDecryptionNonce: z.string(),+ publicKey: z.string(),+ encryptedSecretKey: z.string(),+ secretKeyDecryptionNonce: z.string(),+ memLimit: z.number(),+ opsLimit: z.number(),+ masterKeyEncryptedWithRecoveryKey: z+ .string()+ .nullish()+ .transform(nullToUndefined),+ masterKeyDecryptionNonce: z.string().nullish().transform(nullToUndefined),+ recoveryKeyEncryptedWithMasterKey: z+ .string()+ .nullish()+ .transform(nullToUndefined),+ recoveryKeyDecryptionNonce: z.string().nullish().transform(nullToUndefined),+});++/**+ * A variant of {@link savedKeyAttributes} that throws if keyAttributes are not+ * present in local storage.+ */+export const ensureSavedKeyAttributes = (): KeyAttributes =>+ ensureExpectedLoggedInValue(savedKeyAttributes());++export interface GenerateKeysAndAttributesResult {+ masterKey: string;+ kek: string;+ keyAttributes: KeyAttributes;+}++/**+ * Generate a new set of key attributes.+ *+ * @param password The password to use for deriving the key encryption key.+ *+ * @returns a newly generated master key (base64 string), kek (base64 string)+ * and the key attributes associated with the combination.+ */+export async function generateKeysAndAttributes(+ password: string,+): Promise<GenerateKeysAndAttributesResult> {+ const masterKey = await generateKey();+ const recoveryKey = await generateKey();+ const {+ key: kek,+ salt: kekSalt,+ opsLimit,+ memLimit,+ } = await deriveSensitiveKey(password);++ const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =+ await encryptBox(masterKey, kek);+ const {+ encryptedData: masterKeyEncryptedWithRecoveryKey,+ nonce: masterKeyDecryptionNonce,+ } = await encryptBox(masterKey, recoveryKey);+ const {+ encryptedData: recoveryKeyEncryptedWithMasterKey,+ nonce: recoveryKeyDecryptionNonce,+ } = await encryptBox(recoveryKey, masterKey);++ const keyPair = await generateKeyPair();+ const {+ encryptedData: encryptedSecretKey,+ nonce: secretKeyDecryptionNonce,+ } = await encryptBox(keyPair.privateKey, masterKey);++ const keyAttributes: KeyAttributes = {+ encryptedKey,+ keyDecryptionNonce,+ kekSalt,+ opsLimit,+ memLimit,+ publicKey: keyPair.publicKey,+ encryptedSecretKey,+ secretKeyDecryptionNonce,+ masterKeyEncryptedWithRecoveryKey,+ masterKeyDecryptionNonce,+ recoveryKeyEncryptedWithMasterKey,+ recoveryKeyDecryptionNonce,+ };++ return { masterKey, kek, keyAttributes };+}++/**+ * Update or set the user's {@link KeyAttributes} on remote.+ */+export const putUserKeyAttributes = async (keyAttributes: KeyAttributes) =>+ ensureOk(+ await fetch(await apiURL("/users/attributes"), {+ method: "PUT",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ keyAttributes }),+ }),+ );++export interface RecoveryKeyAttributes {+ masterKeyEncryptedWithRecoveryKey: string;+ masterKeyDecryptionNonce: string;+ recoveryKeyEncryptedWithMasterKey: string;+ recoveryKeyDecryptionNonce: string;+}++/**+ * Update the encrypted recovery key attributes for the logged in user.+ *+ * In practice, this is not expected to be called and is meant as a rare+ * fallback for very old accounts created prior to recovery key related+ * attributes being assigned on account setup. Even for these, it'll be called+ * only once.+ */+export const putUserRecoveryKeyAttributes = async (+ recoveryKeyAttributes: RecoveryKeyAttributes,+) =>+ ensureOk(+ await fetch(await apiURL("/users/recovery-key"), {+ method: "PUT",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(recoveryKeyAttributes),+ }),+ );++/**+ * Ask remote to send a OTP / OTT to the given email to verify that the user has+ * access to it. Subsequent the app will pass this OTT back via the+ * {@link verifyOTT} method.+ *+ * @param email The email to verify.+ *+ * @param purpose In which context is the email being verified. Remote applies+ * additional business rules depending on this. For example, passing the purpose+ * "login" ensures that the OTT is only sent to an already registered email.+ *+ * In cases where the purpose is ambiguous (e.g. we're not sure if it is an+ * existing login or a new signup), the purpose can be set to `undefined`.+ */+export const sendOTT = async (+ email: string,+ purpose: "change" | "signup" | "login" | undefined,+) =>+ ensureOk(+ await fetch(await apiURL("/users/ott"), {+ method: "POST",+ headers: publicRequestHeaders(),+ body: JSON.stringify({ email, purpose }),+ }),+ );++/**+ * The response from remote on a successful user verification, either via+ * {@link verifyEmail} or {@link verifySRP}.+ *+ * The {@link id} is always present. The rest of the values are are optional+ * since only a subset of them will be returned depending on the case:+ *+ * 1. If the user has both passkeys and TOTP based second factor enabled, then+ * the following will be set:+ * - {@link passkeySessionID}, {@link accountsUrl}+ * - {@link twoFactorSessionIDV2}+ *+ * 2. If the user has only passkeys enabled, then the following will be set:+ * - {@link passkeySessionID}, {@link accountsUrl}+ *+ * 3. If the user has only TOTP based second factor enabled, then the following+ * will be set:+ * - {@link twoFactorSessionID}+ *+ * 4. If the user doesn't have any second factor, but has already setup their+ * key attributes, then the following will be set:+ * - {@link keyAttributes}+ * - {@link encryptedToken}+ *+ * 5. Finally, in the rare case that the user has not yet setup their key+ * attributes, then the following will be set:+ * - {@link token}+ */+export interface EmailOrSRPVerificationResponse {+ /**+ * The user's ID.+ */+ id: number;+ /**+ * The user's key attributes.+ *+ * These will be set (along with the {@link encryptedToken}) if the user+ * does not have a second factor.+ */+ keyAttributes?: KeyAttributes;+ /**+ * The base64 representation of an encrypted auth token, encrypted using the+ * user's public key.+ *+ * These will be set (along with the {@link keyAttributes}) if the user+ * does not have a second factor.+ */+ encryptedToken?: string;+ /**+ * The base64 representation of an auth token.+ *+ * This will be set in the rare edge case for when the user has not yet+ * setup their key attributes.+ */+ token?: string;+ /**+ * A session ID that can be used to complete the TOTP based second factor.+ *+ * This will be set if the user has enabled a TOTP based second factor but+ * has not enabled passkeys.+ */+ twoFactorSessionID?: string;+ /**+ * A session ID that can be used to complete passkey verification.+ *+ * This will be set if the user has added a passkey to their account.+ */+ passkeySessionID?: string;+ /**+ * Base URL for the accounts app where we should redirect to for passkey+ * verification.+ *+ * This will only be set if the user has setup a passkey (i.e., whenever+ * {@link passkeySessionID} is defined).+ */+ accountsUrl?: string;+ /**+ * A session ID that can be used to complete the TOTP based second fator.+ *+ * This will be set in lieu of {@link twoFactorSessionID} if the user has+ * setup both passkeys and TOTP based two factors are enabled for their+ * account.+ *+ * ---+ *+ * Historical context: {@link twoFactorSessionIDV2} is only set if user has+ * both passkey and two factor enabled. This is to ensure older clients keep+ * using passkey flow when both are set. It is intended to be removed once+ * all clients starts surfacing both options for performing 2FA.+ *+ * See also {@link useSecondFactorChoiceIfNeeded}.+ */+ twoFactorSessionIDV2?: string;+}++/**+ * Zod schema for the {@link EmailOrSRPVerificationResponse} type.+ *+ * See: [Note: Duplicated Zod schema and TypeScript type]+ */+const RemoteEmailOrSRPVerificationResponse = z.object({+ id: z.number(),+ keyAttributes: RemoteKeyAttributes.nullish().transform(nullToUndefined),+ encryptedToken: z.string().nullish().transform(nullToUndefined),+ token: z.string().nullish().transform(nullToUndefined),+ twoFactorSessionID: z.string().nullish().transform(nullToUndefined),+ passkeySessionID: z.string().nullish().transform(nullToUndefined),+ accountsUrl: z.string().nullish().transform(nullToUndefined),+ twoFactorSessionIDV2: z.string().nullish().transform(nullToUndefined),+});++/**+ * A specialization of {@link RemoteEmailOrSRPVerificationResponse} for SRP+ * verification, which results in the {@link srpM2} field in addition to the+ * other ones.+ *+ * The declaration conceptually belongs to `srp.ts`, but is here to avoid cyclic+ * dependencies.+ */+export const RemoteSRPVerificationResponse = z.object({+ ...RemoteEmailOrSRPVerificationResponse.shape,+ /**+ * The SRP M2 (evidence message), the proof that the server has the+ * verifier.+ */+ srpM2: z.string(),+});++/**+ * Verify user's access to the given {@link email} by comparing the OTT that+ * remote previously sent to that email.+ *+ * @param email The email to verify.+ *+ * @param ott The OTT that the user entered.+ *+ * @param source During signup, we ask the user the referral "source" through+ * which they heard about Ente. When present (i.e. during signup, and if the+ * user indeed provided it), that source should be passed as this parameter.+ */+export const verifyEmail = async (+ email: string,+ ott: string,+ source: string | undefined,+): Promise<EmailOrSRPVerificationResponse> => {+ const res = await fetch(await apiURL("/users/verify-email"), {+ method: "POST",+ headers: publicRequestHeaders(),+ body: JSON.stringify({ email, ott, ...(source && { source }) }),+ });+ ensureOk(res);+ return RemoteEmailOrSRPVerificationResponse.parse(await res.json());+};++/**+ * Log the user out on remote, if possible and needed.+ */+export const remoteLogoutIfNeeded = async () => {+ if (!(await savedAuthToken())) {+ // If the logout is attempted during the login / signup flow itself,+ // then we won't have an auth token. Handle that gracefully.+ return;+ }++ const res = await fetch(await apiURL("/users/logout"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ });+ if (res.status == 401) {+ // Ignore if we get a 401 Unauthorized, this is expected to happen on+ // token expiry.+ return;+ }++ ensureOk(res);+};++/**+ * Generate a new local-only KEK (key encryption key) suitable for interactive+ * use and update the locally saved key attributes to reflect it.+ *+ * See {@link deriveInteractiveKey} for more details.+ *+ * In brief, after the initial password verification, we create a new+ * inetractive KEK derived from the same password as the original KEK, but with+ * so called interactive mem and ops limits which result in a noticeably faster+ * key derivation.+ *+ * We then overwrite the encrypted master key, encryption nonce and the KEK+ * derivation parameters (see: [Note: KEK three tuple]) in the locally persisted+ * {@link KeyAttributes} so that these interactive parameters get used+ * subsequent reauthentication.+ *+ * These are more ergonomic for the user especially in the web app where they+ * need to enter their password to access their masterKey when repopening the+ * app in a new tab (on desktop we can avoid this by using OS storage, see+ * [Note: Safe storage and interactive KEK attributes]).+ *+ * @param password The user's password.+ *+ * @param keyAttributes The existing "original" key attributes, which we+ * might've generated locally (new signup) or fetched from remote (existing+ * login).+ *+ * @param masterKey The user's master key (base64 encoded).+ *+ * @returns the update key attributes.+ */+export const generateAndSaveInteractiveKeyAttributes = async (+ password: string,+ keyAttributes: KeyAttributes,+ key: string,+): Promise<KeyAttributes> => {+ const {+ key: interactiveKEK,+ salt: kekSalt,+ opsLimit,+ memLimit,+ } = await deriveInteractiveKey(password);++ const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =+ await encryptBox(key, interactiveKEK);++ const interactiveKeyAttributes = {+ ...keyAttributes,+ encryptedKey,+ keyDecryptionNonce,+ kekSalt,+ opsLimit,+ memLimit,+ };+ saveKeyAttributes(interactiveKeyAttributes);+ return interactiveKeyAttributes;+};++/**+ * Change the email associated with the user's account (both locally and on+ * remote)+ *+ * @param email The new email.+ *+ * @param ott The verification code that was sent to the new email.+ */+export const changeEmail = async (email: string, ott: string) => {+ await postChangeEmail(email, ott);+ updateSavedLocalUser({ email });+};++/**+ * Change the email associated with the user's account on remote.+ */+const postChangeEmail = async (email: string, ott: string) =>+ ensureOk(+ await fetch(await apiURL("/users/change-email"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ email, ott }),+ }),+ );++/**+ * Change the user's password on both remote and locally.+ *+ * @param password The new password.+ */+export const changePassword = async (password: string) => {+ const user = ensureLocalUser();+ const masterKey = await ensureMasterKeyFromSession();+ const keyAttributes = ensureSavedKeyAttributes();++ // Generate new KEK.+ const {+ key: kek,+ salt: kekSalt,+ opsLimit,+ memLimit,+ } = await deriveSensitiveKey(password);++ // Generate new key attributes.+ const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =+ await encryptBox(masterKey, kek);+ const updatedKeyAttr: UpdatedKeyAttr = {+ encryptedKey,+ keyDecryptionNonce,+ kekSalt,+ opsLimit,+ memLimit,+ };++ // Update SRP and key attributes on remote.+ await updateSRPAndKeyAttributes(+ await generateSRPSetupAttributes(kek),+ updatedKeyAttr,+ );++ // Update SRP attributes locally.+ await getAndSaveSRPAttributes(user.email);++ const srpAttributes = await getSRPAttributes(user.email);+ saveSRPAttributes(ensure(srpAttributes));++ // Update key attributes locally, generating a new interactive kek while+ // we're at it.+ await generateAndSaveInteractiveKeyAttributes(+ password,+ { ...keyAttributes, ...updatedKeyAttr },+ masterKey,+ );+};++/**+ * Update the {@link id} and {@link encryptedToken} present in the saved partial+ * local user.+ *+ * This function removes the {@link token}, if any, present in the saved partial+ * local user and sets the provided {@link encryptedToken}.+ *+ * It is expected that the code will subsequently redirect to "/credentials",+ * which should call {@link decryptAndStoreTokenIfNeeded} which will decrypt the+ * newly set {@link encryptedToken} and write out the decrypted value as the+ * {@link token} in the saved local user.+ *+ * @param userID The ID of the user whose token this is. This is also saved to+ * the partial local user (after doing a sanity check that we're not replacing+ * partial data with a different userID).+ *+ * @param encryptedToken The newly obtained base64 encoded encrypted token from+ * remote (e.g. as a result of the user verifying their email).+ */+export const resetSavedLocalUserTokens = async (+ userID: number,+ encryptedToken: string,+) => {+ const user = savedPartialLocalUser();+ if (user?.id && user.id != userID) {+ throw new Error(`User ID mismatch (${user.id}, ${userID})`);+ }+ replaceSavedLocalUser({+ ...user,+ id: userID,+ token: undefined,+ encryptedToken,+ });+ return removeAuthToken();+};++/**+ * Decrypt the user's {@link encryptedToken}, if present, and use it to update+ * both the locally saved user and the KV DB.+ *+ * @param keyAttributes The user's key attributes.+ *+ * @param masterKey The user's master key (base64 encoded).+ */+export const decryptAndStoreTokenIfNeeded = async (+ keyAttributes: KeyAttributes,+ masterKey: string,+) => {+ const { encryptedToken } = savedPartialLocalUser() ?? {};+ if (!encryptedToken) return;++ const { encryptedSecretKey, secretKeyDecryptionNonce, publicKey } =+ keyAttributes;+ const privateKey = await decryptBox(+ { encryptedData: encryptedSecretKey, nonce: secretKeyDecryptionNonce },+ masterKey,+ );++ const token = await toB64URLSafe(+ await boxSealOpenBytes(encryptedToken, { publicKey, privateKey }),+ );++ updateSavedLocalUser({ token, encryptedToken: undefined });+ return saveAuthToken(token);+};++const TwoFactorSecret = z.object({+ /**+ * The 2FA secret code.+ */+ secretCode: z.string(),+ /**+ * A base64 encoded "image/png".+ */+ qrCode: z.string(),+});++export type TwoFactorSecret = z.infer<typeof TwoFactorSecret>;++/**+ * Start a TOTP based two factor setup process by fetching a secret code (and+ * the corresponding QR code) from remote.+ *+ * Once the user provides us with a TOTP generated using the provided secret, we+ * can finish the setup with {@link setupTwoFactorFinish}.+ */+export const setupTwoFactor = async (): Promise<TwoFactorSecret> => {+ const res = await fetch(await apiURL("/users/two-factor/setup"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return TwoFactorSecret.parse(await res.json());+};++/**+ * Finish the TOTP based two factor setup by provided a previously obtained+ * secret (using {@link setupTwoFactor}) and the current TOTP generated using+ * that secret.+ *+ * This updates both the state both locally and on remote.+ *+ * @param secretCode The value of {@link secretCode} from the+ * {@link TwoFactorSecret} obtained by {@link setupTwoFactor}.+ *+ * @param totp The current TOTP corresponding to {@link secretCode}.+ */+export const setupTwoFactorFinish = async (+ secretCode: string,+ totp: string,+) => {+ const box = await encryptBox(secretCode, await getUserRecoveryKey());+ await enableTwoFactor({+ code: totp,+ encryptedTwoFactorSecret: box.encryptedData,+ twoFactorSecretDecryptionNonce: box.nonce,+ });+ updateSavedLocalUser({ isTwoFactorEnabled: true });+};++interface EnableTwoFactorRequest {+ /**+ * The current value of the TOTP corresponding to the two factor {@link+ * secretCode} obtained from a previous call to {@link setupTwoFactor}.+ */+ code: string;+ /**+ * The {@link secretCode} encrypted with the user's recovery key.+ *+ * This is used in the case of second factor recovery.+ */+ encryptedTwoFactorSecret: string;+ /**+ * The nonce that was used when encrypting {@link encryptedTwoFactorSecret}.+ */+ twoFactorSecretDecryptionNonce: string;+}++/**+ * Enable the TOTP based two factor for the user by providing the current 2FA+ * code corresponding the two factor secret, and encrypted secrets for future+ * recovery (if needed).+ */+const enableTwoFactor = async (req: EnableTwoFactorRequest) =>+ ensureOk(+ await fetch(await apiURL("/users/two-factor/enable"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(req),+ }),+ );++/**+ * The result of a successful two factor verification (TOTP or passkey),+ * recovery removal (TOTP) or recovery bypass (passkey).+ */+export const TwoFactorAuthorizationResponse = z.object({+ /**+ * The user's ID.+ */+ id: z.number(),+ /**+ * The user's key attributes.+ */+ keyAttributes: RemoteKeyAttributes,+ /**+ * A encrypted auth token.+ */+ encryptedToken: z.string(),+});++export type TwoFactorAuthorizationResponse = z.infer<+ typeof TwoFactorAuthorizationResponse+>;++export const verifyTwoFactor = async (+ code: string,+ sessionID: string,+): Promise<TwoFactorAuthorizationResponse> => {+ const res = await fetch(await apiURL("/users/two-factor/verify"), {+ method: "POST",+ headers: publicRequestHeaders(),+ body: JSON.stringify({ code, sessionID }),+ });+ ensureOk(res);+ return TwoFactorAuthorizationResponse.parse(await res.json());+};++/** The type of the second factor we're trying to act on */+export type TwoFactorType = "totp" | "passkey";++const TwoFactorRecoveryResponse = z.object({+ /**+ * The recovery secret, encrypted using the user's recovery key.+ */+ encryptedSecret: z.string(),+ /**+ * The nonce used during encryption of {@link encryptedSecret}.+ */+ secretDecryptionNonce: z.string(),+});++export type TwoFactorRecoveryResponse = z.infer<+ typeof TwoFactorRecoveryResponse+>;++/**+ * Initiate second factor reset or bypass by requesting the encrypted second+ * factor recovery secret (and nonce) from remote. The user can then decrypt+ * these using their recovery key to reset or bypass their second factor.+ *+ * @param twoFactorType The type of second factor to reset or bypass.+ *+ * @param sessionID A two factor session ID ({@link twoFactorSessionID} or+ * {@link passkeySessionID}) for the user.+ *+ * [Note: Second factor recovery]+ *+ * 1. When setting up a TOTP based second factor, client sends a (encrypted 2fa+ * recovery secret, nonce) pair to remote. This is a randomly generated+ * secret (and nonce) encrypted using the user's recovery key.+ *+ * 2. Similarly, when setting up a passkey as the second factor, the client+ * sends a encrypted recovery secret (see {@link configurePasskeyRecovery}).+ *+ * 3. When the user wishes to reset or bypass their second factor, the client+ * asks remote for these encrypted secrets (using {@link getRecoverTwoFactor}).+ *+ * 4. User then enters their recovery key, which the client uses to decrypt the+ * recovery secret and provide it back to remote for verification (using+ * {@link removeTwoFactor}).+ *+ * 5. If the recovery secret matches, then remote resets (TOTP based) or bypass+ * (passkey based) the user's second factor.+ */+export const getRecoverTwoFactor = async (+ twoFactorType: TwoFactorType,+ sessionID: string,+): Promise<TwoFactorRecoveryResponse> => {+ const res = await fetch(+ await apiURL("/users/two-factor/recover", { twoFactorType, sessionID }),+ { headers: publicRequestHeaders() },+ );+ ensureOk(res);+ return TwoFactorRecoveryResponse.parse(await res.json());+};++/**+ * Finish the second factor recovery / bypass initiated by+ * {@link getRecoverTwoFactor} using the provided recovery key mnemonic entered+ * by the user.+ *+ * See: [Note: Second factor recovery].+ *+ * This completes the recovery process both locally, and on remote.+ *+ * @param twoFactorType The second factor type (same value as what would've been+ * passed to {@link getRecoverTwoFactor} for obtaining+ * {@link recoveryResponse}).+ *+ * @param sessionID The second factor session ID (same value as what would've+ * been passed to {@link getRecoverTwoFactor} for obtaining+ * {@link recoveryResponse}).+ *+ * @param recoveryResponse The response to a previous call to+ * {@link getRecoverTwoFactor}.+ *+ * @param recoveryKeyMnemonic The 24-word BIP-39 recovery key mnemonic provided+ * by the user to complete recovery.+ */+export const recoverTwoFactorFinish = async (+ twoFactorType: TwoFactorType,+ sessionID: string,+ recoveryResponse: TwoFactorRecoveryResponse,+ recoveryKeyMnemonic: string,+) => {+ const { encryptedSecret: encryptedData, secretDecryptionNonce: nonce } =+ recoveryResponse;+ const twoFactorSecret = await decryptBox(+ { encryptedData, nonce },+ await recoveryKeyFromMnemonic(recoveryKeyMnemonic),+ );+ const { id, keyAttributes, encryptedToken } = await removeTwoFactor(+ twoFactorType,+ sessionID,+ twoFactorSecret,+ );+ await resetSavedLocalUserTokens(id, encryptedToken);+ updateSavedLocalUser({+ isTwoFactorEnabled: undefined,+ twoFactorSessionID: undefined,+ passkeySessionID: undefined,+ });+ if (twoFactorType == "passkey") clearInflightPasskeySessionID();+ saveKeyAttributes(keyAttributes);+};++const removeTwoFactor = async (+ twoFactorType: TwoFactorType,+ sessionID: string,+ secret: string,+): Promise<TwoFactorAuthorizationResponse> => {+ const res = await fetch(await apiURL("/users/two-factor/remove"), {+ method: "POST",+ headers: publicRequestHeaders(),+ body: JSON.stringify({ twoFactorType, sessionID, secret }),+ });+ ensureOk(res);+ return TwoFactorAuthorizationResponse.parse(await res.json());+};diff --git a/web/apps/albums/vendor/ente-base/app.ts b/web/apps/albums/vendor/ente-base/app.tsnew file mode 100644index 0000000000..0556caaca9--- /dev/null+++ b/web/apps/albums/vendor/ente-base/app.ts@@ -0,0 +1,130 @@+export const appNames = [+ "accounts",+ "albums",+ "auth",+ "cast",+ "embed",+ "share",+ "photos",+ "ensu",+ "locker",+] as const;++/**+ * Arbitrary names that we used as keys for indexing various constants+ * corresponding to our apps that rely on this package.+ */+export type AppName = (typeof appNames)[number];++/**+ * The unique key for the app.+ *+ * This is the name of the Ente app which we're currently running as. It is used+ * as a key for various properties that are different across apps.+ *+ * Parts of our code are shared across apps. Some parts of them also run in+ * non-main thread execution contexts like web workers. So there isn't always an+ * easy way to figure out what the current app is.+ *+ * To solve this, we inject the app name during the build process. This is+ * available to all our code (shared packages, web workers).+ *+ * This constant employs an `as` cast to avoid incurring a dynamic check, and as+ * such may be incorrect (e.g. when a new app gets added). So apps should+ * dynamically validate and log it once somewhere during init.+ */+export const appName: AppName = process.env.appName as AppName;++/**+ * True if we're running in our desktop app.+ *+ * This is similar to checking for `globalThis.electron`, however the advantage+ * of this check is that it will also work inside web workers (whose globalThis+ * won't have an electron object defined).+ *+ * This check can still have false positives during dev mode if someone connects+ * their browser to port where the desktop app's web app is being served from in+ * dev mode. If in the future some code needs to definitely rule out those false+ * positives, it'd need a runtime check of the form+ * `navigator.userAgent.includes("Electron")`.+ */+export const isDesktop = process.env.isDesktop == "1";++/**+ * Version of the desktop app.+ *+ * This is only defined when {@link isDesktop} is true.+ */+export const desktopAppVersion = process.env.desktopAppVersion;++/**+ * Static (English) title for the app.+ *+ * This is shown until we have the localized version.+ */+export const staticAppTitle = {+ accounts: "Ente Accounts",+ albums: "Ente Photos",+ auth: "Ente Auth",+ cast: "Ente Photos",+ embed: "Ente Photos",+ share: "Ente Locker",+ photos: "Ente Photos",+ // Ensu (chat) web app.+ ensu: "Ensu",+ locker: "Ente Locker",+}[appName];++/**+ * Client "package names" for our app.+ *+ * The package name is used as the "X-Client-Package" header in API requests.+ *+ * In cases where this code works for both a web and a desktop app for the same+ * app (currently only photos), this will be the platform specific package name.+ */+export const clientPackageName = (() => {+ if (isDesktop) {+ if (appName === "photos") return "io.ente.photos.desktop";+ if (appName === "ensu") return "io.ente.ensu.desktop";+ throw new Error(`Unsupported desktop appName ${appName}`);+ }+ return {+ accounts: "io.ente.accounts.web",+ albums: "io.ente.albums.web",+ auth: "io.ente.auth.web",+ cast: "io.ente.cast.web",+ embed: "io.ente.photos.web", // Use photos package name for embed app+ share: "io.ente.share.web",+ photos: "io.ente.photos.web",+ // Ensu (chat) web app.+ ensu: "io.ente.ensu",+ locker: "io.ente.locker.web",+ }[appName];+})();++/**+ * The client package name, augmented with the client version where applicable.+ *+ * This string is used as the "client identifier" in payloads (e.g. ML data+ * generated by a client).+ *+ * For the desktop app, it will be client package name and version. Otherwise,+ * it'll just be the same as {@link clientPackageName}.+ */+export const clientIdentifier = (() => {+ if (isDesktop) {+ if (!desktopAppVersion)+ throw new Error(`desktopAppVersion is not defined`);++ if (appName === "photos") {+ return `io.ente.photos.desktop/${desktopAppVersion}`;+ }+ if (appName === "ensu") {+ return `io.ente.ensu.desktop/${desktopAppVersion}`;+ }++ throw new Error(`Unsupported desktop appName ${appName}`);+ }+ return clientPackageName;+})();diff --git a/web/apps/albums/vendor/ente-base/assert.ts b/web/apps/albums/vendor/ente-base/assert.tsnew file mode 100644index 0000000000..6f4743e7db--- /dev/null+++ b/web/apps/albums/vendor/ente-base/assert.ts@@ -0,0 +1,15 @@+import { isDevBuild } from "./env";+import log from "./log";++/**+ * If running in a dev build, throw an exception with the given message.+ * Otherwise log it as a warning.+ *+ * @param message An optional message to use for the failure. If not provided,+ * then a generic one is used.+ */+export const assertionFailed = (message?: string) => {+ message = message ?? "Assertion failed";+ if (isDevBuild) throw new Error(message);+ log.warn(message);+};diff --git a/web/apps/albums/vendor/ente-base/blob-cache.ts b/web/apps/albums/vendor/ente-base/blob-cache.tsnew file mode 100644index 0000000000..c64ff317a4--- /dev/null+++ b/web/apps/albums/vendor/ente-base/blob-cache.ts@@ -0,0 +1,244 @@+import { isDesktop } from "./app";++const blobCacheNames = [+ "thumbs",+ "face-crops",+ // Desktop app only+ "files",+] as const;++/**+ * Namespaces into which our blob caches are divided+ *+ * Note that namespaces are just arbitrary (but predefined) strings to split the+ * cached data into "folders", so to speak.+ * */+export type BlobCacheNamespace = (typeof blobCacheNames)[number];++/**+ * A namespaced blob cache.+ *+ * This cache is suitable for storing large amounts of data (entire files).+ *+ * To obtain a cache for a given namespace, use {@link openBlobCache}. To clear all+ * cached data (e.g. during logout), use {@link clearBlobCaches}.+ *+ * [Note: Caching files]+ *+ * The underlying implementation of the cache is different depending on the+ * runtime environment.+ *+ * * The preferred implementation, and the one that is used when we're running+ * in a browser, is to use the standard [Web+ * Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache).+ *+ * * However when running under Electron (when this code runs as part of our+ * desktop app), a custom OPFS based cache is used instead. This is because+ * Electron currently doesn't support using standard Web Cache API for data+ * served by a custom protocol handler (See this+ * [issue](https://github.com/electron/electron/issues/35033), and the+ * underlying restriction that comes from+ * [Chromium](https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/modules/cache_storage/cache.cc;l=83-87?q=%22Request%20scheme%20%27%22&ss=chromium))+ *+ * [OPFS](https://web.dev/articles/origin-private-file-system) stands for Origin+ * Private File System. It is a recent API that allows a web site to store+ * reasonably large amounts of data. One option (that may still become possible+ * in the future) was to always use OPFS for caching instead of this dual+ * implementation, however currently [Safari does not support writing to OPFS+ * outside of web+ * workers](https://webkit.org/blog/12257/the-file-system-access-api-with-origin-private-file-system/)+ * ([the WebKit bug](https://bugs.webkit.org/show_bug.cgi?id=231706)), so it's+ * not trivial to use this as a full on replacement of the Web Cache in the+ * browser. So for now we go with this split implementation.+ */+export interface BlobCache {+ /**+ * Get the data corresponding to {@link key} (if found) from the cache.+ */+ get: (key: string) => Promise<Blob | undefined>;+ /**+ * Check if there is an item corresponding to {@link key} in the cache.+ */+ has: (key: string) => Promise<boolean>;+ /**+ * Add the given {@link key}-value ({@link blob}) pair to the cache.+ */+ put: (key: string, blob: Blob) => Promise<void>;+ /**+ * Delete the blob corresponding to the given {@link key}.+ *+ * The returned promise resolves to `true` if a cache entry was found,+ * otherwise it resolves to `false`.+ * */+ delete: (key: string) => Promise<boolean>;+}++const cachedCaches = new Map<BlobCacheNamespace, BlobCache>();++/**+ * Return the {@link BlobCache} corresponding to the given {@link name}.+ *+ * This is a wrapper over {@link openBlobCache} that caches (pun intended) the+ * cache and returns the same one each time it is called with the same name.+ * It'll open the cache lazily the first time it is invoked.+ */+export const blobCache = async (+ name: BlobCacheNamespace,+): Promise<BlobCache> => {+ let c = cachedCaches.get(name);+ if (!c) cachedCaches.set(name, (c = await openBlobCache(name)));+ return c;+};++/**+ * Create a new {@link BlobCache} corresponding to the given {@link name}.+ *+ * @param name One of the arbitrary but predefined namespaces of type+ * {@link BlobCacheNamespace} which group related data and allow us to use the+ * same key across namespaces.+ */+export const openBlobCache = async (+ name: BlobCacheNamespace,+): Promise<BlobCache> =>+ isDesktop ? openOPFSCacheWeb(name) : openWebCache(name);++/**+ * [Note: ArrayBuffer vs Blob vs Uint8Array]+ *+ * ArrayBuffers are in memory, while blobs are unreified, and can directly point+ * to on disk objects too.+ *+ * If we are just passing data around without necessarily needing to manipulate+ * it, and we already have a blob, it's best to just pass that blob. Further,+ * blobs also retains the file's encoding information , and are thus a layer+ * above array buffers which are just raw byte sequences.+ *+ * ArrayBuffers are not directly manipulatable, which is where some sort of a+ * typed array or a data view comes into the picture. The typed `Uint8Array` is+ * a common way.+ *+ * To convert from ArrayBuffer to Uint8Array,+ *+ * new Uint8Array(arrayBuffer)+ *+ * Blobs are immutable, but a usual scenario is storing an entire file in a+ * blob, and when the need comes to display it, we can obtain a URL for it using+ *+ * URL.createObjectURL(blob)+ *+ * Also note that a File is a Blob!+ *+ * To convert from a Blob to ArrayBuffer+ *+ * await blob.arrayBuffer()+ *+ * To convert from a Blob to Uint8Array, chain the two steps+ *+ * new Uint8Array(await blob.arrayBuffer())+ *+ * To convert from an ArrayBuffer or Uint8Array to Blob+ *+ * new Blob([arrayBuffer, andOrAnyArray, andOrstring])+ *+ * To convert from a Uint8Array/ArrayBuffer/Blob to a ReadableStream+ *+ * new Response(array).body+ * OR+ * new Blob([...]).stream()+ *+ * To convert from a stream to a string (or JSON)+ *+ * await new Response(stream).text()+ * await new Response(stream).json()+ *+ * Refs:+ * - https://github.com/yigitunallar/arraybuffer-vs-blob+ * - https://stackoverflow.com/questions/11821096/what-is-the-difference-between-an-arraybuffer-and-a-blob+ */++/** An implementation of {@link BlobCache} using Web Cache APIs */+const openWebCache = async (name: BlobCacheNamespace) => {+ const cache = await caches.open(name);+ return {+ get: async (key: string) => {+ const res = await cache.match(key);+ return await res?.blob();+ },+ has: async (key: string) => cache.match(key).then((v) => !!v),+ put: (key: string, blob: Blob) => cache.put(key, new Response(blob)),+ delete: (key: string) => cache.delete(key),+ };+};++/** An implementation of {@link BlobCache} using OPFS */+const openOPFSCacheWeb = async (name: BlobCacheNamespace) => {+ // While all major browsers support OPFS now, their implementations still+ // have various quirks. However, we don't need to handle all possible cases+ // and can just instead use the APIs and guarantees Chromium provides since+ // this code will only run in our Electron app (which'll use Chromium as the+ // renderer).+ //+ // So for our purpose, these can serve as the doc for what's available:+ // https://web.dev/articles/origin-private-file-system++ const root = await navigator.storage.getDirectory();+ const caches = await root.getDirectoryHandle("cache", { create: true });+ const cache = await caches.getDirectoryHandle(name, { create: true });++ return {+ get: async (key: string) => {+ try {+ const fileHandle = await cache.getFileHandle(key);+ return await fileHandle.getFile();+ } catch (e) {+ if (e instanceof DOMException && e.name == "NotFoundError")+ return undefined;+ throw e;+ }+ },+ has: async (key: string) => {+ try {+ await cache.getFileHandle(key);+ return true;+ } catch (e) {+ if (e instanceof DOMException && e.name == "NotFoundError")+ return false;+ throw e;+ }+ },+ put: async (key: string, blob: Blob) => {+ const fileHandle = await cache.getFileHandle(key, { create: true });+ const writable = await fileHandle.createWritable();+ await writable.write(blob);+ await writable.close();+ },+ delete: async (key: string) => {+ try {+ await cache.removeEntry(key);+ return true;+ } catch (e) {+ if (e instanceof DOMException && e.name == "NotFoundError")+ return false;+ throw e;+ }+ },+ };+};++/**+ * Delete all cached data, including cached caches.+ *+ * Meant for use during logout, to reset the state of the user's account.+ */+export const clearBlobCaches = async () => {+ cachedCaches.clear();+ return isDesktop ? clearOPFSCaches() : clearWebCaches();+};++const clearWebCaches = () =>+ Promise.all(blobCacheNames.map((name) => caches.delete(name)));++const clearOPFSCaches = async () => {+ const root = await navigator.storage.getDirectory();+ await root.removeEntry("cache", { recursive: true });+};diff --git a/web/apps/albums/vendor/ente-base/components/EnteLogo.tsx b/web/apps/albums/vendor/ente-base/components/EnteLogo.tsxnew file mode 100644index 0000000000..1d77de41fc--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/EnteLogo.tsx@@ -0,0 +1,48 @@+import { styled } from "@mui/material";+import React from "react";++interface EnteLogoProps {+ /**+ * The height of the logo image, in pixels.+ *+ * Default: 18px+ */+ height?: number;+}++/**+ * The Ente logo ("ente" in Montserrat), as an inline SVG.+ *+ * Having it as an inline SVG has two advantages:+ *+ * - It does not rely on a corresponding asset in the public folder+ * - It can be styled using CSS.+ *+ * The default height of the SVG element is 18px. The size can be customized by+ * providing a {@link height} prop: the SVG will preserve its aspect ratio when+ * fitting inside the provided viewport.+ */+export const EnteLogo: React.FC<EnteLogoProps> = ({ height }) => (+ <svg+ height={height ?? "18"}+ viewBox="0 0 43 13"+ fill="currentColor"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path d="M6.102 12.144C4.998 12.144 4.026 11.928 3.186 11.496C2.358 11.064 1.716 10.476 1.26 9.732C0.804 8.976 0.576 8.118 0.576 7.158C0.576 6.186 0.798 5.328 1.242 4.584C1.698 3.828 2.316 3.24 3.096 2.82C3.876 2.388 4.758 2.172 5.742 2.172C6.69 2.172 7.542 2.376 8.298 2.784C9.066 3.18 9.672 3.756 10.116 4.512C10.56 5.256 10.782 6.15 10.782 7.194C10.782 7.302 10.776 7.428 10.764 7.572C10.752 7.704 10.74 7.83 10.728 7.95H2.862V6.312H9.252L8.172 6.798C8.172 6.294 8.07 5.856 7.866 5.484C7.662 5.112 7.38 4.824 7.02 4.62C6.66 4.404 6.24 4.296 5.76 4.296C5.28 4.296 4.854 4.404 4.482 4.62C4.122 4.824 3.84 5.118 3.636 5.502C3.432 5.874 3.33 6.318 3.33 6.834V7.266C3.33 7.794 3.444 8.262 3.672 8.67C3.912 9.066 4.242 9.372 4.662 9.588C5.094 9.792 5.598 9.894 6.174 9.894C6.69 9.894 7.14 9.816 7.524 9.66C7.92 9.504 8.28 9.27 8.604 8.958L10.098 10.578C9.654 11.082 9.096 11.472 8.424 11.748C7.752 12.012 6.978 12.144 6.102 12.144ZM18.5375 2.172C19.3055 2.172 19.9895 2.328 20.5895 2.64C21.2015 2.94 21.6815 3.408 22.0295 4.044C22.3775 4.668 22.5515 5.472 22.5515 6.456V12H19.7435V6.888C19.7435 6.108 19.5695 5.532 19.2215 5.16C18.8855 4.788 18.4055 4.602 17.7815 4.602C17.3375 4.602 16.9355 4.698 16.5755 4.89C16.2275 5.07 15.9515 5.352 15.7475 5.736C15.5555 6.12 15.4595 6.612 15.4595 7.212V12H12.6515V2.316H15.3335V4.998L14.8295 4.188C15.1775 3.54 15.6755 3.042 16.3235 2.694C16.9715 2.346 17.7095 2.172 18.5375 2.172ZM29.0568 12.144C27.9168 12.144 27.0288 11.856 26.3928 11.28C25.7568 10.692 25.4388 9.822 25.4388 8.67V0.174H28.2468V8.634C28.2468 9.042 28.3548 9.36 28.5708 9.588C28.7868 9.804 29.0808 9.912 29.4528 9.912C29.8968 9.912 30.2748 9.792 30.5868 9.552L31.3428 11.532C31.0548 11.736 30.7068 11.892 30.2988 12C29.9028 12.096 29.4888 12.144 29.0568 12.144ZM23.9448 4.692V2.532H30.6588V4.692H23.9448ZM37.4262 12.144C36.3222 12.144 35.3502 11.928 34.5102 11.496C33.6822 11.064 33.0402 10.476 32.5842 9.732C32.1282 8.976 31.9002 8.118 31.9002 7.158C31.9002 6.186 32.1222 5.328 32.5662 4.584C33.0222 3.828 33.6402 3.24 34.4202 2.82C35.2002 2.388 36.0822 2.172 37.0662 2.172C38.0142 2.172 38.8662 2.376 39.6222 2.784C40.3902 3.18 40.9962 3.756 41.4402 4.512C41.8842 5.256 42.1062 6.15 42.1062 7.194C42.1062 7.302 42.1002 7.428 42.0882 7.572C42.0762 7.704 42.0642 7.83 42.0522 7.95H34.1862V6.312H40.5762L39.4962 6.798C39.4962 6.294 39.3942 5.856 39.1902 5.484C38.9862 5.112 38.7042 4.824 38.3442 4.62C37.9842 4.404 37.5642 4.296 37.0842 4.296C36.6042 4.296 36.1782 4.404 35.8062 4.62C35.4462 4.824 35.1642 5.118 34.9602 5.502C34.7562 5.874 34.6542 6.318 34.6542 6.834V7.266C34.6542 7.794 34.7682 8.262 34.9962 8.67C35.2362 9.066 35.5662 9.372 35.9862 9.588C36.4182 9.792 36.9222 9.894 37.4982 9.894C38.0142 9.894 38.4642 9.816 38.8482 9.66C39.2442 9.504 39.6042 9.27 39.9282 8.958L41.4222 10.578C40.9782 11.082 40.4202 11.472 39.7482 11.748C39.0762 12.012 38.3022 12.144 37.4262 12.144Z" />+ </svg>+);++/**+ * A container for {@link EnteLogo} that reset the line height to vertically+ * center the logo within the surrounding context.+ *+ * By default, the line height causes the SVG to have an extra space at the+ * bottom. Removing it allows the SVG contents to be centered using its inherent+ * sizing. his is a convenience container that resets the line height, and also+ * takes the {@link sx} prop to allow for easy tweaking of other styling of the+ * container without touching the SVG.+ */+export const EnteLogoBox = styled("div")`+ line-height: 0;+`;diff --git a/web/apps/albums/vendor/ente-base/components/EnteSwitch.tsx b/web/apps/albums/vendor/ente-base/components/EnteSwitch.tsxnew file mode 100644index 0000000000..b339fafecb--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/EnteSwitch.tsx@@ -0,0 +1,55 @@+import { Switch, styled, type SwitchProps } from "@mui/material";+import React from "react";++/**+ * A custom variant of the MUI {@link Switch}, styled per our designs.+ */+export const EnteSwitch: React.FC<SwitchProps> = styled((props) => (+ <Switch disableRipple {...props} />+))(({ theme }) => ({+ width: 40,+ height: 24,+ padding: 0,+ "& .MuiSwitch-switchBase": {+ padding: 0,+ margin: 2,+ transitionDuration: "300ms",+ "&.Mui-checked": {+ transform: "translateX(16px)",+ color: "white",+ "& + .MuiSwitch-track": {+ opacity: 1,+ border: 0,+ backgroundColor: theme.vars.palette.fixed.switchOn,+ },+ "&.Mui-disabled + .MuiSwitch-track": { opacity: 0.5 },+ },+ "&.Mui-disabled .MuiSwitch-thumb": {+ color: theme.vars.palette.grey[600],+ ...theme.applyStyles("light", {+ color: theme.vars.palette.grey[100],+ }),+ },+ "&.Mui-disabled + .MuiSwitch-track": { opacity: 0.3 },+ },+ "& .MuiSwitch-thumb": { boxSizing: "border-box", width: 20, height: 20 },+ "& .MuiSwitch-track": {+ borderRadius: 22 / 2,+ backgroundColor: theme.vars.palette.fill.muted,+ opacity: 1,+ transition: theme.transitions.create(["background-color"], {+ duration: 500,+ }),+ },+ // Use an alternative affordance to indicate focusVisible as the ripple+ // effect is disabled.+ ".MuiSwitch-switchBase.Mui-focusVisible + .MuiSwitch-track": {+ outline: `2px solid ${theme.vars.palette.stroke.muted}`,+ outlineOffset: "-2px",+ },+ // Same for when the switch is active.+ ".MuiSwitch-switchBase:active + .MuiSwitch-track": {+ outline: `1px solid ${theme.vars.palette.stroke.faint}`,+ outlineOffset: "-1px",+ },+}));diff --git a/web/apps/albums/vendor/ente-base/components/ErrorIndicator.tsx b/web/apps/albums/vendor/ente-base/components/ErrorIndicator.tsxnew file mode 100644index 0000000000..16f7ebf919--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/ErrorIndicator.tsx@@ -0,0 +1,41 @@+import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline";+import { Stack, Typography } from "@mui/material";+import { t } from "i18next";+import type React from "react";++/**+ * An error message indicator, styled to complement {@link ActivityIndicator}.+ *+ * If a child is provided, it is used as the error message to show (after being+ * wrapped in a suitable {@link Typography}). Otherwise the default generic+ * error message is shown.+ */+export const ActivityErrorIndicator: React.FC<React.PropsWithChildren> = ({+ children,+}) => (+ <Stack sx={{ gap: 2, alignItems: "center" }}>+ <ErrorOutlineIcon color="secondary" />+ <Typography sx={{ color: "text.muted" }}>+ {children ?? t("generic_error")}+ </Typography>+ </Stack>+);++/**+ * An smaller error message indicator suitable for being shown above or below+ * text fields.+ *+ * If a child is provided, it is used as the error message to show (after being+ * wrapped in a suitable {@link Typography}). Otherwise the default generic+ * error message is shown.+ */+export const InlineErrorIndicator: React.FC<React.PropsWithChildren> = ({+ children,+}) => (+ <Stack direction="row" sx={{ gap: "5px", alignItems: "center" }}>+ <ErrorOutlineIcon sx={{ fontSize: "16px", color: "critical.main" }} />+ <Typography variant="small" sx={{ color: "critical.main" }}>+ {children ?? t("generic_error")}+ </Typography>+ </Stack>+);diff --git a/web/apps/albums/vendor/ente-base/components/Head.tsx b/web/apps/albums/vendor/ente-base/components/Head.tsxnew file mode 100644index 0000000000..613ad6dcb0--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/Head.tsx@@ -0,0 +1,141 @@+import Head from "next/head";+import React from "react";+import { haveWindow } from "../env";+import {+ albumsAppOrigin,+ isCustomAlbumsAppOrigin,+ isCustomShareAppOrigin,+ shareAppOrigin,+} from "../origins";++interface CustomHeadProps {+ title: string;+}++/**+ * A custom version of "next/head" that sets the title, description, favicon and+ * some other boilerplate <head> tags.+ *+ * This assumes the existence of `public/images/favicon.png`.+ */+export const CustomHead: React.FC<CustomHeadProps> = ({ title }) => (+ <Head>+ <title>{title}</title>+ <link rel="icon" href="/images/favicon.png" type="image/png" />+ <meta+ name="description"+ content="Ente - end-to-end encrypted cloud with open-source apps"+ />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <meta name="referrer" content="strict-origin-when-cross-origin" />+ </Head>+);++/**+ * A static SSR-ed variant of {@link CustomHead} for use with the albums app+ * deployed on production Ente instances for link previews.+ *+ * In particular,+ *+ * - Any client side modifications to the document's head will be too late for+ * use by the link previews, so the contents of this need to part of the+ * static HTML.+ *+ * - "og:image" needs to be an absolute URL.+ *+ * To avoid getting in the way of self hosters, we do a deployment URL check+ * before inlining this into the build.+ */+export const CustomHeadAlbums: React.FC = () => (+ <Head>+ <title>Ente Photos</title>+ <link rel="icon" href="/images/favicon.png" type="image/png" />+ <meta+ name="description"+ content="Safely store and share your best moments"+ />+ <meta+ property="og:image"+ content="https://albums.ente.io/images/preview.jpg"+ />+ {/* Twitter wants its own thing. */}+ <meta+ name="twitter:image"+ content="https://albums.ente.io/images/preview.jpg"+ />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <meta name="referrer" content="strict-origin-when-cross-origin" />+ </Head>+);++/**+ * A convenience fan out to conditionally show one of {@link CustomHead} or+ * {@link CustomHeadAlbums}.+ *+ * 1. This component defaults to {@link CustomHeadAlbums} during SSR unless a+ * custom endpoint is defined.+ *+ * 2. Currently the photos and albums app use the same code. During SSR this+ * uses the albums variant, and then does a client side update to the photos+ * head when it detects that the origin it is being served on is not the+ * albums origin.+ *+ * The current content of the head is such that it sort of works for both photos+ * and public albums, so the client side update is just an enhancement. We+ * should not need this component when the photos and public albums app split.+ */+export const CustomHeadPhotosOrAlbums: React.FC<CustomHeadProps> = ({+ title,+}) =>+ isCustomAlbumsAppOrigin ||+ (haveWindow() &&+ new URL(window.location.href).origin != albumsAppOrigin()) ? (+ <CustomHead {...{ title }} />+ ) : (+ <CustomHeadAlbums />+ );++/**+ * A static SSR-ed variant of {@link CustomHead} for use with the share app+ * (Public Locker) deployed on production Ente instances for link previews.+ *+ * Similar to {@link CustomHeadAlbums}, this includes Open Graph meta tags with+ * absolute URLs for social media preview images.+ */+export const CustomHeadShareStatic: React.FC = () => (+ <Head>+ <title>Ente Locker</title>+ <link rel="icon" href="/images/favicon.png" type="image/png" />+ <meta+ name="description"+ content="Securely store and share your documents"+ />+ <meta+ property="og:image"+ content="https://share.ente.io/images/preview.png"+ />+ <meta+ name="twitter:image"+ content="https://share.ente.io/images/preview.png"+ />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <meta name="referrer" content="strict-origin-when-cross-origin" />+ </Head>+);++/**+ * A convenience fan out to conditionally show one of {@link CustomHead} or+ * {@link CustomHeadShareStatic}.+ *+ * This component defaults to {@link CustomHeadShareStatic} during SSR unless a+ * custom endpoint is defined, and then does a client side update when it+ * detects that the origin it is being served on is not the share origin.+ */+export const CustomHeadShare: React.FC<CustomHeadProps> = ({ title }) =>+ isCustomShareAppOrigin ||+ (haveWindow() &&+ new URL(window.location.href).origin != shareAppOrigin()) ? (+ <CustomHead {...{ title }} />+ ) : (+ <CustomHeadShareStatic />+ );diff --git a/web/apps/albums/vendor/ente-base/components/LinkButton.tsx b/web/apps/albums/vendor/ente-base/components/LinkButton.tsxnew file mode 100644index 0000000000..cd7be3fd57--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/LinkButton.tsx@@ -0,0 +1,54 @@+import { Link, type ButtonProps } from "@mui/material";+import React from "react";++/**+ * A button that looks like a link.+ *+ * The use of this component is not encouraged. It is only useful in uncommon+ * cases where we do not have sufficient space to include a proper button.+ */+export const LinkButton: React.FC<+ React.PropsWithChildren<Pick<ButtonProps, "onClick">>+> = ({ onClick, children }) => (+ <Link+ component="button"+ sx={(theme) => ({+ color: "text.base",+ textDecoration: "underline",+ // The shortcut "text.faint" does not work with textDecorationColor+ // (as of MUI v6).+ textDecorationColor: theme.vars.palette.text.faint,+ "&:hover": {+ color: "accent.main",+ textDecoration: "underline",+ textDecorationColor: "accent.main",+ },+ })}+ {...{ onClick }}+ >+ {children}+ </Link>+);++/**+ * A variant of {@link LinkButton} that does not show an underline, and instead+ * uses a bolder font weight to indicate clickability.+ *+ * Similar caveats as {@link LinkButton} apply.+ */+export const LinkButtonUndecorated: React.FC<+ React.PropsWithChildren<Pick<ButtonProps, "onClick">>+> = ({ onClick, children }) => (+ <Link+ component="button"+ sx={{+ textDecoration: "none",+ color: "text.muted",+ fontWeight: "medium",+ "&:hover": { color: "accent.main" },+ }}+ {...{ onClick }}+ >+ {children}+ </Link>+);diff --git a/web/apps/albums/vendor/ente-base/components/MiniDialog.tsx b/web/apps/albums/vendor/ente-base/components/MiniDialog.tsxnew file mode 100644index 0000000000..21e48f17e1--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/MiniDialog.tsx@@ -0,0 +1,385 @@+import type { ButtonProps, ModalProps } from "@mui/material";+import {+ Box,+ Dialog,+ DialogContent,+ DialogTitle,+ Stack,+ Typography,+ type DialogProps,+} from "@mui/material";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { LoadingButton } from "ente-base/components/mui/LoadingButton";+import { t } from "i18next";+import React, { useState } from "react";+import log from "../log";+import { InlineErrorIndicator } from "./ErrorIndicator";++/**+ * Customize the contents of an {@link AttributedMiniDialog}.+ */+export interface MiniDialogAttributes {+ /**+ * The dialog's title.+ *+ * This will be usually be a string, but the prop accepts any React node to+ * allow passing a i18next <Trans /> component.+ */+ title?: React.ReactNode;+ /**+ * An optional component shown next to the title.+ */+ icon?: React.ReactNode;+ /**+ * The dialog's message.+ *+ * This will be usually be a string, but the prop accepts any React node to+ * allow passing a i18next <Trans /> component.+ */+ message?: React.ReactNode;+ /**+ * If `true`, then the dialog cannot be closed (e.g. with the ESC key, or+ * clicking on the backdrop) except through one of the explicitly provided+ * actions.+ */+ nonClosable?: boolean;+ /**+ * If `true`, then the dialog cannot be replaced by another dialog while it+ * is being displayed.+ *+ * The app uses a single component to render mini dialogs, and it is+ * possible that new dialog contents might preempt and replace contents in a+ * dialog that is already being shown. Usually if such preemption is+ * expected then both dialogs use differing mechanisms, but it can happen in+ * rare unforeseen cases.+ *+ * This flag allow a dialog to indicate that it should not be preempted, as+ * it contains some critical information.+ *+ * Use this flag sparingly.+ */+ nonReplaceable?: boolean;+ /**+ * Customize the primary action button shown in the dialog.+ *+ * This is provided by boxes which serve as some sort of confirmation. If+ * not provided, only the {@link cancel} button is shown, unless that too is+ * explicitly disabled.+ */+ continue?: {+ /**+ * The string to use as the label for the primary action button.+ *+ * Default is `t("ok")`.+ */+ text?: string;+ /**+ * The color of the button.+ *+ * Default is "accent".+ */+ color?: ButtonProps["color"];+ /**+ * If `true`, the primary action button is auto focused when the dialog+ * is opened, allowing the user to confirm just by pressing ENTER.+ */+ autoFocus?: ButtonProps["autoFocus"];+ /**+ * The function to call when the user activates the button.+ *+ * If this function returns a promise, then an activity indicator will+ * be shown on the button until the promise settles.+ *+ * If this function is not provided, or if the function completes /+ * fulfills, then then the dialog is automatically closed.+ *+ * Otherwise (that is, if the provided function throws), the dialog+ * remains open, showing a generic error.+ *+ * That's quite a mouthful, here's a flowchart:+ *+ * - Not provided: Close+ * - Provided sync:+ * - Success: Close+ * - Failure: Remain open, showing generic error+ * - Provided async:+ * - Success: Close+ * - Failure: Remain open, showing generic error+ */+ action?: () => void | Promise<void>;+ };+ /**+ * Customize the secondary action button shown in the dialog.+ *+ * This is rarely needed. When provided, these attributes behave similar to+ * the {@link continue} attributes, except this button is shown below the+ * primary button.+ *+ * This is not supported when button direction is "row".+ */+ secondary?: {+ /**+ * The string to use as the label for the secondary action button.+ *+ * Must be provided.+ */+ text: string;+ /**+ * The color of the button.+ *+ * Default is "primary".+ */+ color?: ButtonProps["color"];+ /**+ * The function to call when the user activates the button.+ *+ * The behaviour of this function is exactly the same as that of the+ * primary {@link action} provided via the {@link continue} attributes.+ */+ action?: () => void | Promise<void>;+ };+ /**+ * The string to use as the label for the cancel button.+ *+ * Default is `t("cancel")`.+ *+ * Set this to `false` to omit the cancel button altogether.+ *+ * The object form allows providing both the button title and the action+ * handler (synchronous). The dialog is always closed on clicks.+ */+ cancel?: string | false | { text: string; action: () => void };+ /** The direction in which the buttons are stacked. Default is "column". */+ buttonDirection?: "row" | "column";+}++type MiniDialogProps = Pick<DialogProps, "open"> & {+ onClose: () => void;+ attributes?: MiniDialogAttributes;+};++/**+ * A small, mostly predefined, MUI {@link Dialog} that can be used to notify the+ * user, or ask for confirmation before actions.+ *+ * The rendered dialog can be customized by modifying the {@link attributes}+ * prop. If you find yourself wanting to customize it further, consider either+ * using a {@link TitledMiniDialog} or {@link Dialog}.+ */+export const AttributedMiniDialog: React.FC<+ React.PropsWithChildren<MiniDialogProps>+> = ({ open, onClose, attributes, children }) => {+ const [phase, setPhase] = useState<+ "loading" | "secondary-loading" | "failed" | undefined+ >();++ if (!attributes) {+ return <></>;+ }++ const resetPhaseAndClose = () => {+ setPhase(undefined);+ onClose();+ };++ const handleClose: ModalProps["onClose"] = (_, reason) => {+ if (attributes.nonClosable) return;+ // Ignore backdrop clicks when we're processing the user request.+ if (+ reason == "backdropClick" &&+ (phase == "loading" || phase == "secondary-loading")+ ) {+ return;+ }+ resetPhaseAndClose();+ };++ const [cancelTitle, handleCancel] = ((+ c: MiniDialogAttributes["cancel"],+ ) => {+ if (c === false) return [undefined, undefined];+ if (c === undefined) return [t("cancel"), resetPhaseAndClose];+ if (typeof c == "string") return [c, resetPhaseAndClose];+ return [+ c.text,+ () => {+ resetPhaseAndClose();+ c.action();+ },+ ];+ })(attributes.cancel);++ const loadingButton = attributes.continue && (+ <LoadingButton+ loading={phase == "loading"}+ disabled={phase == "secondary-loading"}+ fullWidth+ color={attributes.continue.color ?? "accent"}+ autoFocus={attributes.continue.autoFocus}+ onClick={async () => {+ setPhase("loading");+ try {+ await attributes.continue?.action?.();+ resetPhaseAndClose();+ } catch (e) {+ log.error(e);+ setPhase("failed");+ }+ }}+ >+ {attributes.continue.text ?? t("ok")}+ </LoadingButton>+ );++ const secondaryLoadingButton = attributes.secondary?.text && (+ <LoadingButton+ disabled={phase == "loading"}+ loading={phase == "secondary-loading"}+ fullWidth+ color={attributes.secondary.color ?? "primary"}+ onClick={async () => {+ setPhase("secondary-loading");+ try {+ await attributes.secondary?.action?.();+ resetPhaseAndClose();+ } catch (e) {+ log.error(e);+ setPhase("failed");+ }+ }}+ >+ {attributes.secondary.text}+ </LoadingButton>+ );++ if (secondaryLoadingButton && attributes.buttonDirection == "row")+ throw new Error("Unsupported combination");++ const cancelButton = cancelTitle && (+ <FocusVisibleButton+ fullWidth+ color="secondary"+ disabled={phase == "loading"}+ onClick={handleCancel}+ >+ {cancelTitle}+ </FocusVisibleButton>+ );++ return (+ <Dialog+ {...{ open }}+ onClose={handleClose}+ fullWidth+ slotProps={{ paper: { sx: { maxWidth: "360px" } } }}+ >+ {(attributes.icon ?? attributes.title) ? (+ <Stack+ direction="row"+ sx={[+ {+ justifyContent: "space-between",+ alignItems: "center",+ "& > svg": {+ fontSize: "32px",+ color: "stroke.faint",+ },+ },+ attributes.icon && attributes.title+ ? { padding: "20px 16px 0px 16px" }+ : { padding: "24px 16px 4px 16px" },+ ]}+ >+ {attributes.title && (+ <DialogTitle+ sx={{+ "&&&": { padding: 0 },+ // Wrap the title to the next line if there+ // isn't sufficient space to make it fit in one.+ flexShrink: 1,+ }}+ >+ {attributes.title}+ </DialogTitle>+ )}+ {attributes.icon}+ </Stack>+ ) : (+ <Box sx={{ height: "8px" }} /> /* Spacer */+ )}+ <DialogContent>+ {attributes.message && (+ <Typography+ component={+ typeof attributes.message == "string" ? "p" : "div"+ }+ sx={{ color: "text.muted" }}+ >+ {attributes.message}+ </Typography>+ )}+ {children}+ <Stack+ sx={{ pt: 3, gap: 1 }}+ direction={attributes.buttonDirection ?? "column"}+ >+ {phase == "failed" && <InlineErrorIndicator />}+ {attributes.buttonDirection == "row" ? (+ <>+ {cancelButton}+ {loadingButton}+ </>+ ) : (+ <>+ {loadingButton}+ {secondaryLoadingButton}+ {cancelButton}+ </>+ )}+ </Stack>+ </DialogContent>+ </Dialog>+ );+};++type TitledMiniDialogProps = Pick<DialogProps, "open" | "onClose" | "sx"> & {+ /**+ * The dialog's title.+ */+ title?: React.ReactNode;+ /**+ * Optional max width of the underlying MUI {@link Paper}.+ *+ * Default: 360px (same as {@link AttributedMiniDialog}).+ */+ paperMaxWidth?: string;+};++/**+ * MiniDialog in a "shell" form.+ *+ * This is a {@link Dialog} for use at places which need more customization than+ * what {@link AttributedMiniDialog} provides, but wish to retain a similar look+ * and feel without duplicating code.+ *+ * It does three things:+ *+ * - Sets a fixed size and padding similar to {@link AttributedMiniDialog}.+ * - Takes the title as a prop, and wraps it in a {@link DialogTitle}.+ * - Wraps children in a scrollable {@link DialogContent}.+ */+export const TitledMiniDialog: React.FC<+ React.PropsWithChildren<TitledMiniDialogProps>+> = ({ open, onClose, sx, paperMaxWidth, title, children }) => (+ <Dialog+ {...{ open, sx }}+ onClose={onClose}+ fullWidth+ slotProps={{ paper: { sx: { maxWidth: paperMaxWidth ?? "360px" } } }}+ >+ <DialogTitle sx={{ "&&&": { paddingBlock: "24px 16px" } }}>+ {title}+ </DialogTitle>+ <DialogContent>{children}</DialogContent>+ </Dialog>+);diff --git a/web/apps/albums/vendor/ente-base/components/Navbar.tsx b/web/apps/albums/vendor/ente-base/components/Navbar.tsxnew file mode 100644index 0000000000..75edd810d5--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/Navbar.tsx@@ -0,0 +1,11 @@+import { styled } from "@mui/material";++export const NavbarBase = styled("div")(+ ({ theme }) => `+ flex: 0 0 64px;+ display: flex;+ justify-content: center;+ align-items: center;+ border-bottom: 1px solid ${theme.vars.palette.divider};+`,+);diff --git a/web/apps/albums/vendor/ente-base/components/OverflowMenu.tsx b/web/apps/albums/vendor/ente-base/components/OverflowMenu.tsxnew file mode 100644index 0000000000..9df36745b2--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/OverflowMenu.tsx@@ -0,0 +1,199 @@+import MoreHorizIcon from "@mui/icons-material/MoreHoriz";+import {+ IconButton,+ MenuItem,+ Stack,+ Typography,+ type IconButtonProps,+ type PaperProps,+} from "@mui/material";+import Menu, { type MenuProps } from "@mui/material/Menu";+import React, { createContext, useContext, useMemo, useState } from "react";++interface OverflowMenuContextT {+ close: () => void;+}++const OverflowMenuContext = createContext<OverflowMenuContextT | undefined>(+ undefined,+);++interface OverflowMenuProps {+ /**+ * An ARIA identifier for the overflow menu when it is displayed.+ */+ ariaID: string;+ /**+ * The icon for the trigger button.+ *+ * If not provided, then by default the MoreHoriz icon from MUI is used.+ */+ triggerButtonIcon?: React.ReactNode;+ /**+ * Optional additional properties for the trigger icon button.+ */+ triggerButtonSxProps?: IconButtonProps["sx"];+ /**+ * Optional additional sx props for the MUI {@link Paper} that underlies the+ * {@link Menu}.+ */+ menuPaperSxProps?: PaperProps["sx"];+}++/**+ * An overflow menu showing {@link OverflowMenuOptions}, alongwith a button to+ * trigger the visibility of the menu.+ */+export const OverflowMenu: React.FC<+ React.PropsWithChildren<OverflowMenuProps>+> = ({+ ariaID,+ triggerButtonIcon,+ triggerButtonSxProps,+ menuPaperSxProps,+ children,+}) => {+ const [anchorEl, setAnchorEl] = useState<MenuProps["anchorEl"]>();+ const context = useMemo(+ () => ({ close: () => setAnchorEl(undefined) }),+ [],+ );+ return (+ <OverflowMenuContext value={context}>+ <IconButton+ onClick={(event) => setAnchorEl(event.currentTarget)}+ aria-controls={anchorEl ? ariaID : undefined}+ aria-haspopup="true"+ aria-expanded={anchorEl ? "true" : undefined}+ sx={triggerButtonSxProps}+ >+ {triggerButtonIcon ?? <MoreHorizIcon />}+ </IconButton>+ <Menu+ id={ariaID}+ {...(anchorEl && { anchorEl })}+ open={!!anchorEl}+ onClose={() => setAnchorEl(undefined)}+ slotProps={{+ paper: { sx: menuPaperSxProps },+ list: {+ // Disable padding at the top and bottom of the menu list.+ disablePadding: true,+ "aria-labelledby": ariaID,+ },+ }}+ anchorOrigin={{ vertical: "bottom", horizontal: "right" }}+ transformOrigin={{ vertical: "top", horizontal: "right" }}+ >+ {children}+ </Menu>+ </OverflowMenuContext>+ );+};++interface OverflowMenuOptionProps {+ /**+ * Called when the menu option is clicked.+ */+ onClick: () => void;+ /**+ * The color of the text and icons.+ *+ * Default: "primary".+ */+ color?: "primary" | "critical";+ /**+ * An optional icon to show at the leading edge of the menu option.+ */+ startIcon?: React.ReactNode;+ /**+ * An optional icon to show at the trailing edge of the menu option.+ */+ endIcon?: React.ReactNode;+ /**+ * If true, the menu option will be styled as selected with a hover effect.+ */+ selected?: boolean;+ /**+ * If true, reduce spacing and sizing for dense menus.+ */+ compact?: boolean;+ /**+ * If true, the option is shown disabled and cannot be selected.+ */+ disabled?: boolean;+}++/**+ * Individual options meant to be shown inside an {@link OverflowMenu}.+ */+export const OverflowMenuOption: React.FC<+ React.PropsWithChildren<OverflowMenuOptionProps>+> = ({+ onClick,+ color = "primary",+ startIcon,+ endIcon,+ selected,+ compact,+ disabled,+ children,+}) => {+ const menuContext = useContext(OverflowMenuContext);++ const handleClick = () => {+ onClick();+ // We might've already been closed as a result of our containing menu+ // getting closed. An example of this is the "Sort by" option in the+ // album options overflow menu, where the `onClick` above will result in+ // `onClose` being called on our parent menu, so `menuContext` will be+ // undefined when we get here.+ menuContext?.close();+ };++ return (+ <MenuItem+ onClick={handleClick}+ selected={selected}+ disabled={disabled}+ sx={(theme) => ({+ minWidth: compact ? 176 : 220,+ color: disabled+ ? theme.vars.palette.text.muted+ : theme.vars.palette[color].main,++ // Reduce the size of the icons a bit to make it fit better with+ // the text.+ "& .MuiSvgIcon-root": { fontSize: compact ? "18px" : "20px" },+ ...(selected && {+ backgroundColor: "rgba(255, 255, 255, 0.08)",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.12)" },+ }),+ })}+ >+ <Stack+ direction="row"+ sx={{+ gap: compact ? 1 : 1.5,+ alignItems: "center",+ // Fill our container.+ width: "100%",+ // MUI has responsive padding, use a static value instead.+ py: compact ? 0.5 : 1,+ }}+ >+ {startIcon}+ <Typography+ sx={{+ flex: 1,+ fontWeight: "medium",+ fontSize: compact ? "0.9rem" : undefined,+ }}+ >+ {children}+ </Typography>+ {endIcon}+ </Stack>+ </MenuItem>+ );+};diff --git a/web/apps/albums/vendor/ente-base/components/RowButton.tsx b/web/apps/albums/vendor/ente-base/components/RowButton.tsxnew file mode 100644index 0000000000..a66bec3e42--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/RowButton.tsx@@ -0,0 +1,425 @@+import {+ Box,+ Divider,+ Stack,+ styled,+ Typography,+ type ButtonProps,+ type TypographyProps,+} from "@mui/material";+import { EnteSwitch } from "ente-base/components/EnteSwitch";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import React from "react";+import { ActivityIndicator } from "./mui/ActivityIndicator";++interface RowButtonGroupTitleProps {+ /**+ * An optional leading SvgIcon before the title.+ */+ icon?: React.ReactNode;+}++/**+ * A section title, meant to precede a {@link RowButtonGroup}.+ */+export const RowButtonGroupTitle: React.FC<+ React.PropsWithChildren<RowButtonGroupTitleProps>+> = ({ children, icon }) => (+ <Stack+ direction="row"+ sx={{+ px: "8px",+ py: "6px",+ gap: "8px",+ "& > svg": { fontSize: "17px", color: "stroke.muted" },+ }}+ >+ {icon && icon}+ <Typography variant="small" sx={{ color: "text.muted" }}>+ {children}+ </Typography>+ </Stack>+);++/**+ * A short description text meant to come after a {@link RowButtonGroup}.+ */+export const RowButtonGroupHint: React.FC<React.PropsWithChildren> = ({+ children,+}) => (+ <Typography+ variant="small"+ sx={{ color: "text.faint", px: "16px", py: "6px" }}+ >+ {children}+ </Typography>+);++/**+ * A divider for buttons in a {@link RowButtonGroup}.+ */+export const RowButtonDivider = () => (+ <Divider sx={{ "&&&": { mttty: 0 }, opacity: 0.4 }} />+);++/**+ * A group of {@link RowButton}s that visually look together as a single+ * section.+ *+ * {@link RowButtonGroupTitle} can be used to provide a title for the entire+ * group, and {@link RowButtonGroupHint} can be used to provide a hint text that+ * follows the group.+ *+ * {@link RowButtonDivider} can be used to to separate the individual buttons in+ * the group.+ *+ * ---+ *+ * Note: {@link RowButtonGroup} is not designed to work with the "secondary"+ * variant of {@link RowButton}.+ */+export const RowButtonGroup = styled("div")(+ ({ theme }) => `+ background-color: ${theme.vars.palette.fill.faint};+ border-radius: 8px;+ /* Modify the RowButton style when it is placed inside a RowButtonGroup. */+ & > button {+ border-radius: 8px;+ background-color: transparent;+ }+ /* Need to retarget the disabled state with increased specificity. */+ & > button.Mui-disabled {+ background-color: transparent;+ }+ & > button:not(:last-of-type) {+ border-bottom-left-radius: 0;+ border-bottom-right-radius: 0;+ }+ & > button:not(:first-of-type) {+ border-top-left-radius: 0;+ border-top-right-radius: 0;+ }+ & > button:hover {+ /* These fills are translucent and additive, and the RowButtonGroup+ already has a background, so pick a (transparent) color that gives us+ a similar outcome of the hover state as for a RowButton that is not+ inside a RowButtonGroup */+ background-color: ${theme.vars.palette.fill.faintHover};+ }+ /* Reset the border radius when showing focus outlines that will be added+ by the styles attached to FocusVisibleButton. */+ & > button.Mui-focusVisible {+ border-radius: 8px;+ }+ /* Modify the outline offset added by FocusVisibleButton for a visual+ effect that fits better with these row buttons. */+ & > button:active {+ outline-offset: 0;+ }+`,+);++interface RowButtonProps {+ /**+ * Variants:+ *+ * - "primary" (default): A row button with a filled in background color.+ *+ * - "secondary": A row button without a fill.+ */+ variant?: "primary" | "secondary";+ /**+ * Color of the row button.+ *+ * Semantically, this is similar to the "color" props for a MUI button,+ * except we only support two cases for this row button component:+ *+ * - "primary" (default): A row button that uses "text.base" as the color of+ * the text (and an appropriate background color, if needed, based on the+ * value of the {@link variant}).+ *+ * - "critical": A row button that uses "critical.main" as the color of the+ * text. The background fill, if any, will be the same as what "primary"+ * would've entailed.+ */+ color?: "primary" | "critical";+ /**+ * Modify the font weight of the {@link label}, when label is a string.+ *+ * Default: "medium".+ */+ fontWeight?: TypographyProps["fontWeight"];+ /**+ * If true, then the row button will be disabled.+ */+ disabled?: boolean;+ /**+ * Called when the row button is activated (e.g. by a click).+ */+ onClick: () => void;+ /**+ * Optional icon shown at the leading edge of the row button.+ *+ * This is usually an icon like an {@link SvgIcon}, but it can be any+ * arbitrary component, the row button does not make any assumptions as to+ * what this is.+ *+ * If it is an {@link SvgIcon}, the row button will size it appropriately.+ */+ startIcon?: React.ReactNode;+ /**+ * Optional icon shown at the trailing edge of the row button.+ *+ * Similar to {@link startIcon} this can be any arbitrary component, though+ * usually it is an {@link SvgIcon} whose size the row button will set.+ */+ endIcon?: React.ReactNode;+ /**+ * The label for the component.+ *+ * Usually this is expected to be a string, in which case it is wrapped up+ * in an appropriate {@link Typography} and shown on the row button. But it+ * can be an arbitrary react component too, to allow customizing its+ * appearance or otherwise modifying it in one off cases (it will be used as+ * it is and not wrapped in a {@link Typography} if it is not a string).+ */+ label: React.ReactNode;+ /**+ * The text (or icon) to show alongside {@link label}, separated from it by+ * a bullet.+ *+ * This is usually expected to be a string, in which case it is wrapped in a+ * {@link Typography} component and styled with a muted text color before+ * being rendered.+ *+ * However, it can also be an {@link SvgIcon} (or any an arbitrary+ * component), though in terms of styling, only an {@link SvgIcon} usually+ * makes sense.+ *+ * Similar to {@link label}, it will not be wrapped in a {@link Typography}+ * if it is not a string.+ */+ caption?: React.ReactNode;+}++/**+ * A button that looks like a row in a group of options / choices.+ *+ * It can be used both standalone, or as part of a {@link RowButtonGroup}.+ */+export const RowButton: React.FC<RowButtonProps> = ({+ variant = "primary",+ color = "primary",+ fontWeight = "medium",+ disabled = false,+ startIcon,+ endIcon,+ label,+ caption,+ onClick,+}) => (+ <RowButtonRoot rbVariant={variant} fullWidth {...{ disabled, onClick }}>+ <Stack+ direction="row"+ sx={[+ {+ flex: 1,+ justifyContent: "space-between",+ alignItems: "center",+ px: "16px",+ pr: "12px",+ color: "text.base",+ },+ color == "critical" && { color: "critical.main" },+ disabled && { color: "text.muted" },+ ]}+ >+ <Stack+ direction="row"+ sx={{ py: "14px", gap: "10px", alignItems: "center" }}+ >+ {startIcon && startIcon}+ <Box sx={{ px: "2px" }}>+ {typeof label != "string" ? (+ label+ ) : caption ? (+ <Stack+ direction="row"+ sx={{ gap: "4px", alignItems: "center" }}+ >+ {/* Don't shrink the main label, instead let the+ caption grow into two lines if it needs to. */}+ <Typography sx={{ flexShrink: 0 }}>+ {label}+ </Typography>+ <CaptionTypography color={color}>+ {"•"}+ </CaptionTypography>+ <CaptionTypography color={color}>+ {caption}+ </CaptionTypography>+ </Stack>+ ) : (+ <Typography fontWeight={fontWeight}>{label}</Typography>+ )}+ </Box>+ </Stack>+ {endIcon && endIcon}+ </Stack>+ </RowButtonRoot>+);++type RowButtonRootProps = ButtonProps & {+ // Prefix with "rb" to differentiate this from the "variant" prop of the MUI+ // button that we're styling.+ rbVariant: RowButtonProps["variant"];+};++const RowButtonRoot = styled(FocusVisibleButton, {+ shouldForwardProp: (prop) => prop != "rbVariant",+ // name: "MuiMenuItem",+})<React.PropsWithChildren<RowButtonRootProps>>(({ theme }) => ({+ // Remove button's default padding.+ padding: 0,+ // Set the size of the any icons (SvgIcon instances) provided to us to make+ // them fit with the Typography within the button's content.+ "& .MuiSvgIcon-root": { fontSize: "20px" },+ variants: [+ {+ props: { rbVariant: "primary" },+ style: {+ backgroundColor: theme.vars.palette.fill.faint,+ "&:hover": { backgroundColor: theme.vars.palette.fill.muted },+ },+ },+ {+ props: { rbVariant: "secondary" },+ style: {+ backgroundColor: "transparent",+ color: "white",+ "&:hover": { backgroundColor: theme.vars.palette.fill.faint },+ },+ },+ ],+}));++const CaptionTypography: React.FC<+ React.PropsWithChildren<{ color: RowButtonProps["color"] }>+> = ({ color, children }) => (+ <Typography+ variant="small"+ sx={[+ color == "critical"+ ? { color: "critical.main" }+ : { color: "text.faint" },+ ]}+ >+ {children}+ </Typography>+);++interface RowSwitchProps {+ /**+ * The state of the contained {@link EnteSwitch}.+ */+ checked?: boolean;+ /**+ * Called when the user activates the contained {@link EnteSwitch}.+ */+ onClick: () => void;+ /**+ * The label for the component.+ *+ * Similar to the {@link label} prop for {@link RowButton}, but can only be+ * a string instead of an arbitrary component.+ */+ label: string;+}++/**+ * A row that visually looks similar to a {@link RowButton}, but instead of a+ * button is a normal {@link Typography} with a {@link EnteSwitch} at its+ * trailing edge.+ *+ * It only works (visually) when placed within a {@link RowButtonGroup} since+ * that is where it gets its background color from.+ */+export const RowSwitch: React.FC<RowSwitchProps> = ({+ checked,+ label,+ onClick,+}) => (+ <Stack+ direction="row"+ sx={{+ flex: 1,+ justifyContent: "space-between",+ alignItems: "center",+ px: "16px",+ pr: "12px",+ }}+ >+ <Typography sx={{ py: "14px", px: "2px", fontWeight: "medium" }}>+ {label}+ </Typography>+ <EnteSwitch {...{ checked, onClick }} />+ </Stack>+);++interface RowLabelProps {+ /**+ * Optional icon shown at the leading edge of the row button.+ *+ * This is usually an icon like an {@link SvgIcon}, but it can be any+ * arbitrary component, the row button does not make any assumptions as to+ * what this is.+ *+ * Unlike a {@link RowButton}, there is not sizing applied to it.+ */+ startIcon?: React.ReactNode;+ /**+ * The label for the component.+ *+ * Similar to the {@link label} prop for {@link RowButton}, but can only be+ * a string instead of an arbitrary component.+ */+ label: string;+}++/**+ * A row that visually looks similar to a {@link RowButton}, but instead of a+ * button is a normal {@link Typography}.+ *+ * This is useful for creating non-interactive, static, labels.+ *+ * It only works (visually) when placed within a {@link RowButtonGroup} since+ * that is where it gets its background color from.+ */+export const RowLabel: React.FC<RowLabelProps> = ({ startIcon, label }) => (+ <Stack+ direction="row"+ sx={{+ flex: 1,+ justifyContent: "space-between",+ alignItems: "center",+ px: "16px",+ pr: "12px",+ }}+ >+ <Stack direction="row" sx={{ py: "14px", gap: "10px" }}>+ {startIcon && startIcon}+ <Box sx={{ px: "2px" }}>+ {/* Nb: Unlike the button, this has "regular" fontWeight. */}+ <Typography>{label}</Typography>+ </Box>+ </Stack>+ </Stack>+);++/**+ * A variant of {@link ActivityIndicator} with defaults suitable to be used as the+ * {@link EndIcon} of a {@link RowButton}.+ */+export const RowButtonEndActivityIndicator: React.FC = () => (+ <ActivityIndicator size="20px" sx={{ color: "stroke.muted" }} />+);diff --git a/web/apps/albums/vendor/ente-base/components/SingleInputDialog.tsx b/web/apps/albums/vendor/ente-base/components/SingleInputDialog.tsxnew file mode 100644index 0000000000..9a1cf64b69--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/SingleInputDialog.tsx@@ -0,0 +1,54 @@+import { Dialog, DialogContent, DialogTitle } from "@mui/material";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import React, { useCallback } from "react";+import { SingleInputForm, type SingleInputFormProps } from "./SingleInputForm";++type SingleInputDialogProps = ModalVisibilityProps &+ Omit<SingleInputFormProps, "onCancel"> & {+ /** Title of the dialog. */+ title: string;+ };++/**+ * A dialog that can be used to ask for a single text input using a+ * {@link SingleInputForm}.+ *+ * The dialog closes when the promise returned by the {@link onSubmit} callback+ * fulfills.+ *+ * See also: {@link CollectionNamer}, its older sibling.+ */+export const SingleInputDialog: React.FC<SingleInputDialogProps> = ({+ open,+ onClose,+ onSubmit,+ title,+ ...rest+}) => {+ const handleSubmit: SingleInputFormProps["onSubmit"] = useCallback(+ async (value, setFieldError) => {+ await onSubmit(value, setFieldError);+ onClose();+ },+ [onClose, onSubmit],+ );++ return (+ <Dialog+ open={open}+ onClose={onClose}+ maxWidth="xs"+ fullWidth+ slotProps={{ paper: { sx: { p: "8px 4px 4px 4px" } } }}+ >+ <DialogTitle>{title}</DialogTitle>+ <DialogContent sx={{ "&&&": { pt: 0 } }}>+ <SingleInputForm+ onCancel={onClose}+ onSubmit={handleSubmit}+ {...rest}+ />+ </DialogContent>+ </Dialog>+ );+};diff --git a/web/apps/albums/vendor/ente-base/components/SingleInputForm.tsx b/web/apps/albums/vendor/ente-base/components/SingleInputForm.tsxnew file mode 100644index 0000000000..24c4c24bb8--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/SingleInputForm.tsx@@ -0,0 +1,198 @@+import {+ Stack,+ TextField,+ type ButtonProps,+ type TextFieldProps,+} from "@mui/material";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { LoadingButton } from "ente-base/components/mui/LoadingButton";+import log from "ente-base/log";+import { useFormik } from "formik";+import { t } from "i18next";+import React, { useCallback, useState } from "react";+import { ShowHidePasswordInputAdornment } from "./mui/PasswordInputAdornment";++export type SingleInputFormProps = Pick<+ TextFieldProps,+ "label" | "placeholder" | "autoComplete" | "autoFocus" | "slotProps"+> & {+ /**+ * The type attribute of the HTML input element that will be used.+ *+ * Default is "text".+ *+ * In addition to changing the behaviour of the HTML input element, the+ * {@link SingleInputForm} component also has special casing for type+ * "password", wherein it'll show an adornment at the end of the text field+ * allowing the user to show or hide the password.+ */+ inputType?: TextFieldProps["type"];+ /**+ * The initial value, if any, to prefill in the input.+ */+ initialValue?: string;+ /**+ * Color of the submit button.+ *+ * Default: "accent".+ */+ submitButtonColor?: ButtonProps["color"];+ /**+ * Title for the submit button.+ */+ submitButtonTitle: string;+ /**+ * Cancellation handler.+ *+ * This function is called when the user activates the cancel button in the+ * form.+ *+ * If this is not provided, then only a full width submit button will be+ * shown in the form (below the input).+ */+ onCancel?: () => void;+ /**+ * Submission handler. A callback invoked when the submit button is pressed.+ *+ * During submission, the text input and the submit button are disabled, and+ * an indeterminate progress indicator is shown.+ *+ * If this function rejects then a generic error helper text is shown below+ * the text input, and the input (/ buttons) reenabled.+ *+ * This function is also passed an function that can be used to explicitly+ * set the error message that as shown below the text input when a specific+ * problem occurs during submission.+ *+ * @param name The current value of the text input.+ *+ * @param setFieldError A function that can be called to set the error message+ * shown below the text input if submission fails.+ *+ * Note that if {@link setFieldError} is called, then the {@link onSubmit}+ * function should not throw, otherwise the error message shown by+ * {@link setFieldError} will get overwritten by the generic error message.+ */+ onSubmit:+ | ((name: string, setFieldError: (message: string) => void) => void)+ | ((+ name: string,+ setFieldError: (message: string) => void,+ ) => Promise<void>);+};++/**+ * A TextField and cancel/submit buttons.+ *+ * A common requirement is taking a single textual input from the user. This is+ * a form suitable for that purpose. It contains a single MUI {@link TextField}+ * and two accompanying buttons; one to submit, and one to cancel.+ *+ * Submission is handled as an async function, during which the input is+ * disabled and a loading indicator is shown. Errors during submission are shown+ * as the helper text associated with the text field.+ *+ * The input field in the form takes autoFocus automatically on mount. Turn off+ * the {@link autoFocus} to disable this behaviour if needed.+ */+export const SingleInputForm: React.FC<SingleInputFormProps> = ({+ inputType,+ initialValue,+ autoFocus,+ submitButtonTitle,+ submitButtonColor,+ onCancel,+ onSubmit,+ ...rest+}) => {+ const [showPassword, setShowPassword] = useState(false);++ const handleToggleShowHidePassword = useCallback(+ () => setShowPassword((show) => !show),+ [],+ );++ const formik = useFormik({+ initialValues: { value: initialValue ?? "" },+ onSubmit: async (values, { setFieldError }) => {+ const value = values.value;+ const setValueFieldError = (message: string) =>+ setFieldError("value", message);++ if (!value) {+ setValueFieldError(t("required"));+ return;+ }+ try {+ await onSubmit(value, setValueFieldError);+ } catch (e) {+ log.error(`Failed to submit input ${value}`, e);+ setValueFieldError(t("generic_error"));+ }+ },+ });++ const submitButton = (+ <LoadingButton+ fullWidth+ type="submit"+ loading={formik.isSubmitting}+ color={submitButtonColor ?? "accent"}+ >+ {submitButtonTitle}+ </LoadingButton>+ );++ // [Note: Use space as default TextField helperText]+ //+ // For MUI text fields that use a conditional helperText, e.g. in case of+ // errors, use an space as the default helperText in the other cases to+ // avoid a layout shift when the helperText is conditionally shown.++ return (+ <form onSubmit={formik.handleSubmit}>+ <TextField+ name="value"+ value={formik.values.value}+ onChange={formik.handleChange}+ type={showPassword ? "text" : (inputType ?? "text")}+ fullWidth+ autoFocus={autoFocus ?? true}+ margin="normal"+ disabled={formik.isSubmitting}+ error={!!formik.errors.value}+ helperText={formik.errors.value ?? " "}+ slotProps={{+ input:+ inputType == "password"+ ? {+ endAdornment: (+ <ShowHidePasswordInputAdornment+ showPassword={showPassword}+ onToggle={+ handleToggleShowHidePassword+ }+ />+ ),+ }+ : {},+ }}+ {...rest}+ />+ {onCancel ? (+ <Stack direction="row" sx={{ gap: "12px" }}>+ <FocusVisibleButton+ fullWidth+ color="secondary"+ onClick={onCancel}+ >+ {t("cancel")}+ </FocusVisibleButton>+ {submitButton}+ </Stack>+ ) : (+ submitButton+ )}+ </form>+ );+};diff --git a/web/apps/albums/vendor/ente-base/components/Typography.tsx b/web/apps/albums/vendor/ente-base/components/Typography.tsxnew file mode 100644index 0000000000..9fa71e7b73--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/Typography.tsx@@ -0,0 +1,37 @@+import { styled, Typography } from "@mui/material";++/**+ * A variant of {@link Typography} that inserts ellipsis instead of wrapping the+ * text over multiple lines, or letting it overflow.+ *+ * Refs:+ * - https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_text/Wrapping_breaking_text+ * - https://developer.mozilla.org/en-US/docs/Web/CSS/white-space+ */+export const EllipsizedTypography = styled(Typography)`+ /* Initial value of overflow is visible. Set overflow (the handling of+ content that is too small for the container in the inline direction) to+ hidden instead. */+ overflow: hidden;+ /* Specify handling of text when it overflows, asking the browser to insert+ ellipsis instead of clipping.++ Note that both overflow and text-overflow are required.+ */+ text-overflow: ellipsis;+ /* Don't automatically wrap the text by inserting line breaks. */+ white-space: nowrap;+`;++/**+ * A variant of {@link EllipsizedTypography} that takes up to 2 lines.+ */+export const Ellipsized2LineTypography = styled(Typography)`+ overflow: hidden;+ text-overflow: ellipsis;+ display: -webkit-box;+ -webkit-line-clamp: 2; /* number of lines to show */+ line-clamp: 2;+ -webkit-box-orient: vertical;+ word-break: break-word;+`;diff --git a/web/apps/albums/vendor/ente-base/components/containers.tsx b/web/apps/albums/vendor/ente-base/components/containers.tsxnew file mode 100644index 0000000000..d2ae57d3ad--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/containers.tsx@@ -0,0 +1,67 @@+import { Stack, styled } from "@mui/material";++/**+ * A {@link Stack} that takes up at least the height of the entire viewport, and+ * centers its children both vertically and horizontally.+ */+export const Stack100vhCenter = styled(Stack)`+ min-height: 100vh;+ justify-content: center;+ align-items: center;+`;++/**+ * A flexbox with justify content set to space-between and item alignment set to+ * center.+ *+ * There is also another SpaceBetweenFlex in the old shared package, but that+ * one also sets width: 100%. As such, that one should be considered deprecated+ * and its uses moved to this one when possible (so that we can then see where+ * the width: 100% is essential).+ */+export const SpacedRow = styled("div")`+ display: flex;+ justify-content: space-between;+ align-items: center;+`;++/**+ * A flexbox that shows its children after centering them both vertically and+ * horizontally.+ */+export const CenteredRow = styled("div")`+ display: flex;+ justify-content: center;+ align-items: center;+`;++/**+ * A flexbox that fills the entire flex direction, and shows its children after+ * centering them both vertically and horizontally.+ */+export const CenteredFill = styled("div")`+ flex: 1;+ display: flex;+ justify-content: center;+ align-items: center;+`;++/**+ * An empty overlay on top of the nearest relative positioned ancestor.+ *+ * {@link Overlay} is an an absolute positioned div that fills the entire+ * nearest relatively positioned ancestor. It is usually used in tandem with a+ * derivate of {@link BaseTile} or {@link BaseTileButton} to show various+ * indicators on top of thumbnails; but it can be used in any context where we+ * want to overlay (usually) transparent content on top of a component.+ *+ * For filling much larger areas (e.g. showing a translucent overlay on top of+ * the entire screen), use the MUI {@link Backdrop} instead.+ */+export const Overlay = styled("div")`+ position: absolute;+ width: 100%;+ height: 100%;+ top: 0;+ left: 0;+`;diff --git a/web/apps/albums/vendor/ente-base/components/loaders.tsx b/web/apps/albums/vendor/ente-base/components/loaders.tsxnew file mode 100644index 0000000000..8e958c067e--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/loaders.tsx@@ -0,0 +1,42 @@+import { Backdrop } from "@mui/material";+import { Stack100vhCenter } from "ente-base/components/containers";+import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";+import React from "react";++/**+ * A centered activity indicator shown in a container that fills up the entire+ * width and height of the viewport.+ *+ * This is meant as a root component of a page, e.g., during initial load.+ */+export const LoadingIndicator: React.FC = () => (+ <Stack100vhCenter>+ <ActivityIndicator />+ </Stack100vhCenter>+);++/**+ * An translucent overlay that covers the entire viewport and shows an activity+ * indicator in its center.+ *+ * Used as a overlay during blocking actions. The use of this component is not+ * recommended for new code.+ */+export const TranslucentLoadingOverlay: React.FC = () => (+ <Backdrop+ // Specifying open here causes us to lose animations. This is not+ // optimal, but fine for now since this the use of this is limited to a+ // few interstitial overlays, and if refactoring consider replacing this+ // entirely with a more localized activity indicator.+ open={true}+ sx={{+ backgroundColor: "var(--mui-palette-backdrop-muted)",+ backdropFilter: "blur(30px) opacity(95%)",+ /* Above the highest possible MUI z-index, that of the MUI tooltip+ See: https://mui.com/material-ui/customization/default-theme/ */+ zIndex: "calc(var(--mui-zIndex-tooltip) + 1)",+ }}+ >+ <ActivityIndicator />+ </Backdrop>+);diff --git a/web/apps/albums/vendor/ente-base/components/mui/ActivityIndicator.tsx b/web/apps/albums/vendor/ente-base/components/mui/ActivityIndicator.tsxnew file mode 100644index 0000000000..bd9e7620c2--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/mui/ActivityIndicator.tsx@@ -0,0 +1,29 @@+import {+ CircularProgress,+ Stack,+ Typography,+ type CircularProgressProps,+} from "@mui/material";+import type React from "react";++/**+ * A standard {@link CircularProgress} for use in our code.+ *+ * If a child is specified, it is wrapped in a Typography and shown as a caption+ * below the {@link CircularProgress}.+ *+ * While it does take and forward props to the the underlying+ * {@link CircularProgress}, if you find yourself needing to customize it too+ * much, consider directly using a {@link CircularProgress} instead.+ */+export const ActivityIndicator: React.FC<+ React.PropsWithChildren<CircularProgressProps>+> = ({ children, ...rest }) =>+ children ? (+ <Stack sx={{ gap: 2, alignItems: "center" }}>+ <CircularProgress color="accent" size={24} {...rest} />+ <Typography sx={{ color: "text.muted" }}>{children}</Typography>+ </Stack>+ ) : (+ <CircularProgress color="accent" size={32} {...rest} />+ );diff --git a/web/apps/albums/vendor/ente-base/components/mui/DialogCloseIconButton.tsx b/web/apps/albums/vendor/ente-base/components/mui/DialogCloseIconButton.tsxnew file mode 100644index 0000000000..6b8fc24856--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/mui/DialogCloseIconButton.tsx@@ -0,0 +1,22 @@+import CloseIcon from "@mui/icons-material/Close";+import { IconButton } from "@mui/material";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import { t } from "i18next";+import React from "react";++type DialogCloseIconButtonProps = Omit<ModalVisibilityProps, "open">;++/**+ * A convenience {@link IconButton} commonly needed on {@link Dialog}s, at the+ * top right, to allow the user to close the dialog.+ *+ * Note that an explicit "Cancel" button is a better approach whenever possible,+ * so use this sparingly.+ */+export const DialogCloseIconButton: React.FC<DialogCloseIconButtonProps> = ({+ onClose,+}) => (+ <IconButton aria-label={t("close")} color="secondary" onClick={onClose}>+ <CloseIcon />+ </IconButton>+);diff --git a/web/apps/albums/vendor/ente-base/components/mui/FocusVisibleButton.tsx b/web/apps/albums/vendor/ente-base/components/mui/FocusVisibleButton.tsxnew file mode 100644index 0000000000..cb7e3e0636--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/mui/FocusVisibleButton.tsx@@ -0,0 +1,23 @@+import { Button, styled, type ButtonProps } from "@mui/material";+import React from "react";++export const RippleDisabledButton: React.FC<ButtonProps> = (props) => (+ <Button disableRipple {...props} />+);++/**+ * A MUI {@link Button} that shows a keyboard focus indicator (e.g. when the+ * user tabs to it) and also an affordance to indicate when it is activated.+ */+export const FocusVisibleButton = styled(RippleDisabledButton)(+ ({ theme }) => `+ &.Mui-focusVisible {+ outline: 1px solid ${theme.vars.palette.stroke.base};+ outline-offset: 2px;+ }+ &:active {+ outline: 1px solid ${theme.vars.palette.stroke.faint};+ outline-offset: 1px;+ }+`,+);diff --git a/web/apps/albums/vendor/ente-base/components/mui/LoadingButton.tsx b/web/apps/albums/vendor/ente-base/components/mui/LoadingButton.tsxnew file mode 100644index 0000000000..84ae32a907--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/mui/LoadingButton.tsx@@ -0,0 +1,41 @@+import { CircularProgress, type ButtonProps } from "@mui/material";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { isSxArray } from "ente-base/components/utils/sx";+import React from "react";++/**+ * A button that shows a indeterminate progress indicator if the {@link loading}+ * prop is set.+ *+ * The button is also disabled when in the loading state.+ */+export const LoadingButton: React.FC<ButtonProps & { loading?: boolean }> = ({+ loading,+ disabled,+ color,+ sx,+ children,+ ...rest+}) =>+ loading ? (+ <FocusVisibleButton+ {...{ color }}+ disabled+ sx={[+ {+ "&.Mui-disabled": {+ backgroundColor: `${color}.main`,+ color: `${color}.contrastText`,+ },+ },+ ...(sx ? (isSxArray(sx) ? sx : [sx]) : []),+ ]}+ {...rest}+ >+ <CircularProgress size={20} sx={{ color: "inherit" }} />+ </FocusVisibleButton>+ ) : (+ <FocusVisibleButton {...{ color, disabled, sx }} {...rest}>+ {children}+ </FocusVisibleButton>+ );diff --git a/web/apps/albums/vendor/ente-base/components/mui/PasswordInputAdornment.tsx b/web/apps/albums/vendor/ente-base/components/mui/PasswordInputAdornment.tsxnew file mode 100644index 0000000000..08c4771bc6--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/mui/PasswordInputAdornment.tsx@@ -0,0 +1,49 @@+import VisibilityIcon from "@mui/icons-material/Visibility";+import VisibilityOffIcon from "@mui/icons-material/VisibilityOff";+import { IconButton, InputAdornment } from "@mui/material";+import { t } from "i18next";+import React from "react";++interface ShowHidePasswordInputAdornmentProps {+ /**+ * When `true`, the password is being shown.+ */+ showPassword: boolean;+ /**+ * Called when the user wants to toggle the state of {@link showPassword}.+ */+ onToggle: () => void;+}++/**+ * A MUI {@link InputAdornment} that can be used at the trailing edge of a+ * password input field to allow the user to toggle the visibility of the+ * password.+ */+export const ShowHidePasswordInputAdornment: React.FC<+ ShowHidePasswordInputAdornmentProps+> = ({ showPassword, onToggle: onToggle }) => {+ // Prevent password field from losing focus when the input adornment is+ // clicked by ignoring both the mouse up and down events. This is the+ // approach mentioned in the MUI docs.+ // https://mui.com/material-ui/react-text-field/#input-adornments+ const preventDefault = (event: React.MouseEvent<HTMLButtonElement>) => {+ event.preventDefault();+ };++ return (+ <InputAdornment position="end">+ <IconButton+ tabIndex={-1}+ color="secondary"+ aria-label={t("show_or_hide_password")}+ onClick={onToggle}+ onMouseUp={preventDefault}+ onMouseDown={preventDefault}+ edge="end"+ >+ {showPassword ? <VisibilityOffIcon /> : <VisibilityIcon />}+ </IconButton>+ </InputAdornment>+ );+};diff --git a/web/apps/albums/vendor/ente-base/components/mui/SidebarDrawer.tsx b/web/apps/albums/vendor/ente-base/components/mui/SidebarDrawer.tsxnew file mode 100644index 0000000000..93862059e6--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/mui/SidebarDrawer.tsx@@ -0,0 +1,206 @@+import ArrowBackIcon from "@mui/icons-material/ArrowBack";+import CloseIcon from "@mui/icons-material/Close";+import {+ Box,+ Drawer,+ IconButton,+ Stack,+ styled,+ Typography,+ type DrawerProps,+} from "@mui/material";+import { isDesktop } from "ente-base/app";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import React from "react";++/**+ * A MUI {@link Drawer} with a standard set of styling that we use for our left+ * and right sidebar panels.+ *+ * It is width limited to 375px, and always at full width. It also has a default+ * padding.+ *+ * It also does some trickery with a sticky opaque bar to ensure that the+ * content scrolls below our inline title bar on desktop.+ */+export const SidebarDrawer: React.FC<DrawerProps> = ({+ slotProps,+ children,+ ...rest+}) => (+ <Drawer+ {...rest}+ slotProps={{+ ...(slotProps ?? {}),+ paper: {+ sx: {+ maxWidth: "375px",+ width: "100%",+ scrollbarWidth: "thin",+ // Need to increase specificity to override inherited padding.+ "&&": { padding: 0 },+ },+ },+ }}+ >+ {isDesktop && <AppTitlebarBackdrop />}+ <Box sx={{ p: 1 }}>{children}</Box>+ </Drawer>+);++/**+ * When running on desktop, we adds a sticky opaque bar at the top of the+ * sidebar with a z-index greater than the expected sidebar contents. This+ * ensures that any title bar overlays added by the system (e.g. the traffic+ * lights on macOS) have a opaque-ish background and the sidebar contents scroll+ * underneath them.+ *+ * See: [Note: Customize the desktop title bar]+ */+const AppTitlebarBackdrop = styled("div")(({ theme }) => ({+ position: "sticky",+ top: 0,+ left: 0,+ width: "100%",+ minHeight: "env(titlebar-area-height, 30px)",+ zIndex: 1,+ backgroundColor: theme.vars.palette.backdrop.muted,+ backdropFilter: "blur(12px)",+}));++/**+ * Common props for a {@link NestedSidebarDrawer} component. In addition to the+ * regular modal visibility controls for opening and closing itself, these also+ * surface an option to close the entire drawer.+ */+export type NestedSidebarDrawerVisibilityProps = ModalVisibilityProps & {+ /**+ * Called when the user wants to close the entire stack of drawers.+ *+ * Note that this does not automatically imply onClose. Each step in the+ * nesting will have to chain their own onCloses to construct a new+ * `onRootClose` suitable for passing to its children.+ */+ onRootClose: () => void;+};++/**+ * A variant of {@link SidebarDrawer} for second level, nested drawers that are+ * shown atop an already visible {@link SidebarDrawer}.+ */+export const NestedSidebarDrawer: React.FC<+ NestedSidebarDrawerVisibilityProps & DrawerProps+> = ({ onClose, onRootClose, ...rest }) => {+ // Intercept backdrop taps and repurpose them to close the entire stack.+ const handleClose: DrawerProps["onClose"] = (_, reason) => {+ if (reason == "backdropClick") {+ onClose();+ onRootClose();+ } else {+ onClose();+ }+ };++ // MUI doesn't (currently, AFAIK) have support for nested drawers, so we+ // emulate that by showing a drawer atop another. To make it fit, we need to+ // modify a few knobs.++ return (+ <SidebarDrawer+ // Disable the transition (otherwise our nested drawer visibly+ // slides in from the wrong direction).+ transitionDuration={0}+ // Make the backdrop transparent (otherwise we end up with two of+ // them - one from the original drawer, and one from this nested+ // one).+ //+ // Note that there is an easy way to hide the backdrop (using the+ // `hideBackdrop` attribute), but that takes away our ability to+ // intercept backdrop clicks to close it.+ slotProps={{+ backdrop: { sx: { "&&&": { backgroundColor: "transparent" } } },+ }}+ onClose={handleClose}+ {...rest}+ />+ );+};++type SidebarDrawerTitlebarProps = Pick<+ NestedSidebarDrawerVisibilityProps,+ "onClose" | "onRootClose"+> & {+ /** Title for the drawer. */+ title: string;+ /** An optional secondary caption shown below the title. */+ caption?: string;+ /**+ * An optional action button shown alongwith the close button at the+ * trailing edge of the sidebar.+ */+ actionButton?: React.ReactNode;+};++/**+ * A bar with a title and back / close buttons, suitable for being used in+ * tandem with a {@link NestedSidebarDrawer}.+ */+export const SidebarDrawerTitlebar: React.FC<SidebarDrawerTitlebarProps> = ({+ title,+ caption,+ onClose,+ onRootClose,+ actionButton,+}) => (+ <Stack sx={{ gap: "4px" }}>+ <Stack direction="row" sx={{ justifyContent: "space-between" }}>+ <IconButton onClick={onClose} color="primary">+ <ArrowBackIcon />+ </IconButton>+ <Stack direction="row" sx={{ gap: "4px" }}>+ {actionButton && actionButton}+ <IconButton onClick={onRootClose} color="secondary">+ <CloseIcon />+ </IconButton>+ </Stack>+ </Stack>+ <Stack sx={{ px: "16px", gap: "4px" }}>+ <Typography variant="h3">{title}</Typography>+ <Typography+ variant="small"+ sx={{+ color: "text.muted",+ wordBreak: "break-all",+ px: "1px",+ minHeight: "17px",+ }}+ >+ {caption}+ </Typography>+ </Stack>+ </Stack>+);++/**+ * A variant of {@link NestedSidebarDrawer} that additionally shows a title.+ *+ * {@link NestedSidebarDrawer} is for second level, nested drawers that are+ * shown atop an already visible {@link SidebarDrawer}. This component combines+ * the {@link NestedSidebarDrawer} with a {@link SidebarDrawerTitlebar} and some+ * standard spacing, so that the caller can just provide the content as the+ * children.+ */+export const TitledNestedSidebarDrawer: React.FC<+ React.PropsWithChildren<+ NestedSidebarDrawerVisibilityProps &+ Pick<DrawerProps, "anchor"> &+ SidebarDrawerTitlebarProps+ >+> = ({ open, onClose, onRootClose, anchor, children, ...rest }) => (+ <NestedSidebarDrawer {...{ open, onClose, onRootClose, anchor }}>+ <Stack sx={{ gap: "4px", py: "12px" }}>+ <SidebarDrawerTitlebar {...{ onClose, onRootClose }} {...rest} />+ {children}+ </Stack>+ </NestedSidebarDrawer>+);diff --git a/web/apps/albums/vendor/ente-base/components/mui/index.tsx b/web/apps/albums/vendor/ente-base/components/mui/index.tsxnew file mode 100644index 0000000000..a440a90964--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/mui/index.tsx@@ -0,0 +1,15 @@+import { IconButton, styled } from "@mui/material";++/**+ * Convenience typed props for a component that acts like a push button.+ */+export interface ButtonishProps {+ onClick: () => void;+}++/**+ * A MUI {@link IconButton} filled in with a faint background.+ */+export const FilledIconButton = styled(IconButton)(({ theme }) => ({+ backgroundColor: theme.vars.palette.fill.faint,+}));diff --git a/web/apps/albums/vendor/ente-base/components/pages/404.tsx b/web/apps/albums/vendor/ente-base/components/pages/404.tsxnew file mode 100644index 0000000000..3940190c92--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/pages/404.tsx@@ -0,0 +1,32 @@+import { useRouter } from "next/router";+import React, { useEffect } from "react";++/**+ * A reusable 404 page.+ */+const Page: React.FC = () => {+ // [Note: 404 back to home]+ //+ // In the desktop app, if the user presses the refresh button when the URL+ // has an attached query parameter, e.g. "/gallery?collectionId=xxx", then+ // the code in next-electron-server blindly appends the html extension to+ // this URL, resulting in it trying to open "gallery?collectionId=xxx.html"+ // instead of "gallery.html". It doesn't find such a file, causing it open+ // "404.html" (the static file generated from this file).+ //+ // One way around is to patch the package, e.g.+ // https://github.com/ente-io/next-electron-server/pull/1/files+ //+ // However, redirecting back to the root is arguably a better fallback in+ // all cases (even when running on our website), since our app is a SPA.++ const router = useRouter();++ useEffect(() => {+ void router.push("/");+ }, [router]);++ return <></>;+};++export default Page;diff --git a/web/apps/albums/vendor/ente-base/components/utils/dialog.tsx b/web/apps/albums/vendor/ente-base/components/utils/dialog.tsxnew file mode 100644index 0000000000..04cdc48711--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/utils/dialog.tsx@@ -0,0 +1,67 @@+import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline";+import { t } from "i18next";+import { useCallback, useState } from "react";+import type { MiniDialogAttributes } from "../MiniDialog";++/**+ * A React hook for simplifying the provisioning of a {@link showMiniDialog}+ * function to inject in app contexts, and of the other props that are needed to+ * be passed to the {@link AttributedMiniDialog}.+ */+export const useAttributedMiniDialog = () => {+ const [attributes, setAttributes] = useState<+ MiniDialogAttributes | undefined+ >(undefined);++ const [open, setOpen] = useState(false);++ const showMiniDialog = useCallback(+ (newAttributes: MiniDialogAttributes) => {+ setAttributes((attributes) =>+ attributes?.nonReplaceable ? attributes : newAttributes,+ );+ setOpen(true);+ },+ [],+ );++ const handleClose = useCallback(() => setOpen(false), []);++ return {+ showMiniDialog,+ miniDialogProps: { open, onClose: handleClose, attributes },+ };+};++/**+ * A convenience function to construct {@link MiniDialogAttributes} for showing+ * error dialogs.+ *+ * It takes one or two arguments.+ *+ * - If both are provided, then the first one is taken as the title and the+ * second one as the message.+ *+ * - Otherwise it sets a default title and use the only argument as the message.+ */+export const errorDialogAttributes = (+ messageOrTitle: string,+ optionalMessage?: string,+): MiniDialogAttributes => {+ const title = optionalMessage ? messageOrTitle : t("error");+ const message = optionalMessage ?? messageOrTitle;++ return {+ title,+ icon: <ErrorOutlineIcon />,+ message,+ continue: { color: "critical" },+ cancel: false,+ };+};++export const genericErrorDialogAttributes = () =>+ errorDialogAttributes(t("generic_error"));++export const genericRetriableErrorDialogAttributes = () =>+ errorDialogAttributes(t("generic_error_retry"));diff --git a/web/apps/albums/vendor/ente-base/components/utils/hooks-app.ts b/web/apps/albums/vendor/ente-base/components/utils/hooks-app.tsnew file mode 100644index 0000000000..3c738a1781--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/utils/hooks-app.ts@@ -0,0 +1,79 @@+import { setupI18n } from "ente-base/i18n";+import { disableDiskLogs } from "ente-base/log";+import { logUnhandledErrorsAndRejections } from "ente-base/log-web";+import { useRouter } from "next/router";+import { useEffect, useState } from "react";++/**+ * A hook that initializes the localization library that we use.+ *+ * This is only meant to be called from the top level `_app.tsx`, as this+ * initialization is intended to happen only once for the lifetime of the app.+ *+ * @returns a boolean which will be set to true when the localized strings have+ * been loaded.+ */+export const useSetupI18n = () => {+ const [isI18nReady, setIsI18nReady] = useState(false);++ useEffect(() => {+ void setupI18n().finally(() => setIsI18nReady(true));+ }, []);++ return isI18nReady;+};++interface SetupLoggingOptions {+ /** If true, then the logs will not be saved to local storage. */+ disableDiskLogs?: boolean;+}++/**+ * A hook that initializes the logging subsystem.+ *+ * This is only meant to be called from the top level `_app.tsx`, as this+ * initialization is intended to happen only once for the lifetime of the app.+ *+ * @param opts Optional {@link SetupLoggingOptions} to customize the setup.+ */+export const useSetupLogs = (opts?: SetupLoggingOptions) => {+ useEffect(() => {+ if (opts?.disableDiskLogs) disableDiskLogs();+ logUnhandledErrorsAndRejections(true);+ return () => logUnhandledErrorsAndRejections(false);+ }, []);+};++/**+ * A hook that keeps track of whether or not we are in the middle of a Next.js+ * route change.+ *+ * The top level app component uses this to show a loading indicator.+ */+export const useIsRouteChangeInProgress = () => {+ const router = useRouter();+ const [loading, setLoading] = useState(false);++ useEffect(() => {+ const handleRouteChangeStart = (url: string) => {+ const newPathname = url.split("?")[0];+ if (window.location.pathname !== newPathname) {+ setLoading(true);+ }+ };++ const handleRouteChangeComplete = () => {+ setLoading(false);+ };++ router.events.on("routeChangeStart", handleRouteChangeStart);+ router.events.on("routeChangeComplete", handleRouteChangeComplete);++ return () => {+ router.events.off("routeChangeStart", handleRouteChangeStart);+ router.events.off("routeChangeComplete", handleRouteChangeComplete);+ };+ }, [router]);++ return loading;+};diff --git a/web/apps/albums/vendor/ente-base/components/utils/hooks.ts b/web/apps/albums/vendor/ente-base/components/utils/hooks.tsnew file mode 100644index 0000000000..f89e7abc1d--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/utils/hooks.ts@@ -0,0 +1,79 @@+import { useMediaQuery, useTheme } from "@mui/material";+import { useCallback, useEffect, useRef, useState } from "react";++/**+ * Return true if the screen width is classified as a small size. This is often+ * treated as an (rather arbitrary) cutoff for "mobile" sized screens.+ *+ * We use the MUI "sm" (small, 600px) breakpoint as the cutoff. This hook will+ * return true if the size of the window's width is less than 600px.+ */+export const useIsSmallWidth = () =>+ useMediaQuery(useTheme().breakpoints.down("sm"));++/**+ * Heuristic "isMobileOrTablet"-ish check using a pointer media query.+ *+ * The absence of fine-resolution pointing device can be taken a quick and proxy+ * for detecting if the user is using a mobile or tablet.+ *+ * This is of course not going to work in all scenarios (e.g. someone connecting+ * their mice to their tablet), but ad-hoc user agent checks are not problem+ * free either. This media query should be accurate enough for cases where false+ * positives will degrade gracefully.+ *+ * See: https://github.com/mui/mui-x/issues/10039+ */+export const useIsTouchscreen = () =>+ useMediaQuery("(hover: none) and (pointer: coarse)", { noSsr: true });++/**+ * A hook that manages a transient "copied" state.+ *+ * @param text The text to copy.+ *+ * @returns a tuple containing a boolean {@link copied} indicating if a copy has+ * just successfully happened, and a function {@link onCopy} to trigger the+ * copy.+ */+export const useClipboardCopy = (+ text: string,+): [copied: boolean, onCopy: () => void] => {+ const [copied, setCopied] = useState(false);++ const handleCopyLink = useCallback(() => {+ void navigator.clipboard.writeText(text).then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1000);+ });+ }, [text]);++ return [copied, handleCopyLink];+};++/**+ * A hook that runs a callback at a specified interval.+ *+ * @param callback The function to call on each interval tick.+ * @param delay The interval in milliseconds, or null to pause the interval.+ */+export const useInterval = (+ callback: () => void,+ delay: number | null,+): void => {+ const savedCallback = useRef(callback);++ // Remember the latest callback+ useEffect(() => {+ savedCallback.current = callback;+ }, [callback]);++ // Set up the interval+ useEffect(() => {+ if (delay === null) return;++ const tick = () => savedCallback.current();+ const id = setInterval(tick, delay);+ return () => clearInterval(id);+ }, [delay]);+};diff --git a/web/apps/albums/vendor/ente-base/components/utils/modal.ts b/web/apps/albums/vendor/ente-base/components/utils/modal.tsnew file mode 100644index 0000000000..0b40c9d786--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/utils/modal.ts@@ -0,0 +1,28 @@+import { useCallback, useState } from "react";++/**+ * Common props that control the display of a modal (e.g. dialog, drawer)+ * component.+ */+export interface ModalVisibilityProps {+ /** If `true`, the component is shown. */+ open: boolean;+ /** Callback fired when the component requests to be closed. */+ onClose: () => void;+}++/**+ * A convenience hook for keeping the state for opening and closing a modal, and+ * exposing a function to close the modal whose identity is stable.+ *+ * These props can be passed verbatim to our components that expect+ * {@link ModalVisibilityProps}.+ */+export const useModalVisibility = () => {+ const [open, setOpen] = useState(false);++ const show = useCallback(() => setOpen(true), []);+ const onClose = useCallback(() => setOpen(false), []);++ return { show, props: { open, onClose } };+};diff --git a/web/apps/albums/vendor/ente-base/components/utils/mui-theme.d.ts b/web/apps/albums/vendor/ente-base/components/utils/mui-theme.d.tsnew file mode 100644index 0000000000..1cdcdef9e2--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/utils/mui-theme.d.ts@@ -0,0 +1,266 @@+import type { PaletteColor } from "@mui/material";+import React from "react";++// Import the module augmentation that provides types for `theme.vars.*`.+import type {} from "@mui/material/themeCssVarsAugmentation";++// Add new tokens to the Palette.+//+// https://mui.com/material-ui/customization/css-theme-variables/usage/#adding-new-theme-tokens++declare module "@mui/material/styles" {+ /**+ * Add new "background" color tokens, giving us:+ *+ * - background.default+ * - background.paper+ * - background.paper2+ * - background.elevatedPaper+ * - background.searchInput+ */+ interface TypeBackground {+ /**+ * A second level elevation, indicating a paper within a paper.+ */+ paper2: string;+ /**+ * The first among background.paper and background.paper2 that is not+ * the same as the default background.+ *+ * In light mode, background.default and background.paper are the same,+ * while in dark mode background.paper is already elevated. This+ * property can be used to obtain the first paper that is actually+ * elevated above the background irrespective of the theme.+ */+ elevatedPaper: string;+ /**+ * Background color for the search input area.+ */+ searchInput: string;+ }++ /**+ * Define a new set of tokens for the "text" color in the palette which+ * matches the strength triads we use for stroke and fill.+ *+ * Since there is no way to override or replace the existing tokens, we can+ * only augment the interface with our new tokens. However, our code should+ * NOT use the default tokens provided by MUI:+ *+ * - text.primary <- Don't use+ * - text.secondary <- Don't use+ * - text.disabled <- Don't use+ *+ * Instead, use these three:+ *+ * - text.base+ * - text.muted+ * - text.faint+ */+ interface TypeText {+ base: string;+ muted: string;+ faint: string;+ }++ interface Palette {+ /**+ * The main brand color. e.g. the "Ente green", the "Auth purple".+ *+ * This does not vary with the color scheme.+ */+ accent: PaletteColor;+ /**+ * The color for potentially dangerous actions, errors, or other things+ * we would like to call the user's attention out to.+ *+ * MUI has an "error" palette color, but that seems to semantically not+ * gel with all uses. e.g. it feels weird to create a button with+ * color="error".+ *+ * This does not vary with the color scheme.+ */+ critical: PaletteColor;+ /**+ * Neutral transparent colors for the stroke of icons and other outlines.+ *+ * These change with the color scheme.+ *+ * They come in three strengths which are meant to play nicely with the+ * corresponding strengths of "text.*" and "fill.*", and an extra+ * "fainter" variant for ad-hoc uses.+ */+ stroke: { base: string; muted: string; faint: string; fainter: string };+ /**+ * Neutral transparent colors for filling small areas like icon or+ * button backgrounds.+ *+ * These change with the color scheme.+ *+ * They come in three strengths which are meant to play nicely with the+ * corresponding strengths of "text.*" and "stroke.*", plus extra ones.+ *+ * Some strengths also have a hover variant, useful to indicate hover on+ * buttons and menu items that use the corresponding fill.+ */+ fill: {+ base: string;+ muted: string;+ faint: string;+ faintHover: string;+ fainter: string;+ };+ /**+ * Transparent background fills that serve as the backdrop of modals,+ * dialogs and drawers etc.+ *+ * These change with the color scheme.+ */+ backdrop: { base: string; muted: string; faint: string };+ /**+ * Various ad-hoc fixed colors used by our designs.+ *+ * These do not change with the color scheme.+ *+ * Some places in the code also use the grey PaletteColor provided by+ * MUI whose corresponding color values can be seen at+ * https://mui.com/material-ui/customization/default-theme/+ */+ fixed: {+ /**+ * The color of a switch when it is enabled.+ */+ switchOn: string;+ /**+ * A subset of the dark mode colors, fixed so that they don't change+ * even when the app is in light mode.+ */+ dark: {+ background: Omit<TypeBackground, "elevatedPaper">;+ text: Omit<TypeText, "primary" | "secondary" | "disabled">;+ divider: string;+ };+ };+ /**+ * MUI as of v6 does not allow customizing shadows easily. This is due+ * for change: https://github.com/mui/material-ui/issues/44291.+ *+ * Meanwhile use a custom variable. Since it is specific to the color+ * scheme, keep it inside the palette.+ */+ boxShadow: {+ /**+ * Drop shadow for the MUI {@link Paper}. In particular, this also+ * gets used as the drop shadow for {@link Dialog} (which uses a+ * {@link Paper} to embed its contents).+ */+ paper: string;+ /**+ * Drop shadow for the MUI {@link Menu} and other small floating+ * elements like the {@link Notification} {@link Snackbar}.+ */+ menu: string;+ /** Currently unused. */+ button: string;+ };+ }++ interface PaletteOptions {+ accent?: Palette["accent"];+ critical?: Palette["critical"];+ stroke?: Palette["stroke"];+ fill?: Palette["fill"];+ backdrop?: Palette["backdrop"];+ fixed?: Palette["fixed"];+ boxShadow?: Palette["boxShadow"];+ }+}++// Make our custom palette colors available for use as the color prop of various+// MUI components.++declare module "@mui/material/Button" {+ interface ButtonPropsColorOverrides {+ // Turn off MUI provided palette colors we don't use.+ error: false;+ success: false;+ info: false;+ warning: false;+ // Add our custom palette colors.+ accent: true;+ critical: true;+ }+}++declare module "@mui/material/IconButton" {+ interface IconButtonPropsColorOverrides {+ // Turn off MUI provided palette colors we don't use.+ error: false;+ success: false;+ info: false;+ warning: false;+ }+}++declare module "@mui/material/Checkbox" {+ interface CheckboxPropsColorOverrides {+ accent: true;+ }+}++declare module "@mui/material/Switch" {+ interface SwitchPropsColorOverrides {+ accent: true;+ }+}++declare module "@mui/material/SvgIcon" {+ interface SvgIconPropsColorOverrides {+ accent: true;+ }+}++declare module "@mui/material/CircularProgress" {+ interface CircularProgressPropsColorOverrides {+ accent: true;+ }+}++// Tell TypeScript about our Typography variants+//+// https://mui.com/material-ui/customization/typography/#adding-amp-disabling-variants++declare module "@mui/material/styles" {+ interface TypographyVariants {+ body: React.CSSProperties;+ small: React.CSSProperties;+ mini: React.CSSProperties;+ tiny: React.CSSProperties;+ }++ interface TypographyVariantsOptions {+ body?: React.CSSProperties;+ small?: React.CSSProperties;+ mini?: React.CSSProperties;+ tiny?: React.CSSProperties;+ }+}++declare module "@mui/material/Typography" {+ // Update the Typography's variant prop options.+ interface TypographyPropsVariantOverrides {+ // Turn off MUI provided variants we don't use.+ subtitle1: false;+ subtitle2: false;+ body1: false;+ body2: false;+ caption: false;+ button: false;+ overline: false;+ // Add our custom variants.+ body: true;+ small: true;+ mini: true;+ tiny: true;+ }+}diff --git a/web/apps/albums/vendor/ente-base/components/utils/sx.ts b/web/apps/albums/vendor/ente-base/components/utils/sx.tsnew file mode 100644index 0000000000..e3f0cf301e--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/utils/sx.ts@@ -0,0 +1,25 @@+import { type SxProps, type Theme } from "@mui/material";+import { type SystemStyleObject } from "@mui/system";++/**+ * Wrapper over Array.isArray that retains the TypeScript type for SxProps when+ * trying to spread them.+ *+ * The recommended pattern to use sx props in our own component (whilst+ * forwarding them to the underlying MUI component) is to:+ *+ * ...(Array.isArray(sx) ? sx : [sx])+ *+ * However, currently (as of MUI v6), this runs afoul of the+ * 'no-unsafe-assignment' eslint rule. This function provides a workaround, and+ * can be used as a drop-in replacement of Array.isArray in the above pattern.+ *+ * Ref: https://github.com/mui/material-ui/issues/37730+ */+export const isSxArray = (+ sx: SxProps<Theme>,+): sx is readonly (+ | boolean+ | SystemStyleObject<Theme>+ | ((theme: Theme) => SystemStyleObject<Theme>)+)[] => Array.isArray(sx);diff --git a/web/apps/albums/vendor/ente-base/components/utils/theme.ts b/web/apps/albums/vendor/ente-base/components/utils/theme.tsnew file mode 100644index 0000000000..17f46cc8cc--- /dev/null+++ b/web/apps/albums/vendor/ente-base/components/utils/theme.ts@@ -0,0 +1,1139 @@+import type { Theme, TypographyVariantsOptions } from "@mui/material";+import { createTheme } from "@mui/material";+import type { Components } from "@mui/material/styles";+import type { AppName } from "ente-base/app";++const getTheme = (appName: AppName): Theme => {+ const colors = getColors(appName);+ const cs = getColorSchemes(colors);+ // Cast app should always be shown in dark.+ const colorSchemes =+ appName == "cast" ? { ...cs, light: cs.dark } : { ...cs };+ return createTheme({+ cssVariables: { colorSchemeSelector: "class" },+ colorSchemes,+ typography: getTypography(appName),+ components: getComponents(appName),+ shape: {+ // Increase the default border radius multiplier from 4 to 8.+ borderRadius: 8,+ },+ transitions: {+ // Increase the default transition out duration from 195 to 300.+ duration: { leavingScreen: 300 },+ },+ });+};++/**+ * [Note: Colors]+ *+ * The word "color" in MUI stands for different things. In particular, the color+ * prop for (e.g.) a Button is not the same as the color passed in the sx prop.+ *+ * There are three layers (only the first is necessary, rest are semantic):+ *+ * 1. Consider some color, say a shade of red. This will be represented by its+ * exact CSS color value, say "#ee0000".+ *+ * 2. These can be groups of color values that have roughly the same hue, but+ * different levels of saturation. Such hue groups are arranged together into+ * a "Colors" exported by "@mui/material":+ *+ * export interface Color {+ * 50: string;+ * 100: string;+ * ...+ * 800: string;+ * 900: string;+ * A100: string;+ * ...+ * A700: string;+ * }+ *+ * 3. Finally, there are "PaletteColors" (the naming of props, and+ * documentation within MUI (as of v6), omits the palette qualifier).+ *+ * export interface PaletteColor {+ * light: string;+ * main: string;+ * dark: string;+ * contrastText: string;+ * }+ *+ * The PaletteColors are what we use in the MUI component props (e.g. Button).+ * The PaletteColors are defined by providing color values for the four "tokens"+ * that make them up, either directly ("#aa000") or via Colors ("red[500]").+ *+ * Within the sx prop we need to specify a color value, which can come from the+ * palette. The "palette", as defined by the palette property we provide when+ * creating the theme, can consist of arbitrary (and nestable) key value pairs.+ *+ * Within sx prop, the "color" and "backgroundColor" props can refer to paths+ * inside this palette object. That is,+ *+ * sx={{ color: "foo.bar" }}+ *+ * resolves to theme.vars.palette.foo.bar.+ *+ * [Note: Color names]+ *+ * When defining color names, there is some attempt at trying to use MUI v6,+ * which uses MD (Material Design) v2, nomenclature when feasible (just to keep+ * the number of concepts low), but as such, our color names should not be+ * thought of as following Material Design, and should be treated as arbitrary+ * tokens reflecting our own design system.+ *+ * Some callouts:+ *+ * - Our "primary" and "secondary" are neutral grays instead of the two-tone+ * primary and secondary in MD. Our "accent" is corresponds to the MD primary.+ *+ * - Our "critical" is similar to and the alternative for the MD error (which is+ * not used).+ *+ * - Two of the other default MD PaletteColors - warning, success - are used+ * rarely, while info is not used at all.+ *+ * [Note: Theme and palette custom variables]+ *+ * Custom variables can be added to both the top level theme object, and to the+ * palette object within the theme. One would imagine that within the palette+ * there would only be colors that follow PaletteColor, but that's not something+ * MUI itself follows.+ *+ * So there is no particular reason to place custom color related variables in+ * theme vs in the palette. As a convention:+ *+ * - Custom colors (even if they're not PaletteColors) go within the palette.+ *+ * - Non-color tokens that depend on the color scheme (e.g. box shadows) also go+ * within the palette so that they can be made color scheme specific.+ *+ * - All other custom variables remain within the top level theme.+ */+const getColors = (appName: AppName) => ({+ ..._colors,+ ...{+ fixed: {+ ..._colors.fixed,+ dark: {+ background: _colors.dark.background,+ text: _colors.dark.text,+ divider: _colors.dark.stroke.faint,+ },+ },+ },+ ...{+ accent:+ appName == "auth"+ ? _colors.accentAuth+ : appName == "share" || appName == "locker"+ ? _colors.accentShare+ : appName == "ensu"+ ? _colors.accentEnsu+ : _colors.accentPhotos,+ accentDark:+ appName == "ensu"+ ? _colors.accentEnsuDark+ : appName == "auth"+ ? _colors.accentAuth+ : appName == "share" || appName == "locker"+ ? _colors.accentShare+ : _colors.accentPhotos,+ },+ ...{+ accentContrastText:+ appName == "ensu" ? _colors.fixed.black : _colors.fixed.white,+ },+ ...{+ light:+ appName == "share" || appName == "locker"+ ? _colors.lightShare+ : appName == "ensu"+ ? _colors.lightEnsu+ : _colors.light,+ },+ ...{+ dark:+ appName == "share" || appName == "locker"+ ? _colors.darkShare+ : appName == "ensu"+ ? _colors.darkEnsu+ : _colors.dark,+ },+});++/**+ * The color values.+ *+ * Use this arbitrarily shaped object to define the palette. This avoid+ * duplication across color schemes, and also helps see if there are any+ * reusable colors.+ */+const _colors = {+ accentPhotos: { dark: "#00b33c", main: "#1db954", light: "#01de4d" },+ accentAuth: { dark: "#8e0fcb", main: "#9610d6", light: "#8e2de2" },+ accentShare: { dark: "#0056CC", main: "#1071FF", light: "#1071FF" },+ accentEnsu: { dark: "#f5d93a", main: "#f5d93a", light: "#f5d93a" },+ accentEnsuDark: { dark: "#f5d93a", main: "#f5d93a", light: "#f5d93a" },+ fixed: {+ white: "#fff",+ black: "#000",+ success: "#1db954",+ golden: "#ffc107",+ danger: { dark: "#f53434", main: "#ea3f3f", light: "#ff6565" },+ switchOn: "#2eca45",+ },+ lightShare: {+ background: {+ default: "#FAFAFA",+ paper: "#fff",+ paper2: "#fbfbfb",+ searchInput: "#f3f3f3",+ },+ backdrop: {+ base: "rgba(255 255 255 / 0.92)",+ muted: "rgba(255 255 255 / 0.75)",+ faint: "rgba(255 255 255 / 0.30)",+ },+ text: {+ base: "#000",+ muted: "rgba(0 0 0 / 0.60)",+ faint: "rgba(0 0 0 / 0.50)",+ },+ fill: {+ base: "#000",+ muted: "rgba(0 0 0 / 0.12)",+ faint: "rgba(0 0 0 / 0.04)",+ faintHover: "rgba(0 0 0 / 0.08)",+ fainter: "rgba(0 0 0 / 0.02)",+ },+ secondary: { main: "#f5f5f5", hover: "#e9e9e9" },+ stroke: {+ base: "#000",+ muted: "rgba(0 0 0 / 0.24)",+ faint: "rgba(0 0 0 / 0.12)",+ fainter: "rgba(0 0 0 / 0.06)",+ },+ boxShadow: {+ paper: "0px 0px 10px rgba(0 0 0 / 0.25)",+ menu: "0px 0px 6px rgba(0 0 0 / 0.16), 0px 3px 6px rgba(0 0 0 / 0.12)",+ button: "0px 4px 4px rgba(0 0 0 / 0.25)",+ },+ },+ lightEnsu: {+ background: {+ default: "#F8F5F0",+ paper: "#F8F5F0",+ paper2: "#FFFDF8",+ searchInput: "#F0EBE4",+ },+ backdrop: {+ base: "rgba(248 245 240 / 0.92)",+ muted: "rgba(248 245 240 / 0.75)",+ faint: "rgba(248 245 240 / 0.30)",+ },+ text: {+ base: "#1A1A1A",+ muted: "#8A8680",+ faint: "rgba(138 134 128 / 0.50)",+ },+ fill: {+ base: "#1A1A1A",+ muted: "rgba(26 26 26 / 0.12)",+ faint: "#F0EBE4",+ faintHover: "#E7E1D8",+ fainter: "#F8F5F0",+ },+ secondary: { main: "#F0EBE4", hover: "#E7E1D8" },+ stroke: {+ base: "#1A1A1A",+ muted: "rgba(26 26 26 / 0.24)",+ faint: "#D4D0C8",+ fainter: "rgba(26 26 26 / 0.06)",+ },+ boxShadow: {+ paper: "0px 0px 10px rgba(0 0 0 / 0.18)",+ menu: "0px 0px 6px rgba(0 0 0 / 0.14), 0px 3px 6px rgba(0 0 0 / 0.10)",+ button: "0px 4px 4px rgba(0 0 0 / 0.18)",+ },+ },+ darkShare: {+ background: {+ default: "#161616",+ paper: "#212121",+ paper2: "#252525",+ searchInput: "#212121",+ },+ backdrop: {+ base: "rgba(0 0 0 / 0.90)",+ muted: "rgba(0 0 0 / 0.65)",+ faint: "rgba(0 0 0 / 0.20)",+ },+ text: {+ base: "#fff",+ muted: "rgba(255 255 255 / 0.70)",+ faint: "rgba(255 255 255 / 0.50)",+ },+ fill: {+ base: "#fff",+ muted: "rgba(255 255 255 / 0.16)",+ faint: "rgba(255 255 255 / 0.12)",+ faintHover: "rgba(255 255 255 / 0.16)",+ fainter: "rgba(255 255 255 / 0.05)",+ },+ secondary: { main: "#2b2b2b", hover: "#373737" },+ stroke: {+ base: "#fff",+ muted: "rgba(255 255 255 / 0.24)",+ faint: "rgba(255 255 255 / 0.16)",+ fainter: "rgba(255 255 255 / 0.12)",+ },+ boxShadow: {+ paper: "0px 2px 12px rgba(0 0 0 / 0.75)",+ menu: "0px 0px 6px rgba(0 0 0 / 0.50), 0px 3px 6px rgba(0 0 0 / 0.25)",+ button: "0px 4px 4px rgba(0 0 0 / 0.75)",+ },+ },+ darkEnsu: {+ background: {+ default: "#141414",+ paper: "#1E1E1E",+ paper2: "#1E1E1E",+ searchInput: "#1E1E1E",+ },+ backdrop: {+ base: "rgba(20 20 20 / 0.90)",+ muted: "rgba(20 20 20 / 0.65)",+ faint: "rgba(20 20 20 / 0.20)",+ },+ text: {+ base: "#E8E4DF",+ muted: "#777777",+ faint: "rgba(119 119 119 / 0.50)",+ },+ fill: {+ base: "#E8E4DF",+ muted: "rgba(232 228 223 / 0.16)",+ faint: "#1E1E1E",+ faintHover: "#2A2A2A",+ fainter: "#141414",+ },+ secondary: { main: "#1E1E1E", hover: "#2A2A2A" },+ stroke: {+ base: "#E8E4DF",+ muted: "rgba(232 228 223 / 0.24)",+ faint: "#2A2A2A",+ fainter: "rgba(232 228 223 / 0.12)",+ },+ boxShadow: {+ paper: "0px 2px 12px rgba(0 0 0 / 0.75)",+ menu: "0px 0px 6px rgba(0 0 0 / 0.50), 0px 3px 6px rgba(0 0 0 / 0.25)",+ button: "0px 4px 4px rgba(0 0 0 / 0.75)",+ },+ },+ light: {+ // Keep these solid.+ background: {+ default: "#fff",+ paper: "#fff",+ paper2: "#fbfbfb",+ searchInput: "#f3f3f3",+ },+ backdrop: {+ base: "rgba(255 255 255 / 0.92)",+ muted: "rgba(255 255 255 / 0.75)",+ faint: "rgba(255 255 255 / 0.30)",+ },+ text: {+ base: "#000",+ muted: "rgba(0 0 0 / 0.60)",+ faint: "rgba(0 0 0 / 0.50)",+ },+ fill: {+ base: "#000",+ muted: "rgba(0 0 0 / 0.12)",+ faint: "rgba(0 0 0 / 0.04)",+ faintHover: "rgba(0 0 0 / 0.08)",+ fainter: "rgba(0 0 0 / 0.02)",+ },+ // MUI (as of v6.4) doesn't like it if we specify a non-solid color for+ // primary.main or secondary.main, or don't specify it using the #nnnnnn+ // notation; it seems to mess with the derivation of the color channels.+ secondary: { main: "#f5f5f5", hover: "#e9e9e9" },+ stroke: {+ base: "#000",+ muted: "rgba(0 0 0 / 0.24)",+ faint: "rgba(0 0 0 / 0.12)",+ fainter: "rgba(0 0 0 / 0.06)",+ },+ boxShadow: {+ paper: "0px 0px 10px rgba(0 0 0 / 0.25)",+ menu: "0px 0px 6px rgba(0 0 0 / 0.16), 0px 3px 6px rgba(0 0 0 / 0.12)",+ button: "0px 4px 4px rgba(0 0 0 / 0.25)",+ },+ },+ dark: {+ background: {+ default: "#000",+ paper: "#1b1b1b",+ paper2: "#252525",+ searchInput: "#1b1b1b",+ },+ backdrop: {+ base: "rgba(0 0 0 / 0.90)",+ muted: "rgba(0 0 0 / 0.65)",+ faint: "rgba(0 0 0 / 0.20)",+ },+ text: {+ base: "#fff",+ muted: "rgba(255 255 255 / 0.70)",+ faint: "rgba(255 255 255 / 0.50)",+ },+ fill: {+ base: "#fff",+ muted: "rgba(255 255 255 / 0.16)",+ faint: "rgba(255 255 255 / 0.12)",+ faintHover: "rgba(255 255 255 / 0.16)",+ fainter: "rgba(255 255 255 / 0.05)",+ },+ secondary: { main: "#2b2b2b", hover: "#373737" },+ stroke: {+ base: "#fff",+ muted: "rgba(255 255 255 / 0.24)",+ faint: "rgba(255 255 255 / 0.16)",+ fainter: "rgba(255 255 255 / 0.12)",+ },+ boxShadow: {+ paper: "0px 2px 12px rgba(0 0 0 / 0.75)",+ menu: "0px 0px 6px rgba(0 0 0 / 0.50), 0px 3px 6px rgba(0 0 0 / 0.25)",+ button: "0px 4px 4px rgba(0 0 0 / 0.75)",+ },+ },+};++const getColorSchemes = (colors: ReturnType<typeof getColors>) => ({+ light: {+ palette: {+ background: {+ ...colors.light.background,+ elevatedPaper: colors.light.background.paper2,+ },+ backdrop: colors.light.backdrop,+ primary: {+ main: colors.fixed.black,+ contrastText: colors.fixed.white,+ },+ secondary: {+ main: colors.light.secondary.main,+ dark: colors.light.secondary.hover,+ contrastText: colors.light.text.base,+ },+ success: { main: colors.fixed.success },+ warning: { main: colors.fixed.golden },+ accent: {+ main: colors.accent.main,+ dark: colors.accent.dark,+ light: colors.accent.light,+ contrastText: colors.accentContrastText,+ },+ critical: {+ main: colors.fixed.danger.main,+ dark: colors.fixed.danger.dark,+ light: colors.fixed.danger.light,+ contrastText: colors.fixed.white,+ },+ text: {+ // Alias the tokens used by MUI to the ones that we use. This way,+ // we don't need to change the default ("primary"), or update the+ // MUI internal styling that refers to these tokens.+ //+ // Our own code should not use these.+ primary: colors.light.text.base,+ secondary: colors.light.text.muted,+ disabled: colors.light.text.faint,+ // Our color tokens.+ base: colors.light.text.base,+ muted: colors.light.text.muted,+ faint: colors.light.text.faint,+ },+ fill: colors.light.fill,+ stroke: colors.light.stroke,+ divider: colors.light.stroke.faint,+ fixed: colors.fixed,+ boxShadow: colors.light.boxShadow,+ // Override some MUI defaults for styling action elements like+ // buttons and menu items.+ //+ // Nb: There are more where these came from, currently those don't+ // affect us, but in the future they might.+ //+ // https://github.com/mui/material-ui/blob/v6.4.0/packages/mui-material/src/styles/createPalette.js#L68+ action: {+ // The color of an active action like an icon button.+ active: colors.light.stroke.base,+ // The color of an hovered action.+ hover: colors.light.fill.faintHover,+ // For an icon button, the hover background color is derived+ // from the active color above and this opacity. Use a value+ // that results in the same result as faintHover.+ hoverOpacity: 0.08,+ // The color of a disabled action.+ disabled: colors.light.text.faint,+ // The background color of a disabled action.+ disabledBackground: colors.light.fill.faint,+ },+ // Override some internal MUI defaults that impact the components+ // which we use.+ //+ // https://github.com/mui/material-ui/blob/v6.4.0/packages/mui-material/src/styles/createThemeWithVars.js#L271+ FilledInput: {+ bg: colors.light.fill.faint,+ hoverBg: colors.light.fill.faintHover,+ // While we don't specifically have disabled inputs, TextInputs+ // do get disabled when the form is submitting, and this value+ // comes into play then.+ disabledBg: colors.light.fill.fainter,+ },+ },+ },+ // -- See the light mode section for comments+ dark: {+ palette: {+ background: {+ ...colors.dark.background,+ elevatedPaper: colors.dark.background.paper,+ },+ backdrop: colors.dark.backdrop,+ primary: {+ main: colors.fixed.white,+ contrastText: colors.fixed.black,+ },+ secondary: {+ main: colors.dark.secondary.main,+ dark: colors.dark.secondary.hover,+ contrastText: colors.dark.text.base,+ },+ success: { main: colors.fixed.success },+ warning: { main: colors.fixed.golden },+ accent: {+ main: colors.accentDark.main,+ dark: colors.accentDark.dark,+ light: colors.accentDark.light,+ contrastText: colors.accentContrastText,+ },+ critical: {+ main: colors.fixed.danger.main,+ dark: colors.fixed.danger.dark,+ light: colors.fixed.danger.light,+ contrastText: colors.fixed.white,+ },+ text: {+ primary: colors.dark.text.base,+ secondary: colors.dark.text.muted,+ disabled: colors.dark.text.faint,+ base: colors.dark.text.base,+ muted: colors.dark.text.muted,+ faint: colors.dark.text.faint,+ },+ fill: colors.dark.fill,+ stroke: colors.dark.stroke,+ divider: colors.dark.stroke.faint,+ fixed: colors.fixed,+ boxShadow: colors.dark.boxShadow,+ // -- See the light mode section for comments+ action: {+ active: colors.dark.stroke.base,+ hover: colors.dark.fill.faintHover,+ hoverOpacity: 0.16,+ disabled: colors.dark.text.faint,+ disabledBackground: colors.dark.fill.faint,+ },+ FilledInput: {+ bg: colors.dark.fill.faint,+ hoverBg: colors.dark.fill.faintHover,+ disabledBg: colors.dark.fill.fainter,+ },+ },+ },+});++/**+ * [Note: Font weights]+ *+ * We only use three font weights:+ *+ * - 500 (sx "regular")+ * - 600 (sx "medium")+ * - 700 (sx "bold", CSS "bold")+ *+ * While the sx prop allows us to use keywords "regular", "medium" and "bold",+ * which we do elsewhere in the code, within this file those keywords cannot be+ * used in all contexts because they instead map to the CSS keywords. To avoid+ * any confusion, within this file we only use the numeric values.+ *+ * ---+ *+ * MUI (as of v6) uses the following font weights by default:+ *+ * - fontWeightLight 300+ * - fontWeightRegular 400+ * - fontWeightMedium 500+ * - fontWeightBold 700+ *+ * The browser default (CSS keyword "normal"), is also 400.+ *+ * However for Inter, the font that we use, 400 is too light, and to improve+ * legibility we change fontWeightRegular to 500.+ *+ * Correspondingly, we shift fontWeightMedium to 600. fontWeightBold then ends+ * up mapping back to 700, which also nicely coincides with the CSS keyword+ * "bold".+ *+ * MUI uses fontWeightLight only as the default font weight for the h1 and h2+ * variants, but we override their font weight in our theme. Thus we don't need+ * to bother with the light variant (though for consistency of specifying every+ * value, we alias it the same weight as regular, 500).+ */+const baseTypography: TypographyVariantsOptions = {+ fontFamily: '"Inter Variable", sans-serif',+ fontWeightLight: 500,+ fontWeightRegular: 500 /* CSS baseline reset sets this as the default */,+ fontWeightMedium: 600,+ fontWeightBold: 700,+ h1: { fontSize: "48px", lineHeight: "58px", fontWeight: 600 /* Medium */ },+ h2: {+ fontSize: "32px",+ lineHeight: "39px",+ fontWeight: 500 /* Reset to regular to override MUI's default theme */,+ },+ h3: { fontSize: "24px", lineHeight: "29px", fontWeight: 600 /* Medium */ },+ h4: {+ fontSize: "22px",+ lineHeight: "27px",+ fontWeight: 500 /* Reset to regular to override MUI's default theme */,+ },+ h5: { fontSize: "20px", lineHeight: "25px", fontWeight: 600 /* Medium */ },+ // h6 is the default variant used by MUI's DialogTitle.+ h6: {+ // The font size and line height below is the same as large.+ fontSize: "18px",+ lineHeight: "22px",+ fontWeight: 600 /* Medium */,+ },+ body: { fontSize: "16px", lineHeight: "20px" },+ small: { fontSize: "14px", lineHeight: "17px" },+ mini: { fontSize: "12px", lineHeight: "15px" },+ tiny: { fontSize: "10px", lineHeight: "12px" },+};++const getTypography = (appName: AppName): TypographyVariantsOptions => {+ if (appName === "ensu") {+ return {+ ...baseTypography,+ fontFamily:+ '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',+ // Ensu-specific variants (type-augmented in web/apps/ensu/src/types).+ message: { fontSize: "15px", lineHeight: "1.7", fontWeight: 400 },+ code: {+ fontSize: "13px",+ lineHeight: "1.45",+ fontWeight: 400,+ fontFamily:+ 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',+ },+ } as TypographyVariantsOptions;+ }+ return baseTypography;+};++// Use the base typography for component style overrides (Button sizing, etc.).+const typography = baseTypography;++/**+ * > [!NOTE]+ * >+ * > The theme isn't tree-shakeable, prefer creating new components for heavy+ * > customization.+ * >+ * > https://mui.com/material-ui/customization/theme-components/+ */+const components: Components = {+ MuiCssBaseline: {+ styleOverrides: {+ body: {+ // MUI has different letter spacing for each variant, but those+ // are values arrived at for the default Material font, and+ // don't work for the font that we're using.+ //+ // So we reset the letter spacing for _all_ variants to a+ // reasonable value that works for our font.+ letterSpacing: "-0.011em",+ },+ },+ },++ MuiTypography: {+ defaultProps: {+ // MUI has body1 as the default variant for Typography, but our+ // variant scheme is different, instead of body1/2, we have+ // large/body/small etc. So reset the default to our equivalent of+ // body1, which is "body".+ variant: "body",+ // Map all our custom variants to <p>.+ variantMapping: { body: "p", small: "p", mini: "p", tiny: "p" },+ },+ },++ MuiModal: {+ styleOverrides: {+ root: {+ // A workaround to prevent stuck modals from blocking clicks.+ // https://github.com/mui/material-ui/issues/32286#issuecomment-1287951109+ '&:has(> div[style*="opacity: 0"])': { pointerEvents: "none" },+ },+ },+ },++ MuiDrawer: {+ styleOverrides: {+ root: {+ ".MuiBackdrop-root": {+ backgroundColor: "var(--mui-palette-backdrop-muted)",+ },+ },+ },+ },++ MuiDialog: {+ defaultProps: {+ // [Note: Workarounds for unactionable ARIA warnings]+ //+ // This is required to prevent console warnings about aria-hiding a+ // focused button when the dialog is closed. e.g. Select a file,+ // delete it. On closing the confirmation dialog, the error appears.+ //+ // The default is supposed to already be false, but setting this+ // again seems to help. But sometimes we need to set this to `true`+ // to prevent the warning. And sometimes neither helps, and we need+ // to add random setTimeouts.+ //+ // Angular, Bootstrap, MUI, shadcn: all seem to be emitting these+ // warning (just search the web). I'm don't know if this is just+ // someone at Chrome deciding to emit spurious warnings without+ // understanding the flow, or if none of these libraries have+ // managed to implement the ARIA spec properly yet (which says more+ // about the spec than about the libraries).+ //+ // - https://issues.chromium.org/issues/392121909+ // - https://github.com/mui/material-ui/issues/43106#issuecomment-2314809028+ closeAfterTransition: false,+ },+ styleOverrides: {+ root: {+ ".MuiBackdrop-root": {+ backgroundColor: "var(--mui-palette-backdrop-muted)",+ },+ // Reset the MUI default paddings to 16px everywhere.+ //+ // This is not a great choice either, usually most dialogs, for+ // one reason or the other, will need to customize this padding+ // anyway. But not resetting it to 16px leaves it at the MUI+ // defaults, which just doesn't work well with our designs.+ "& .MuiDialogTitle-root": {+ // MUI default is '16px 24px'.+ padding: "16px",+ },+ "& .MuiDialogContent-root": {+ // MUI default is '20px 24px'.+ padding: "16px",+ // If the contents of the dialog's contents exceed the+ // available height, show a scrollbar just for the contents+ // instead of the entire dialog.+ overflowY: "auto",+ },+ "& .MuiDialogActions-root": {+ // MUI default is way off for us since they cluster the+ // buttons to the right, while our designs usually want the+ // buttons to align with the heading / content.+ padding: "16px",+ },+ ".MuiDialogTitle-root + .MuiDialogContent-root": {+ // MUI resets this to 0 when the content doesn't use+ // dividers (none of ours do). I feel that is a better+ // default, since unlike margins, padding doesn't collapse,+ // but changing this now would break existing layouts.+ paddingTop: "16px",+ },+ },+ },+ },++ MuiPaper: {+ styleOverrides: {+ root: {+ variants: [+ {+ // Use our "paper" shadow for elevated Paper.+ props: { variant: "elevation" },+ style: {+ // MUI applies a semi-transparent background image+ // for elevation in dark mode. Remove it to match+ // background for our designs.+ backgroundImage: "none",+ // Use our paper shadow.+ boxShadow: "var(--mui-palette-boxShadow-paper)",+ },+ },+ {+ // Undo the effects of variant "elevation" case above+ // case when elevation is 0.+ props: { elevation: 0 },+ style: { boxShadow: "none" },+ },+ ],+ },+ },+ },++ // The default link "color" prop is "primary", which maps to "fill.base"+ // (and equivalently, to "text.base"). In our current designs, the <Link>+ // MUI component is only used in places where the surrounding text uses+ // "text.muted", so this default already provides it a highlight compared to+ // the text it in embedded in.+ //+ // We additionally disable the underline, and add a hover indication by+ // switching its color to the main accent.+ MuiLink: {+ defaultProps: { underline: "none" },+ styleOverrides: {+ root: { "&:hover": { color: "var(--mui-palette-accent-main)" } },+ },+ },++ MuiButton: {+ defaultProps: {+ // Change the default button variant from "text" to "contained".+ variant: "contained",+ // Disable shadows.+ disableElevation: true,+ },+ styleOverrides: {+ // We don't use the size prop for the MUI button, or rather it+ // cannot be used, since we have fixed the paddings and font sizes+ // unconditionally here (which is all that the size prop changes).+ root: {+ padding: "12px 16px",+ borderRadius: "4px",+ textTransform: "none",+ // Body, but medium.+ fontSize: typography.body?.fontSize,+ lineHeight: typography.body?.lineHeight,+ fontWeight: 600,+ },+ startIcon: { marginRight: "12px", "&& >svg": { fontSize: "20px" } },+ endIcon: { marginLeft: "12px", "&& >svg": { fontSize: "20px" } },+ },+ },++ MuiInputBase: {+ styleOverrides: {+ formControl: {+ // Give a symmetric border to the input field, by default the+ // border radius is only applied to the top for the "filled"+ // variant of input used inside TextFields.+ borderRadius: "8px",+ // Clip the bottom border so that there is no gap between the+ // filled area and the (full width) border.+ overflow: "hidden",+ // Hide the bottom border that always appears for the "filled"+ // variant of input used inside TextFields.+ "::before": { borderBottom: "none !important" },+ },+ },+ },++ MuiTextField: {+ defaultProps: {+ // The MUI default variant is "outlined", override it to use the+ // "filled" one by default.+ variant: "filled",+ // Reduce the vertical margins that MUI adds to the TextField.+ //+ // Note that this causes things to be too tight when the helper text+ // is shown, so this is not recommended for new code that we write.+ margin: "dense",+ },+ styleOverrides: {+ root: { "& .MuiInputAdornment-root": { marginRight: "8px" } },+ },+ },++ MuiCheckbox: {+ defaultProps: {+ // Disable the ripple effect for all checkboxes.+ disableRipple: true,+ },+ styleOverrides: {+ // Since we've disabled the ripple, add other affordances to it (a+ // background and outline) to clearly indicate whenever it gains+ // keyboard focus.+ root: {+ "&.Mui-focusVisible": {+ backgroundColor: "var(--mui-palette-fill-faint)",+ outline: "1px solid var(--mui-palette-stroke-faint)",+ },+ },+ },+ },++ MuiSvgIcon: {+ styleOverrides: {+ root: {+ variants: [+ {+ props: { color: "primary" },+ style: { color: "var(--mui-palette-stroke-base)" },+ },+ {+ props: { color: "secondary" },+ style: { color: "var(--mui-palette-stroke-muted)" },+ },+ ],+ },+ },+ },++ MuiIconButton: {+ styleOverrides: {+ root: {+ padding: "12px",+ variants: [+ {+ props: { color: "primary" },+ style: { color: "var(--mui-palette-stroke-base)" },+ },+ {+ props: { color: "secondary" },+ style: { color: "var(--mui-palette-stroke-muted)" },+ },+ ],+ "&.Mui-disabled": { color: "var(--mui-palette-stroke-faint)" },+ },+ },+ },++ MuiMenu: {+ styleOverrides: {+ root: {+ ".MuiMenu-paper": {+ boxShadow: "var(--mui-palette-boxShadow-menu)",+ },+ },+ },+ },++ MuiSnackbar: {+ styleOverrides: {+ root: {+ // Set a default border radius for all snackbar's (e.g.+ // notification popups).+ borderRadius: "8px",+ },+ },+ },++ MuiAlert: {+ defaultProps: {+ // Use the outlined variant by default (instead of "standard").+ variant: "outlined",+ },+ },+};++const getComponents = (appName: AppName): Components => {+ if (appName !== "ensu" && appName !== "locker") return components;++ const muiButtonStyleOverrides = (components.MuiButton?.styleOverrides ??+ {}) as Record<string, unknown>;+ const muiButtonRootStyleOverrides =+ (muiButtonStyleOverrides.root as Record<string, unknown> | undefined) ??+ {};+ const muiIconButtonStyleOverrides = (components.MuiIconButton+ ?.styleOverrides ?? {}) as Record<string, unknown>;+ const muiIconButtonRootStyleOverrides =+ (muiIconButtonStyleOverrides.root as+ | Record<string, unknown>+ | undefined) ?? {};+ const muiInputBaseStyleOverrides = (components.MuiInputBase+ ?.styleOverrides ?? {}) as Record<string, unknown>;+ const muiInputBaseFormControlStyleOverrides =+ (muiInputBaseStyleOverrides.formControl as+ | Record<string, unknown>+ | undefined) ?? {};+ const muiDialogTitleStyleOverrides = (components.MuiDialogTitle+ ?.styleOverrides ?? {}) as Record<string, unknown>;+ const muiDialogContentStyleOverrides = (components.MuiDialogContent+ ?.styleOverrides ?? {}) as Record<string, unknown>;++ if (appName === "locker") {+ return {+ ...components,+ MuiButton: {+ ...components.MuiButton,+ styleOverrides: {+ ...muiButtonStyleOverrides,+ root: {+ ...muiButtonRootStyleOverrides,+ borderRadius: "20px",+ },+ } as NonNullable<+ NonNullable<Components["MuiButton"]>["styleOverrides"]+ >,+ },+ MuiIconButton: {+ ...components.MuiIconButton,+ styleOverrides: {+ ...muiIconButtonStyleOverrides,+ root: {+ ...muiIconButtonRootStyleOverrides,+ borderRadius: "18px",+ },+ } as NonNullable<+ NonNullable<Components["MuiIconButton"]>["styleOverrides"]+ >,+ },+ MuiInputBase: {+ ...components.MuiInputBase,+ styleOverrides: {+ ...muiInputBaseStyleOverrides,+ formControl: {+ ...muiInputBaseFormControlStyleOverrides,+ borderRadius: "16px",+ },+ } as NonNullable<+ NonNullable<Components["MuiInputBase"]>["styleOverrides"]+ >,+ },+ MuiOutlinedInput: {+ ...components.MuiOutlinedInput,+ styleOverrides: {+ ...components.MuiOutlinedInput?.styleOverrides,+ root: {+ ...(components.MuiOutlinedInput?.styleOverrides+ ?.root as Record<string, unknown> | undefined),+ borderRadius: "16px",+ },+ } as NonNullable<+ NonNullable<+ Components["MuiOutlinedInput"]+ >["styleOverrides"]+ >,+ },+ MuiFilledInput: {+ ...components.MuiFilledInput,+ styleOverrides: {+ ...components.MuiFilledInput?.styleOverrides,+ root: {+ ...(components.MuiFilledInput?.styleOverrides?.root as+ | Record<string, unknown>+ | undefined),+ borderRadius: "16px",+ },+ } as NonNullable<+ NonNullable<Components["MuiFilledInput"]>["styleOverrides"]+ >,+ },+ MuiDialogTitle: {+ ...components.MuiDialogTitle,+ styleOverrides: {+ ...muiDialogTitleStyleOverrides,+ root: {+ ...(muiDialogTitleStyleOverrides.root as+ | Record<string, unknown>+ | undefined),+ paddingBottom: "12px",+ },+ } as NonNullable<+ NonNullable<Components["MuiDialogTitle"]>["styleOverrides"]+ >,+ },+ MuiDialogContent: {+ ...components.MuiDialogContent,+ styleOverrides: {+ ...muiDialogContentStyleOverrides,+ root: {+ ...(muiDialogContentStyleOverrides.root as+ | Record<string, unknown>+ | undefined),+ paddingTop: "8px",+ },+ } as NonNullable<+ NonNullable<+ Components["MuiDialogContent"]+ >["styleOverrides"]+ >,+ },+ };+ }++ return {+ ...components,+ MuiTypography: {+ ...components.MuiTypography,+ defaultProps: {+ ...components.MuiTypography?.defaultProps,+ variantMapping: {+ ...components.MuiTypography?.defaultProps?.variantMapping,+ message: "p",+ code: "code",+ } as Record<string, string>,+ },+ },+ MuiButton: {+ ...components.MuiButton,+ styleOverrides: {+ ...muiButtonStyleOverrides,+ root: { ...muiButtonRootStyleOverrides, borderRadius: "16px" },+ } as NonNullable<+ NonNullable<Components["MuiButton"]>["styleOverrides"]+ >,+ },+ };+};++// Exports ---++/**+ * The MUI {@link Theme} to use for the photos app.+ *+ * This is also the "default" theme, in that it is used for the accounts app+ * which serves both photos and auth.+ */+export const photosTheme = getTheme("photos");++/**+ * The MUI {@link Theme} to use for the auth app.+ */+export const authTheme = getTheme("auth");++/**+ * The MUI {@link Theme} to use for the cast app.+ *+ * This is the same as the dark theme for the photos app.+ */+export const castTheme = getTheme("cast");++/**+ * The MUI {@link Theme} to use for the Ensu app.+ */+export const ensuTheme = getTheme("ensu");++/**+ * The MUI {@link Theme} to use for the locker public app.+ */+export const shareTheme = getTheme("share");++/** Theme for the locker app (blue accent, matching mobile Locker app). */+export const lockerTheme = getTheme("locker");diff --git a/web/apps/albums/vendor/ente-base/context.ts b/web/apps/albums/vendor/ente-base/context.tsnew file mode 100644index 0000000000..ca3ee1fda6--- /dev/null+++ b/web/apps/albums/vendor/ente-base/context.ts@@ -0,0 +1,67 @@+import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";+import { createContext, useContext } from "react";+import { genericErrorDialogAttributes } from "./components/utils/dialog";+import log from "./log";++/**+ * The type of the context expected to be present in the React tree for all apps+ * that use the base package.+ *+ * It is usually provided by the _app.tsx for the corresponding app.+ */+export interface BaseContextT {+ /**+ * Perform the (possibly app specific) logout sequence.+ */+ logout: () => void;+ /**+ * Show a "mini dialog" with the given attributes.+ *+ * Mini dialogs (see {@link AttributedMiniDialog}) are meant for simple+ * confirmation or notifications. Their appearance and functionality can be+ * customized by providing appropriate {@link MiniDialogAttributes}.+ */+ showMiniDialog: (attributes: MiniDialogAttributes) => void;+ /**+ * Log the given error and show a generic error {@link MiniDialog}.+ */+ onGenericError: (error: unknown) => void;+}++/**+ * The React {@link Context} of type {@link BaseContextT} available to all React+ * components that refer to the base package.+ */+export const BaseContext = createContext<BaseContextT | undefined>(undefined);++/**+ * Utility hook to get the required {@link BaseContextT} that is expected to be+ * available to all React components that refer to the base package.+ */+export const useBaseContext = (): BaseContextT => useContext(BaseContext)!;++/**+ * A helper function to create a {@link BaseContext} by deriving derivable+ * context values from the minimal subset.+ *+ * In simpler words, it automatically provides a definition of+ * {@link onGenericError} using the given {@link showMiniDialog} prop.+ */+export const deriveBaseContext = ({+ logout,+ showMiniDialog,+}: Omit<BaseContextT, "onGenericError">): BaseContextT => {+ const onGenericError = (e: unknown) => {+ log.error(e);+ // The generic error handler is sometimes called in the context of+ // actions that were initiated by a confirmation dialog action handler+ // themselves, then we need to let the current one close.+ //+ // See: [Note: Chained MiniDialogs]+ setTimeout(() => {+ showMiniDialog(genericErrorDialogAttributes());+ }, 0);+ };++ return { logout, showMiniDialog, onGenericError };+};diff --git a/web/apps/albums/vendor/ente-base/crypto/index.ts b/web/apps/albums/vendor/ente-base/crypto/index.tsnew file mode 100644index 0000000000..cf837db59c--- /dev/null+++ b/web/apps/albums/vendor/ente-base/crypto/index.ts@@ -0,0 +1,531 @@+/**+ * @file Cryptographic operations. This is the highest layer of the crypto code+ * hierarchy, and is meant to be used directly by the rest of our code.+ *+ * --|+ * --> For each function, more detailed documentation is in `libsodium.ts` <-+ * --|+ *+ * [Note: Crypto code hierarchy]+ *+ * 1. ente-base/crypto (Crypto API for our code)+ * 2. ente-base/crypto/libsodium (The actual implementation)+ * 3. libsodium-wrappers (JavaScript bindings to libsodium)+ *+ * Our cryptography primitives are provided by libsodium, specifically, its+ * JavaScript bindings ("libsodium-wrappers"). That is the lowest layer.+ *+ * > Note that we use the sumo variant, "libsodium-wrappers-sumo", since the+ * standard variant does not provide the `crypto_pwhash_*` functions.+ *+ * Direct usage of "libsodium-wrappers" is restricted to `crypto/libsodium.ts`.+ * That is the next higher layer. Usually the functions in this file are thin+ * wrappers over the raw libsodium APIs, with a bit of massaging. They also+ * ensure that sodium.ready has been called before accessing libsodium's APIs,+ * thus all the functions it exposes are async.+ *+ * Direct usage of "libsodium-wrappers" is restricted to this file,+ * `crypto/index.ts`. This is the highest layer. These are direct proxies to+ * functions exposed by `crypto/libsodium.ts`, but they automatically defer to a+ * worker thread if we're not already running on one. More on this below.+ *+ * ---+ *+ * [Note: Using libsodium in worker thread]+ *+ * This file, `crypto/index.ts`, and `crypto/worker.ts` are mostly logic-less+ * trampolines meant to allow us to seamlessly use the the same API both from+ * the main thread or from a web worker whilst ensuring that the implementation+ * never runs on the main thread.+ *+ * Cryptographic operations like encryption are CPU intensive and would cause+ * the UI to stutter if used directly on the main thread. To keep the UI smooth,+ * we instead want to run them in a web worker. However, sometimes we already+ * _are_ running in a web worker, and delegating to another worker is wasteful.+ *+ * The external API functions provided by this file check to see if we're+ * already in a web worker, and if so directly invoke the implementation.+ * Otherwise the call the sibling function in a shared "crypto" web worker+ * (which then invokes the implementation function, but this time in the context+ * of a web worker).+ *+ * As a consumer, it is safe to just call functions in this file, and they'll+ * just do the right thing based on the context. However, it is also fine to+ * explicitly get an handle to a crypto web worker and use that. e.g., the+ * uploader creates it own crypto worker instances and directly calls the+ * functions in the workers that it created instead of going through this file.+ *+ * ---+ *+ * [Note: Crypto layer API data types]+ *+ * There are two primary types used when exchanging data with these functions:+ *+ * 1. Base64 strings. Unless stated otherwise, all strings are taken as base64+ * encoded representations of the underlying data. Usually, the unqualified+ * function deals with base64 strings, since they also are the data type in+ * which we usually store and send the data.+ *+ * 2. Raw bytes. Uint8Arrays are byte arrays. The functions that deal with bytes+ * are usually indicated by a *Bytes suffix in their name, but not always+ * since it might also be the natural choice for functions that deal with+ * larger amounts of data.+ *+ * Where relevant and useful, functions also accept a union of these two - a+ * {@link BytesOrB64} where the implementation will automatically convert+ * to/from base64 to bytes if needed, thus saving on unnecessary conversions at+ * the caller side.+ *+ * Apart from these two, there are other secondary, one off types.+ *+ * 1. Hex representations of the bytes. These are indicated by the *Hex suffix+ * on the functions dealing with them.+ *+ * 2. JSON values. These are indicated by the *JSON suffix on the functions+ * dealing with them.+ */+import { ComlinkWorker } from "ente-base/worker/comlink-worker";+import { inWorker } from "../env";+import * as libsodium from "./libsodium";+import type {+ BytesOrB64,+ DerivedKey,+ EncryptedBlob,+ EncryptedBlobB64,+ EncryptedBlobBytes,+ EncryptedBox,+ EncryptedBoxB64,+ EncryptedFile,+ InitChunkDecryptionResult,+ InitChunkEncryptionResult,+ KeyPair,+ SodiumStateAddress,+} from "./types";+import type { CryptoWorker } from "./worker";++/**+ * Cached instance of the {@link ComlinkWorker} that wraps our web worker.+ */+let _comlinkWorker: ComlinkWorker<typeof CryptoWorker> | undefined;++/**+ * Lazily created, cached, instance of a "shared" CryptoWorker web worker.+ *+ * Some code which needs to do operations in parallel (e.g. during the upload+ * flow) creates its own CryptoWorker web workers. But those are exceptions; the+ * rest of the code normally calls the functions in this file, and they all+ * implicitly use a default "shared" web worker (unless we're already running in+ * the context of a web worker).+ */+const sharedWorker = () =>+ (_comlinkWorker ??= createComlinkCryptoWorker()).remote;++/**+ * Create a new instance of a comlink worker that wraps a {@link CryptoWorker}+ * web worker.+ */+export const createComlinkCryptoWorker = () =>+ new ComlinkWorker<typeof CryptoWorker>(+ "crypto",+ new Worker(new URL("worker.ts", import.meta.url)),+ );++/**+ * Convert bytes ({@link Uint8Array}) to a base64 string.+ */+export const toB64 = (bytes: Uint8Array): Promise<string> =>+ inWorker()+ ? libsodium.toB64(bytes)+ : sharedWorker().then((w) => w.toB64(bytes));++/**+ * Convert a base64 string to bytes ({@link Uint8Array}).+ */+export const fromB64 = (b64String: string): Promise<Uint8Array> =>+ inWorker()+ ? libsodium.fromB64(b64String)+ : sharedWorker().then((w) => w.fromB64(b64String));++/**+ * URL safe variant of {@link toB64}.+ */+export const toB64URLSafe = (bytes: Uint8Array): Promise<string> =>+ inWorker()+ ? libsodium.toB64URLSafe(bytes)+ : sharedWorker().then((w) => w.toB64URLSafe(bytes));++/**+ * URL safe variant of {@link toB64} that does not add any padding ("="+ * characters).+ */+export const toB64URLSafeNoPadding = (bytes: Uint8Array): Promise<string> =>+ inWorker()+ ? libsodium.toB64URLSafeNoPadding(bytes)+ : sharedWorker().then((w) => w.toB64URLSafeNoPadding(bytes));++/**+ * URL safe unpadded variant of {@link fromB64}.+ */+export const fromB64URLSafeNoPadding = (+ b64String: string,+): Promise<Uint8Array> =>+ inWorker()+ ? libsodium.fromB64URLSafeNoPadding(b64String)+ : sharedWorker().then((w) => w.fromB64URLSafeNoPadding(b64String));++/**+ * Convert a base64 string to the hex representation of the underlying bytes.+ */+export const toHex = (b64String: string): Promise<string> =>+ inWorker()+ ? libsodium.toHex(b64String)+ : sharedWorker().then((w) => w.toHex(b64String));++/**+ * Convert a hex string to the base64 representation of the underlying bytes.+ */+export const fromHex = (hexString: string): Promise<string> =>+ inWorker()+ ? libsodium.fromHex(hexString)+ : sharedWorker().then((w) => w.fromHex(hexString));++/**+ * Return a new randomly generated 256-bit key (as a base64 string).+ *+ * The returned key is suitable for use with the *Box encryption functions, and+ * as a general encryption key (e.g. as the user's master key or recovery key).+ */+export const generateKey = (): Promise<string> =>+ inWorker()+ ? libsodium.generateKey()+ : sharedWorker().then((w) => w.generateKey());++/**+ * Return a new randomly generated 256-bit key (as a base64 string) suitable for+ * use with the *Blob or *Stream encryption functions.+ */+export const generateBlobOrStreamKey = (): Promise<string> =>+ inWorker()+ ? libsodium.generateBlobOrStreamKey()+ : sharedWorker().then((w) => w.generateBlobOrStreamKey());++/**+ * Encrypt the given data, returning a box containing the encrypted data and a+ * randomly generated nonce that was used during encryption.+ *+ * Both the encrypted data and the nonce are returned as base64 strings.+ *+ * Use {@link decryptBox} to decrypt the result.+ *+ * > The suffix "Box" comes from the fact that it uses the so called secretbox+ * > APIs provided by libsodium under the hood.+ * >+ * > See: [Note: 3 forms of encryption (Box | Blob | Stream)]+ */+export const encryptBox = (+ data: BytesOrB64,+ key: BytesOrB64,+): Promise<EncryptedBoxB64> =>+ inWorker()+ ? libsodium.encryptBox(data, key)+ : sharedWorker().then((w) => w.encryptBox(data, key));++/**+ * Encrypt the given data, returning a blob containing the encrypted data and a+ * decryption header as base64 strings.+ *+ * This function is usually used to encrypt data associated with an Ente object+ * (file, collection, entity) using the object's key.+ *+ * Use {@link decryptBlob} or {@link decryptBlobBytes} to decrypt the result.+ *+ * > The suffix "Blob" comes from our convention of naming functions that use+ * > the secretstream APIs without breaking the data into chunks.+ * >+ * > See: [Note: 3 forms of encryption (Box | Blob | Stream)]+ */+export const encryptBlob = (+ data: BytesOrB64,+ key: BytesOrB64,+): Promise<EncryptedBlobB64> =>+ inWorker()+ ? libsodium.encryptBlob(data, key)+ : sharedWorker().then((w) => w.encryptBlob(data, key));++/**+ * A variant of {@link encryptBlob} that returns the result components as bytes+ * instead of as base64 strings.+ *+ * Use {@link decryptBlob} or {@link decryptBlobBytes} to decrypt the result.+ */+export const encryptBlobBytes = (+ data: BytesOrB64,+ key: BytesOrB64,+): Promise<EncryptedBlobBytes> =>+ inWorker()+ ? libsodium.encryptBlobBytes(data, key)+ : sharedWorker().then((w) => w.encryptBlobBytes(data, key));++/**+ * Encrypt the JSON metadata associated with an Ente object (file, collection or+ * entity) using the object's key.+ *+ * This is a variant of {@link encryptBlob} tailored for encrypting any+ * arbitrary metadata associated with an Ente object. For example, it is used+ * for encrypting the various metadata fields associated with a file, using that+ * file's key.+ *+ * Instead of raw bytes, it takes as input an arbitrary JSON object which it+ * encodes into a string, and encrypts that.+ *+ * Use {@link decryptMetadataJSON} to decrypt the result.+ *+ * @param jsonValue The JSON value to encrypt. This can be an arbitrary JSON+ * value, but since TypeScript currently doesn't have a native JSON type, it is+ * typed as {@link unknown}.+ *+ * @param key The encryption key.+ */+export const encryptMetadataJSON = (+ jsonValue: unknown,+ key: BytesOrB64,+): Promise<EncryptedBlobB64> =>+ inWorker()+ ? libsodium.encryptMetadataJSON(jsonValue, key)+ : sharedWorker().then((w) => w.encryptMetadataJSON(jsonValue, key));++/**+ * Encrypt the given data using chunked streaming encryption, but process all+ * the chunks in one go.+ */+export const encryptStreamBytes = (+ data: Uint8Array,+ key: BytesOrB64,+): Promise<EncryptedFile> =>+ inWorker()+ ? libsodium.encryptStreamBytes(data, key)+ : sharedWorker().then((w) => w.encryptStreamBytes(data, key));++/**+ * Prepare for chunked streaming encryption using {@link encryptStreamChunk}.+ */+export const initChunkEncryption = (+ key: BytesOrB64,+): Promise<InitChunkEncryptionResult> =>+ inWorker()+ ? libsodium.initChunkEncryption(key)+ : sharedWorker().then((w) => w.initChunkEncryption(key));++/**+ * Encrypt a chunk as part of a chunked streaming encryption.+ */+export const encryptStreamChunk = (+ data: Uint8Array,+ state: SodiumStateAddress,+ isFinalChunk: boolean,+): Promise<Uint8Array> =>+ inWorker()+ ? libsodium.encryptStreamChunk(data, state, isFinalChunk)+ : sharedWorker().then((w) =>+ w.encryptStreamChunk(data, state, isFinalChunk),+ );++/**+ * Decrypt a box encrypted using {@link encryptBox} and returns the decrypted+ * bytes as a base64 string.+ */+export const decryptBox = (+ box: EncryptedBox,+ key: BytesOrB64,+): Promise<string> =>+ inWorker()+ ? libsodium.decryptBox(box, key)+ : sharedWorker().then((w) => w.decryptBox(box, key));++/**+ * Variant of {@link decryptBox} that returns the decrypted bytes as it is+ * (without encoding them to base64).+ */+export const decryptBoxBytes = (+ box: EncryptedBox,+ key: BytesOrB64,+): Promise<Uint8Array> =>+ inWorker()+ ? libsodium.decryptBoxBytes(box, key)+ : sharedWorker().then((w) => w.decryptBoxBytes(box, key));++/**+ * Decrypt a blob encrypted using either {@link encryptBlobBytes} or+ * {@link encryptBlob} and return it as a base64 encoded string.+ */+export const decryptBlob = (+ blob: EncryptedBlob,+ key: BytesOrB64,+): Promise<string> =>+ inWorker()+ ? libsodium.decryptBlob(blob, key)+ : sharedWorker().then((w) => w.decryptBlob(blob, key));++/**+ * A variant of {@link decryptBlobBytes} that returns the result bytes directly+ * (instead of encoding them as a base64 string).+ */+export const decryptBlobBytes = (+ blob: EncryptedBlob,+ key: BytesOrB64,+): Promise<Uint8Array> =>+ inWorker()+ ? libsodium.decryptBlobBytes(blob, key)+ : sharedWorker().then((w) => w.decryptBlobBytes(blob, key));++/**+ * Decrypt the result of {@link encryptStreamBytes}.+ */+export const decryptStreamBytes = (+ file: EncryptedFile,+ key: BytesOrB64,+): Promise<Uint8Array> =>+ inWorker()+ ? libsodium.decryptStreamBytes(file, key)+ : sharedWorker().then((w) => w.decryptStreamBytes(file, key));++/**+ * Prepare to decrypt the encrypted result produced using {@link initChunkEncryption} and+ * {@link encryptStreamChunk}.+ */+export const initChunkDecryption = (+ header: string,+ key: BytesOrB64,+): Promise<InitChunkDecryptionResult> =>+ inWorker()+ ? libsodium.initChunkDecryption(header, key)+ : sharedWorker().then((w) => w.initChunkDecryption(header, key));++/**+ * Decrypt an individual chunk produced by {@link encryptStreamChunk}.+ *+ * This function is used in tandem with {@link initChunkDecryption}.+ */+export const decryptStreamChunk = (+ data: Uint8Array,+ state: SodiumStateAddress,+): Promise<Uint8Array> =>+ inWorker()+ ? libsodium.decryptStreamChunk(data, state)+ : sharedWorker().then((w) => w.decryptStreamChunk(data, state));++/**+ * Decrypt the metadata JSON encrypted using {@link encryptMetadataJSON}.+ *+ * @returns The decrypted JSON value. Since TypeScript does not have a native+ * JSON type, we need to return it as an `unknown`.+ */+export const decryptMetadataJSON = (+ blob: EncryptedBlob,+ key: BytesOrB64,+): Promise<unknown> =>+ inWorker()+ ? libsodium.decryptMetadataJSON(blob, key)+ : sharedWorker().then((w) => w.decryptMetadataJSON(blob, key));++/**+ * Generate a new public/private keypair.+ */+export const generateKeyPair = (): Promise<KeyPair> =>+ inWorker()+ ? libsodium.generateKeyPair()+ : sharedWorker().then((w) => w.generateKeyPair());++/**+ * Public key encryption.+ */+export const boxSeal = (data: string, publicKey: string): Promise<string> =>+ inWorker()+ ? libsodium.boxSeal(data, publicKey)+ : sharedWorker().then((w) => w.boxSeal(data, publicKey));++/**+ * Decrypt the result of {@link boxSeal}.+ */+export const boxSealOpen = (+ encryptedData: string,+ keyPair: KeyPair,+): Promise<string> =>+ inWorker()+ ? libsodium.boxSealOpen(encryptedData, keyPair)+ : sharedWorker().then((w) => w.boxSealOpen(encryptedData, keyPair));++/**+ * Variant of {@link boxSealOpen} that returns the decrypted bytes as it is+ * (without encoding them to base64).+ */+export const boxSealOpenBytes = (+ encryptedData: string,+ keyPair: KeyPair,+): Promise<Uint8Array> =>+ inWorker()+ ? libsodium.boxSealOpenBytes(encryptedData, keyPair)+ : sharedWorker().then((w) =>+ w.boxSealOpenBytes(encryptedData, keyPair),+ );++/**+ * Return a new randomly generated 128-bit salt (as a base64 string).+ *+ * The returned salt is suitable for use with {@link deriveKey}, and also as a+ * general 128-bit salt.+ */+export const generateDeriveKeySalt = (): Promise<string> =>+ inWorker()+ ? libsodium.generateDeriveKeySalt()+ : sharedWorker().then((w) => w.generateDeriveKeySalt());++/**+ * Derive a key by hashing the given {@link passphrase} using Argon 2id.+ */+export const deriveKey = (+ passphrase: string,+ salt: string,+ opsLimit: number,+ memLimit: number,+): Promise<string> =>+ inWorker()+ ? libsodium.deriveKey(passphrase, salt, opsLimit, memLimit)+ : sharedWorker().then((w) =>+ w.deriveKey(passphrase, salt, opsLimit, memLimit),+ );++/**+ * Derive a sensitive key from the given {@link passphrase}.+ */+export const deriveSensitiveKey = (passphrase: string): Promise<DerivedKey> =>+ inWorker()+ ? libsodium.deriveSensitiveKey(passphrase)+ : sharedWorker().then((w) => w.deriveSensitiveKey(passphrase));++/**+ * Derive an key suitable for interactive use from the given {@link passphrase}.+ */+export const deriveInteractiveKey = (+ passphrase: string,+): Promise<DerivedKey> =>+ inWorker()+ ? libsodium.deriveInteractiveKey(passphrase)+ : sharedWorker().then((w) => w.deriveInteractiveKey(passphrase));++/**+ * Derive a subkey of the given {@link key} using the specified parameters.+ *+ * @returns the bytes of the derived subkey.+ */+export const deriveSubKeyBytes = async (+ key: string,+ subKeyLength: number,+ subKeyID: number,+ context: string,+): Promise<Uint8Array> =>+ inWorker()+ ? libsodium.deriveSubKeyBytes(key, subKeyLength, subKeyID, context)+ : sharedWorker().then((w) =>+ w.deriveSubKeyBytes(key, subKeyLength, subKeyID, context),+ );diff --git a/web/apps/albums/vendor/ente-base/crypto/libsodium.ts b/web/apps/albums/vendor/ente-base/crypto/libsodium.tsnew file mode 100644index 0000000000..18129942d3--- /dev/null+++ b/web/apps/albums/vendor/ente-base/crypto/libsodium.ts@@ -0,0 +1,900 @@+/**+ * @file A thin-ish layer over the actual libsodium APIs, to make them more+ * palatable to the rest of our Javascript code.+ *+ * All functions are stateless, async, and safe to use in Web Workers.+ *+ * Docs for the JS library: https://github.com/jedisct1/libsodium.js.+ *+ * To see where this code fits, see [Note: Crypto code hierarchy].+ */+import { mergeUint8Arrays } from "ente-utils/array";+import sodium from "libsodium-wrappers-sumo";+import {+ deriveKeyInsufficientMemoryErrorMessage,+ streamEncryptionChunkSize,+ type BytesOrB64,+ type DerivedKey,+ type EncryptedBlob,+ type EncryptedBlobB64,+ type EncryptedBlobBytes,+ type EncryptedBox,+ type EncryptedBoxB64,+ type EncryptedFile,+ type InitChunkDecryptionResult,+ type InitChunkEncryptionResult,+ type KeyPair,+ type SodiumStateAddress,+} from "./types";++/**+ * Convert bytes ({@link Uint8Array}) to a base64 string.+ *+ * See also {@link toB64URLSafe} and {@link toB64URLSafeNoPadding}.+ */+export const toB64 = async (input: Uint8Array) => {+ await sodium.ready;+ return sodium.to_base64(input, sodium.base64_variants.ORIGINAL);+};++/**+ * Convert a base64 string to bytes ({@link Uint8Array}).+ *+ * This is the converse of {@link toBase64}.+ */+export const fromB64 = async (input: string): Promise<Uint8Array> => {+ await sodium.ready;+ return sodium.from_base64(input, sodium.base64_variants.ORIGINAL);+};++/**+ * Convert bytes ({@link Uint8Array}) to a URL-safe base64 string.+ *+ * See also {@link toB64URLSafe} and {@link toB64URLSafeNoPadding}.+ */+export const toB64URLSafe = async (input: Uint8Array) => {+ await sodium.ready;+ return sodium.to_base64(input, sodium.base64_variants.URLSAFE);+};++/**+ * Convert bytes ({@link Uint8Array}) to a unpadded URL-safe base64 string.+ *+ * This differs from {@link toB64URLSafe} in that it does not append any+ * trailing padding character(s) "=" to make the resultant string's length be an+ * integer multiple of 4.+ *+ * - In some contexts, for example when serializing WebAuthn binary for+ * transmission over the network, this is the required / recommended approach.+ *+ * - In other cases, for example when trying to pass an arbitrary JSON string+ * via a URL parameter, this is also convenient so that we do not have to deal+ * with any ambiguity surrounding the "=" which is also the query parameter+ * key value separator.+ */+export const toB64URLSafeNoPadding = async (input: Uint8Array) => {+ await sodium.ready;+ return sodium.to_base64(input, sodium.base64_variants.URLSAFE_NO_PADDING);+};++/**+ * Convert a unpadded URL-safe base64 string to bytes ({@link Uint8Array}).+ *+ * This is the converse of {@link toB64URLSafeNoPadding}, and does not expect+ * its input string's length to be a an integer multiple of 4.+ */+export const fromB64URLSafeNoPadding = async (input: string) => {+ await sodium.ready;+ return sodium.from_base64(input, sodium.base64_variants.URLSAFE_NO_PADDING);+};++/**+ * Convert a base64 string to the hex representation of the bytes that the base+ * 64 string encodes.+ *+ * Use {@link fromHex} to go back.+ */+export const toHex = async (input: string) => {+ await sodium.ready;+ return sodium.to_hex(await fromB64(input));+};++/**+ * Convert a hex string to the base64 representation of the bytes that the hex+ * string encodes.+ *+ * This is the inverse of {@link toHex}.+ */+export const fromHex = async (input: string): Promise<string> => {+ await sodium.ready;+ return await toB64(sodium.from_hex(input));+};++/**+ * If the provided {@link bob} ("Bytes or B64 string") is already a+ * {@link Uint8Array}, return it unchanged, otherwise convert the base64 string+ * into bytes and return those.+ */+const bytes = async (bob: BytesOrB64) =>+ typeof bob == "string" ? fromB64(bob) : bob;++/**+ * Generate a new randomly generated 256-bit key for use as a general encryption+ * key and return its base64 string representation.+ *+ * From the architecture docs:+ *+ * > [`crypto_secretbox_keygen`](https://libsodium.gitbook.io/doc/public-key_cryptography/sealed_boxes)+ * > is used to generate all random keys within the application. Your+ * > `masterKey`, `recoveryKey`, `collectionKey`, `fileKey` are all 256-bit keys+ * > generated using this API.+ *+ * {@link generateKey} can be contrasted with {@link generateBlobOrStreamKey}+ * and can be thought of as a hypothetical "generateBoxKey". That is, the key+ * returned by this function is suitable for being used with the *Box encryption+ * functions (which eventually delegate to the libsodium's secretbox APIs).+ *+ * While this is a reasonable semantic distinction, in terms of implementation+ * there is no difference: currently both {@link generateKey} (or the+ * hypothetical "generateBoxKey") and {@link generateBlobOrStreamKey} produce+ * 256-bits of entropy that does not have any ties to a particular algorithm.+ *+ * @returns A new randomly generated 256-bit key (as a base64 string).+ */+export const generateKey = async () => {+ await sodium.ready;+ return toB64(sodium.crypto_secretbox_keygen());+};++/**+ * Generate a new key for use with the *Blob or *Stream encryption functions,+ * and return its base64 string representation.+ *+ * This returns a new randomly generated 256-bit key (as a base64 string)+ * suitable for being used with libsodium's secretstream APIs.+ */+export const generateBlobOrStreamKey = async () => {+ await sodium.ready;+ return toB64(sodium.crypto_secretstream_xchacha20poly1305_keygen());+};++/**+ * Encrypt the given data using libsodium's secretbox APIs, using a randomly+ * generated nonce.+ *+ * Use {@link decryptBox} or {@link decryptBoxBytes} to decrypt the result.+ *+ * @param data The data to encrypt.+ *+ * @param key The key to use for encryption.+ *+ * @returns The encrypted data and the generated nonce, both as base64 strings.+ *+ * [Note: 3 forms of encryption (Box | Blob | Stream)]+ *+ * libsodium provides two "high level" encryption patterns:+ *+ * 1. Authenticated encryption ("secretbox")+ * https://doc.libsodium.org/secret-key_cryptography/secretbox+ *+ * 2. Encrypted streams and file encryption ("secretstream")+ * https://doc.libsodium.org/secret-key_cryptography/secretstream+ *+ * In terms of the underlying algorithm, they are essentially the same.+ *+ * 1. The secretbox APIs use XSalsa20 with Poly1305 (where XSalsa20 is the+ * stream cipher used for encryption, which Poly1305 is the MAC used for+ * authentication).+ *+ * 2. The secretstream APIs use XChaCha20 with Poly1305.+ *+ * XSalsa20 is a minor variant (predecessor in fact) of XChaCha20. I am not+ * aware why libsodium uses both the variants, but they seem to have similar+ * characteristics.+ *+ * These two sets of APIs map functionally map to two different use cases.+ *+ * 1. If there is a single independent bit of data to encrypt, the secretbox+ * APIs fit the bill.+ *+ * 2. If there is a set of related data to encrypt, e.g. the contents of a file+ * where the file is too big to fit into a single message, then the+ * secretstream APIs are more appropriate.+ *+ * However, in our code we have evolved two different use cases for the 2nd+ * option. The data to encrypt might be smaller than our streaming encryption+ * chunk size (e.g. the public magic metadata associated with the+ * {@link EnteFile}), so we do not chunk it and instead encrypt / decrypt it in+ * a single go. In contrast, the actual file that the user wishes to upload may+ * be arbitrarily big, and there we first break in into chunks before using the+ * streaming encryption.+ *+ * Thus, we have three scenarios:+ *+ * 1. Box: Using secretbox APIs to encrypt some independent blob of data.+ *+ * 2. Blob: Using secretstream APIs without chunking. This is used to encrypt+ * data associated to an Ente object (file, collection, entity, etc), when+ * the data is small-ish (less than a few MBs).+ *+ * 3. Stream/Chunks: Using secretstream APIs for encrypting chunks. This is used+ * to encrypt the actual content of the files associated with an EnteFile+ * object. This itself happens in two ways:+ *+ * 3a. One shot mode - where we do break the data into chunks, but a single+ * function processes all the chunks in one go.+ *+ * 3b. Streaming - where all the chunks are processed one by one.+ *+ * "Blob" is not a prior term of art in this context, it is just something we+ * use to abbreviate "data encrypted using secretstream APIs without chunking".+ *+ * The distinction between Box and Blob is also handy since not only does the+ * underlying algorithm differ, but also the terminology that libsodium use for+ * the nonce.+ *+ * 1. When using the secretbox APIs, the nonce is called the "nonce", and needs+ * to be provided by us (the caller).+ *+ * 2. When using the secretstream APIs, the nonce is internally generated by+ * libsodium and provided by libsodium to us (the caller) as a "header".+ *+ * However, even for case 1, the functions we expose from libsodium.ts generate+ * the nonce for the caller. So for higher level functions, the difference+ * between Box and Blob encryption is:+ *+ * 1. Box uses secretbox APIs (Salsa), Blob uses secretstream APIs (ChaCha).+ *+ * 2. Blob should generally be used for data associated with an Ente object, and+ * Box for the other cases.+ *+ * 3. Box returns a "nonce", while Blob returns a "header".+ *+ * The difference between case 2 and 3 (Blob vs Stream) is that while both use+ * the same algorithms, in case of Blob the entire data is encrypted / decrypted+ * without chunking, whilst the *Stream routines first break it into+ * {@link streamEncryptionChunkSize} chunks.+ */+export const encryptBox = async (+ data: BytesOrB64,+ key: BytesOrB64,+): Promise<EncryptedBoxB64> => {+ await sodium.ready;+ const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);+ const encryptedData = sodium.crypto_secretbox_easy(+ await bytes(data),+ nonce,+ await bytes(key),+ );+ return {+ encryptedData: await toB64(encryptedData),+ nonce: await toB64(nonce),+ };+};++/**+ * Encrypt the given data using libsodium's secretstream APIs without chunking.+ *+ * Use {@link decryptBlobBytes} to decrypt the result.+ *+ * @param data The data to encrypt.+ *+ * @param key The key to use for encryption.+ *+ * @returns The encrypted data and the decryption header as {@link Uint8Array}s.+ *+ * - See: [Note: 3 forms of encryption (Box | Blob | Stream)].+ *+ * - See: https://doc.libsodium.org/secret-key_cryptography/secretstream+ */+export const encryptBlobBytes = async (+ data: BytesOrB64,+ key: BytesOrB64,+): Promise<EncryptedBlobBytes> => {+ await sodium.ready;++ const keyBytes = await bytes(key);+ const initPushResult =+ sodium.crypto_secretstream_xchacha20poly1305_init_push(keyBytes);+ const [pushState, header] = [initPushResult.state, initPushResult.header];++ const pushResult = sodium.crypto_secretstream_xchacha20poly1305_push(+ pushState,+ await bytes(data),+ null,+ sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL,+ );+ return { encryptedData: pushResult, decryptionHeader: header };+};++/**+ * A higher level variant of {@link encryptBlobBytes} that returns the both the+ * encrypted data and decryption header as base64 strings.+ *+ * This is the variant expected to serve majority of the public API use cases.+ */+export const encryptBlob = async (+ data: BytesOrB64,+ key: BytesOrB64,+): Promise<EncryptedBlobB64> => {+ const { encryptedData, decryptionHeader } = await encryptBlobBytes(+ data,+ key,+ );+ return {+ encryptedData: await toB64(encryptedData),+ decryptionHeader: await toB64(decryptionHeader),+ };+};++/**+ * Encrypt the provided JSON value (using {@link encryptBlob}) after converting+ * it to a JSON string (and UTF-8 encoding it to obtain bytes).+ *+ * Use {@link decryptMetadataJSON} to decrypt the result and convert it back to+ * a JSON value.+ */+export const encryptMetadataJSON = (+ jsonValue: unknown,+ key: BytesOrB64,+): Promise<EncryptedBlobB64> =>+ encryptBlob(new TextEncoder().encode(JSON.stringify(jsonValue)), key);++/**+ * Encrypt the given data using libsodium's secretstream APIs after breaking it+ * into {@link streamEncryptionChunkSize} chunks.+ *+ * Use {@link decryptStreamBytes} to decrypt the result.+ *+ * Unlike {@link initChunkDecryption} / {@link encryptFileChunk}, this function+ * processes all the chunks at once in a single call to this function.+ *+ * @param data The data to encrypt.+ *+ * @returns The encrypted bytes ({@link Uint8Array}) and the decryption header+ * (as a base64 string).+ *+ * - See: [Note: 3 forms of encryption (Box | Blob | Stream)].+ *+ * - See: https://doc.libsodium.org/secret-key_cryptography/secretstream+ */+export const encryptStreamBytes = async (+ data: Uint8Array,+ key: BytesOrB64,+): Promise<EncryptedFile> => {+ await sodium.ready;++ const keyBytes = await bytes(key);+ const initPushResult =+ sodium.crypto_secretstream_xchacha20poly1305_init_push(keyBytes);+ const [pushState, header] = [initPushResult.state, initPushResult.header];+ let bytesRead = 0;+ let tag = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;++ const encryptedChunks = [];++ while (tag !== sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL) {+ let chunkSize = streamEncryptionChunkSize;+ if (bytesRead + chunkSize >= data.length) {+ chunkSize = data.length - bytesRead;+ tag = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL;+ }++ const buffer = data.slice(bytesRead, bytesRead + chunkSize);+ bytesRead += chunkSize;+ const pushResult = sodium.crypto_secretstream_xchacha20poly1305_push(+ pushState,+ buffer,+ null,+ tag,+ );+ encryptedChunks.push(pushResult);+ }+ return {+ encryptedData: mergeUint8Arrays(encryptedChunks),+ decryptionHeader: await toB64(header),+ };+};++/**+ * Initialize libsodium's secretstream APIs for encrypting+ * {@link streamEncryptionChunkSize} chunks. Subsequently, each chunk can be+ * encrypted using {@link encryptStreamChunk}.+ *+ * Use {@link initChunkDecryption} to initialize the decryption routine, and+ * {@link decryptStreamChunk} to decrypt the individual chunks.+ *+ * See also: {@link encryptStreamBytes} which also does chunked encryption but+ * encrypts all the chunks in a single call.+ *+ * @param key The key to use for encryption.+ *+ * @returns The decryption header (as a base64 string) which should be preserved+ * and used during decryption, and an opaque "push state" that should be passed+ * to subsequent calls to {@link encryptStreamChunk} along with the chunks's+ * contents.+ */+export const initChunkEncryption = async (+ key: BytesOrB64,+): Promise<InitChunkEncryptionResult> => {+ await sodium.ready;+ const keyBytes = await bytes(key);+ const { state, header } =+ sodium.crypto_secretstream_xchacha20poly1305_init_push(keyBytes);+ return { decryptionHeader: await toB64(header), pushState: state };+};++/**+ * Encrypt an individual chunk using libsodium's secretstream APIs.+ *+ * This function is not meant to be standalone, but is instead called in tandem+ * with {@link initChunkEncryption} for encrypting data after breaking it into+ * chunks.+ *+ * @param data The chunk's data as bytes ({@link Uint8Array}).+ *+ * @param pushState The state for this instantiation of chunked encryption. This+ * should be treated as opaque libsodium state that should be passed to all+ * calls to {@link encryptStreamChunk} that are paired with a particular+ * {@link initChunkEncryption}.+ *+ * @param isFinalChunk `true` if this is the last chunk in the sequence.+ *+ * @returns The encrypted chunk.+ */+export const encryptStreamChunk = async (+ data: Uint8Array,+ pushState: SodiumStateAddress,+ isFinalChunk: boolean,+): Promise<Uint8Array> => {+ await sodium.ready;+ const tag = isFinalChunk+ ? sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL+ : sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;+ return sodium.crypto_secretstream_xchacha20poly1305_push(+ pushState,+ data,+ null,+ tag,+ );+};++/**+ * Decrypt the result of {@link encryptBox} and return the decrypted bytes.+ */+export const decryptBoxBytes = async (+ { encryptedData, nonce }: EncryptedBox,+ key: BytesOrB64,+): Promise<Uint8Array> => {+ await sodium.ready;+ return sodium.crypto_secretbox_open_easy(+ await bytes(encryptedData),+ await bytes(nonce),+ await bytes(key),+ );+};++/**+ * Variant of {@link decryptBoxBytes} that returns the data as a base64 string.+ */+export const decryptBox = (+ box: EncryptedBox,+ key: BytesOrB64,+): Promise<string> => decryptBoxBytes(box, key).then(toB64);++/**+ * Decrypt the result of {@link encryptBlobBytes} or {@link encryptBlob}.+ */+export const decryptBlobBytes = async (+ { encryptedData, decryptionHeader }: EncryptedBlob,+ key: BytesOrB64,+): Promise<Uint8Array> => {+ await sodium.ready;+ const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(+ await bytes(decryptionHeader),+ await bytes(key),+ );+ const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(+ pullState,+ await bytes(encryptedData),+ null,+ );+ return pullResult.message;+};++/**+ * A variant of {@link decryptBlobBytes} that returns the result as a base64+ * string.+ */+export const decryptBlob = (+ blob: EncryptedBlob,+ key: BytesOrB64,+): Promise<string> => decryptBlobBytes(blob, key).then(toB64);++/**+ * Decrypt the result of {@link encryptMetadataJSON} and return the JSON value+ * obtained by parsing the decrypted JSON string (which is obtained by UTF-8+ * decoding the decrypted bytes).+ *+ * Since TypeScript doesn't currently have a native JSON type, the returned+ * value is casted as an `unknown`.+ */+export const decryptMetadataJSON = async (+ blob: EncryptedBlob,+ key: BytesOrB64,+): Promise<unknown> =>+ JSON.parse(+ new TextDecoder().decode(await decryptBlobBytes(blob, key)),+ ) as unknown;++/**+ * Decrypt the result of {@link encryptStreamBytes}.+ */+export const decryptStreamBytes = async (+ { encryptedData, decryptionHeader }: EncryptedFile,+ key: BytesOrB64,+): Promise<Uint8Array> => {+ await sodium.ready;+ const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(+ await fromB64(decryptionHeader),+ await bytes(key),+ );+ const decryptionChunkSize =+ streamEncryptionChunkSize ++ sodium.crypto_secretstream_xchacha20poly1305_ABYTES;+ let bytesRead = 0;+ const decryptedChunks = [];+ let tag = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;+ while (tag !== sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL) {+ let chunkSize = decryptionChunkSize;+ if (bytesRead + chunkSize > encryptedData.length) {+ chunkSize = encryptedData.length - bytesRead;+ }+ const buffer = encryptedData.slice(bytesRead, bytesRead + chunkSize);+ const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(+ pullState,+ buffer,+ );+ decryptedChunks.push(pullResult.message);+ tag = pullResult.tag;+ bytesRead += chunkSize;+ }+ return mergeUint8Arrays(decryptedChunks);+};++/**+ * Prepare to decrypt the result of {@link initChunkEncryption} and+ * {@link encryptStreamChunk}.+ *+ * @param decryptionHeader The header (as a base64 string) that was produced+ * during encryption by {@link initChunkEncryption}.+ *+ * @param key The encryption key.+ *+ * @returns The pull state, which should be treated as opaque libsodium specific+ * state that should be passed along to each subsequent call to+ * {@link decryptStreamChunk}, and the size of each (decrypted) chunk that will+ * be produced by subsequent calls to {@link decryptStreamChunk}.+ */+export const initChunkDecryption = async (+ decryptionHeader: string,+ key: BytesOrB64,+): Promise<InitChunkDecryptionResult> => {+ await sodium.ready;+ const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(+ await fromB64(decryptionHeader),+ await bytes(key),+ );+ const decryptionChunkSize =+ streamEncryptionChunkSize ++ sodium.crypto_secretstream_xchacha20poly1305_ABYTES;+ return { pullState, decryptionChunkSize };+};++/**+ * Decrypt an individual chunk of the data encrypted using+ * {@link initChunkEncryption} and {@link encryptStreamChunk}.+ *+ * This is meant to be used in tandem with {@link initChunkDecryption}. During+ * each invocation, it should be passed the encrypted chunk, and the+ * {@link pullState} returned by {@link initChunkDecryption}. It will then+ * return the corresponding decrypted chunk's bytes.+ */+export const decryptStreamChunk = async (+ data: Uint8Array,+ pullState: SodiumStateAddress,+): Promise<Uint8Array> => {+ await sodium.ready;+ const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(+ pullState,+ data,+ );+ return pullResult.message;+};++/**+ * Initialize and return new state that can be used to hash the chunks of data+ * in a streaming manner.+ *+ * [Note: Chunked hashing]+ *+ * 1. Obtain a hash state using {@link chunkHashInit}.+ *+ * 2. Pass the hash state and the data chunk to {@link chunkHashUpdate}.+ *+ * 3. Finalize the hash state and obtain the hash using {@link chunkHashFinal}.+ *+ * @returns An opaque object representing the hash state. This can be passed+ * (along with the data to hash) to {@link chunkHashUpdate}, and the final hash+ * obtained using {@link chunkHashFinal}.+ */+export const chunkHashInit = async (): Promise<SodiumStateAddress> => {+ await sodium.ready;+ return sodium.crypto_generichash_init(+ null,+ sodium.crypto_generichash_BYTES_MAX,+ );+};++/**+ * Update the hash state to incorporate the contents of the provided data chunk.+ *+ * See: [Note: Chunked hashing]+ *+ * @param hashState A hash state obtained using {@link chunkHashInit}.+ *+ * @param chunk The data (bytes) to hash.+ */+export const chunkHashUpdate = async (+ hashState: SodiumStateAddress,+ chunk: Uint8Array,+) => {+ await sodium.ready;+ sodium.crypto_generichash_update(hashState, chunk);+};++/**+ * Finalize a hash state and return the hash it represents (as a base64 string).+ *+ * See: [Note: Chunked hashing]+ *+ * @param hashState A hash state obtained using {@link chunkHashInit} and fed+ * chunks using {@link chunkHashUpdate}.+ *+ * @returns The hash of all the chunks (as a base64 string).+ */+export const chunkHashFinal = async (hashState: SodiumStateAddress) => {+ await sodium.ready;+ const hash = sodium.crypto_generichash_final(+ hashState,+ sodium.crypto_generichash_BYTES_MAX,+ );+ return toB64(hash);+};++/**+ * Generate a new public/private keypair for use with public-key encryption+ * functions, and return their base64 string representations.+ *+ * These keys are suitable for being used with the {@link boxSeal} and+ * {@link boxSealOpen} functions.+ */+export const generateKeyPair = async () => {+ await sodium.ready;+ const keyPair = sodium.crypto_box_keypair();+ return {+ publicKey: await toB64(keyPair.publicKey),+ privateKey: await toB64(keyPair.privateKey),+ };+};++/**+ * Public key encryption.+ *+ * Encrypt the given {@link data} using the given {@link publicKey}.+ *+ * This function performs asymmetric (public-key) encryption. To decrypt the+ * result, use {@link boxSealOpen}.+ *+ * @param data The input data to encrypt, represented as a base64 string.+ *+ * @param publicKey The public key to use for encryption (as a base64 string).+ *+ * @returns The encrypted data (as a base64 string).+ */+export const boxSeal = async (data: string, publicKey: string) => {+ await sodium.ready;+ return toB64(+ sodium.crypto_box_seal(await fromB64(data), await fromB64(publicKey)),+ );+};++/**+ * Decrypt the result of {@link boxSeal}.+ *+ * All parameters are base64 string representations of the underlying data. The+ * result is the bytes obtained by decryption.+ */+export const boxSealOpenBytes = async (+ encryptedData: string,+ { publicKey, privateKey }: KeyPair,+): Promise<Uint8Array> => {+ await sodium.ready;+ return sodium.crypto_box_seal_open(+ await fromB64(encryptedData),+ await fromB64(publicKey),+ await fromB64(privateKey),+ );+};++/**+ * A variant of {@link boxSealOpenBytes} that returns the result as a base64+ * string.+ */+export const boxSealOpen = async (encryptedData: string, keyPair: KeyPair) =>+ toB64(await boxSealOpenBytes(encryptedData, keyPair));++/**+ * Generate a new randomly generated 128-bit salt suitable for use with the key+ * derivation functions ({@link deriveKey} and its variants).+ *+ * @returns The base64 representation of a randomly generated 128-bit salt.+ */+export const generateDeriveKeySalt = async () => {+ await sodium.ready;+ return await toB64(sodium.randombytes_buf(sodium.crypto_pwhash_SALTBYTES));+};++/**+ * Derive a key by hashing the given {@link passphrase} using Argon 2id.+ *+ * While the underlying primitive is a password hash (e.g for its storage), this+ * function is also meant for key derivation using a low-entropy input by+ * deriving a longer hash from the user's human chosen passphrase.+ *+ * The returned key can be used with the various *Box encryption routines.+ *+ * @param passphrase The password / passphrase to hash (normal UTF-8 string).+ *+ * @param salt Base64 string representing the salt to use when hashing.+ *+ * @param opsLimit Operation limit. The maximum amount of computations to+ * perform.+ *+ * @param memLimit Memory limit. The maximum amount of RAM to use.+ *+ * @returns The base64 representation of a 256-bit key suitable for being used+ * with libsodium's secretbox APIs.+ */+export const deriveKey = async (+ passphrase: string,+ salt: string,+ opsLimit: number,+ memLimit: number,+) => {+ await sodium.ready;+ return await toB64(+ sodium.crypto_pwhash(+ sodium.crypto_secretbox_KEYBYTES,+ sodium.from_string(passphrase),+ await fromB64(salt),+ opsLimit,+ memLimit,+ sodium.crypto_pwhash_ALG_ARGON2ID13,+ ),+ );+};++/**+ * A variant of {@link deriveKey} with (dynamic) parameters for deriving+ * sensitive keys (like the user's master key KEK (key encryption key).+ *+ * This function defers to {@link deriveKey} after choosing the most secure ops+ * and mem limits that the current device can handle. For details about these+ * limits, see https://libsodium.gitbook.io/doc/password_hashing/default_phf.+ *+ * @returns Both the derived key, and the ops and mem limits that were chosen+ * during the derivation (this information will be needed the user's other+ * clients to derive the same result).+ */+export const deriveSensitiveKey = async (+ passphrase: string,+): Promise<DerivedKey> => {+ await sodium.ready;++ const salt = await generateDeriveKeySalt();++ const desiredStrength =+ sodium.crypto_pwhash_MEMLIMIT_SENSITIVE *+ sodium.crypto_pwhash_OPSLIMIT_SENSITIVE;+ // When the sensitive memLimit (1 GB) is used, on low spec devices the OS+ // often kills the app with OOM. Note that could happen at a later stage+ // too, so checking the current device's capabilities will not help. For+ // example, the user may create an account on a powerful desktop device, but+ // then try to log in later on their weaker mobile device, and will need to+ // reset their password.+ //+ // To avoid this, we start with the moderate memLimit (256 MB), but scale up+ // the opsLimit correspondingly (16). This ensures that the product of these+ // two variables (the area under the graph that determines the amount of+ // work) stays the same.+ let memLimit = sodium.crypto_pwhash_MEMLIMIT_MODERATE; // = 256 MB+ const factor = Math.floor(+ sodium.crypto_pwhash_MEMLIMIT_SENSITIVE /+ sodium.crypto_pwhash_MEMLIMIT_MODERATE,+ ); // = 4+ let opsLimit = sodium.crypto_pwhash_OPSLIMIT_SENSITIVE * factor; // = 16+ if (memLimit * opsLimit != desiredStrength) {+ throw new Error(`Invalid mem and ops limits: ${memLimit}, ${opsLimit}`);+ }++ const minMemLimit = sodium.crypto_pwhash_MEMLIMIT_MIN;+ while (memLimit > minMemLimit) {+ try {+ const key = await deriveKey(passphrase, salt, opsLimit, memLimit);+ return { key, salt, opsLimit, memLimit };+ } catch {+ opsLimit *= 2;+ memLimit /= 2;+ }+ }+ throw new Error(deriveKeyInsufficientMemoryErrorMessage);+};++/**+ * A variant of {@link deriveSensitiveKey} for deriving an alternative key with+ * parameters suitable for interactive use.+ */+export const deriveInteractiveKey = async (+ passphrase: string,+): Promise<DerivedKey> => {+ const salt = await generateDeriveKeySalt();+ const opsLimit = sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE;+ const memLimit = sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE;++ const key = await deriveKey(passphrase, salt, opsLimit, memLimit);+ return { key, salt, opsLimit, memLimit };+};++/**+ * Derive a {@link subKeyID}-th subkey of length {@link subKeyLength} bytes by+ * applying a KDF (Key Derivation Function) for the given {@link key} and the+ * {@link context}.+ *+ * Multiple secret subkeys can be (deterministically) derived from a single+ * high-entropy key. Knowledge of the derived key does not impact the security+ * of the key from which it was derived, or of its potential sibling subkeys.+ *+ * See: https://doc.libsodium.org/key_derivation+ *+ * @param key The key whose subkey we are deriving. In the context of+ * key derivation, this is usually referred to as the "master key", but we+ * deemphasize that nomenclature to avoid confusion with the user's master key.+ *+ * @param subKeyLength The length of the required subkey.+ *+ * @param subKeyID An identifier of the subkey.+ *+ * @param context A short but otherwise arbitrary string (non-secret) used to+ * separate domains in which the subkeys are going to be used.+ *+ * @returns The bytes of the subkey.+ *+ * Note that returning bytes is a bit unusual, usually we'd return the base64+ * string from functions. However, this particular function is used in only one+ * place in our code, and so we adapt the interface for its convenience.+ */+export const deriveSubKeyBytes = async (+ key: BytesOrB64,+ subKeyLength: number,+ subKeyID: number,+ context: string,+): Promise<Uint8Array> => {+ await sodium.ready;+ return sodium.crypto_kdf_derive_from_key(+ subKeyLength,+ subKeyID,+ context,+ await bytes(key),+ );+};diff --git a/web/apps/albums/vendor/ente-base/crypto/types.ts b/web/apps/albums/vendor/ente-base/crypto/types.tsnew file mode 100644index 0000000000..8b82a2aef8--- /dev/null+++ b/web/apps/albums/vendor/ente-base/crypto/types.ts@@ -0,0 +1,243 @@+/**+ * @file types shared between the public API (main thread) and implementation+ * (worker thread). Also some constants, but no code.+ */+import { type StateAddress } from "libsodium-wrappers-sumo";++/**+ * An opaque object meant to be threaded through various functions that deal+ * with resumable chunk based processing.+ */+export type SodiumStateAddress = StateAddress;++/**+ * The various *Stream encryption functions break up the input into chunks of+ * {@link streamEncryptionChunkSize} bytes during encryption (except the last+ * chunk which can be smaller since a file would rarely align exactly to a+ * {@link streamEncryptionChunkSize} multiple).+ *+ * The various *Stream decryption functions also assume that each potential+ * chunk is {@link streamEncryptionChunkSize} long.+ *+ * This value of this constant is 4 MB (and is unlikely to change).+ */+export const streamEncryptionChunkSize = 4 * 1024 * 1024;++/**+ * The message of the {@link Error} that is thrown by {@link deriveSensitiveKey}+ * if we could not find acceptable ops and mem limit combinations without+ * exceeded the maximum mem limit.+ *+ * Generally, this indicates that the current device is not powerful enough to+ * perform the key derivation. This is rare for computers, but can happen with+ * older mobile devices with too little RAM.+ */+export const deriveKeyInsufficientMemoryErrorMessage =+ "Failed to derive key (insufficient memory)";++/**+ * Data provided either as bytes ({@link Uint8Array}) or their base64 string+ * representation.+ */+export type BytesOrB64 = Uint8Array | string;++/**+ * The result of encryption using the secretbox APIs.+ *+ * It contains an encrypted data and a randomly generated nonce that was used+ * during encryption. Both these values are needed to decrypt the data. The+ * nonce does not need to be secret.+ *+ * See: [Note: 3 forms of encryption (Box | Blob | Stream)].+ */+export interface EncryptedBox {+ /**+ * The data to decrypt.+ */+ encryptedData: BytesOrB64;+ /**+ * The nonce that was used during encryption.+ *+ * The nonce is required to decrypt the data, but it does not need to be+ * kept secret.+ */+ nonce: BytesOrB64;+}++export interface EncryptedBoxB64 {+ /**+ * The encrypted data as a base64 string.+ */+ encryptedData: string;+ /**+ * The nonce that was used during encryption, as a base64 string.+ *+ * The nonce is required to decrypt the data, but it does not need to be+ * kept secret.+ */+ nonce: string;+}++/**+ * The result of encryption using the secretstream APIs without chunking.+ *+ * It contains an encrypted data and a header that should be provided during+ * decryption. The header does not need to be secret.+ *+ * See: [Note: 3 forms of encryption (Box | Blob | Stream)].+ *+ * This type is a combination of {@link EncryptedBlobBytes} and+ * {@link EncryptedBlobB64} which allows the decryption routines to accept+ * either the bytes or the base64 variants produced by the encryption routines.+ */+export interface EncryptedBlob {+ /**+ * The encrypted data.+ */+ encryptedData: BytesOrB64;+ /**+ * The decryption header.+ *+ * While the exact contents of the header are libsodium's internal details,+ * it effectively contains a random nonce generated by libsodium. It does+ * not need to be secret, but it is required to decrypt the data.+ */+ decryptionHeader: BytesOrB64;+}++/**+ * A variant of {@link EncryptedBlob} that has the encrypted data and header+ * as bytes ({@link Uint8Array}s).+ */+export interface EncryptedBlobBytes {+ /**+ * The encrypted data.+ */+ encryptedData: Uint8Array;+ /**+ * The decryption header.+ *+ * While the exact contents of the header are libsodium's internal details,+ * it effectively contains a random nonce generated by libsodium. It does+ * not need to be secret, but it is required to decrypt the data.+ */+ decryptionHeader: Uint8Array;+}++/**+ * A variant of {@link EncryptedBlob} that has the encrypted data and header+ * as base64 strings.+ */+export interface EncryptedBlobB64 {+ /**+ * The encrypted data as a base64 string.+ */+ encryptedData: string;+ /**+ * A base64 string containing the decryption header.+ *+ * While the exact contents of the header are libsodium's internal details,+ * it effectively contains a random nonce generated by libsodium. It does+ * not need to be secret, but it is required to decrypt the data.+ */+ decryptionHeader: string;+}++/**+ * An intermediate between {@link EncryptedBlobBytes} and+ * {@link EncryptedBlobB64} that has the encrypted as bytes+ * ({@link Uint8Array}s), but the {@link decryptionHeader} as a base64 string.+ *+ * Such a format is handy for encrypting files, since it can then directly be+ * used (the file's encrypted bytes get uploaded separately, whilst the base64+ * decryption header becomes part of the corresponding {@link EnteFile}).+ */+export interface EncryptedFile {+ /**+ * The encrypted data.+ */+ encryptedData: Uint8Array;+ /**+ * A base64 string containing the decryption header.+ *+ * While the exact contents of the header are libsodium's internal details,+ * it effectively contains a random nonce generated by libsodium. It does+ * not need to be secret, but it is required to decrypt the data.+ */+ decryptionHeader: string;+}++/**+ * An object returned by the init function of chunked encryption routines.+ */+export interface InitChunkEncryptionResult {+ /**+ * A base64 string containing the decryption header.+ *+ * While the exact contents of the header are libsodium's internal details,+ * it effectively contains a random nonce generated by libsodium. It does+ * not need to be secret, but it is required to decrypt the data.+ */+ decryptionHeader: string;+ /**+ * An opaque value that refers to the internal state used by the resumable+ * calls in the encryption sequence.+ */+ pushState: SodiumStateAddress;+}++/**+ * An object returned by the init function of chunked decryption routines.+ */+export interface InitChunkDecryptionResult {+ /**+ * An opaque value that refers to the internal state used by the resumable+ * calls in the decryption sequence.+ */+ pullState: SodiumStateAddress;+ /**+ * The expected size of each chunk.+ */+ decryptionChunkSize: number;+}++/**+ * A pair of public and private keys.+ */+export interface KeyPair {+ /**+ * The public key of the keypair, as a base64 encoded string.+ */+ publicKey: string;+ /**+ * The private key of the keypair, as a base64 encoded string.+ *+ * Some places also refer to it as the "secret key".+ *+ * See: [Note: privateKey and secretKey].+ */+ privateKey: string;+}++/**+ * A key derived from a user provided passphrase, and the various attributes+ * that were used during the key derivation.+ */+export interface DerivedKey {+ /**+ * The newly derived key itself, as a base64 encoded string.+ */+ key: string;+ /**+ * The randomly generated salt (as a base64 string) that was used when deriving the key.+ */+ salt: string;+ /**+ * opsLimit used during key derivation.+ */+ opsLimit: number;+ /**+ * memLimit used during key derivation.+ * */+ memLimit: number;+}diff --git a/web/apps/albums/vendor/ente-base/crypto/worker.ts b/web/apps/albums/vendor/ente-base/crypto/worker.tsnew file mode 100644index 0000000000..bc25a7c0ad--- /dev/null+++ b/web/apps/albums/vendor/ente-base/crypto/worker.ts@@ -0,0 +1,53 @@+import { expose } from "comlink";+import { logUnhandledErrorsAndRejectionsInWorker } from "ente-base/log-web";+import * as libsodium from "./libsodium";++/**+ * A web worker that exposes the functions defined by libsodium.ts.+ *+ * See: [Note: Crypto code hierarchy].+ *+ * Note: Keep these methods logic free. They are meant to be trivial proxies.+ */+export class CryptoWorker {+ toB64 = libsodium.toB64;+ fromB64 = libsodium.fromB64;+ toB64URLSafe = libsodium.toB64URLSafe;+ toB64URLSafeNoPadding = libsodium.toB64URLSafeNoPadding;+ fromB64URLSafeNoPadding = libsodium.fromB64URLSafeNoPadding;+ toHex = libsodium.toHex;+ fromHex = libsodium.fromHex;+ generateKey = libsodium.generateKey;+ generateBlobOrStreamKey = libsodium.generateBlobOrStreamKey;+ encryptBox = libsodium.encryptBox;+ encryptBlob = libsodium.encryptBlob;+ encryptBlobBytes = libsodium.encryptBlobBytes;+ encryptMetadataJSON = libsodium.encryptMetadataJSON;+ encryptStreamBytes = libsodium.encryptStreamBytes;+ initChunkEncryption = libsodium.initChunkEncryption;+ encryptStreamChunk = libsodium.encryptStreamChunk;+ decryptBox = libsodium.decryptBox;+ decryptBoxBytes = libsodium.decryptBoxBytes;+ decryptBlob = libsodium.decryptBlob;+ decryptBlobBytes = libsodium.decryptBlobBytes;+ decryptMetadataJSON = libsodium.decryptMetadataJSON;+ decryptStreamBytes = libsodium.decryptStreamBytes;+ initChunkDecryption = libsodium.initChunkDecryption;+ decryptStreamChunk = libsodium.decryptStreamChunk;+ chunkHashInit = libsodium.chunkHashInit;+ chunkHashUpdate = libsodium.chunkHashUpdate;+ chunkHashFinal = libsodium.chunkHashFinal;+ generateKeyPair = libsodium.generateKeyPair;+ boxSeal = libsodium.boxSeal;+ boxSealOpen = libsodium.boxSealOpen;+ boxSealOpenBytes = libsodium.boxSealOpenBytes;+ generateDeriveKeySalt = libsodium.generateDeriveKeySalt;+ deriveKey = libsodium.deriveKey;+ deriveSensitiveKey = libsodium.deriveSensitiveKey;+ deriveInteractiveKey = libsodium.deriveInteractiveKey;+ deriveSubKeyBytes = libsodium.deriveSubKeyBytes;+}++expose(CryptoWorker);++logUnhandledErrorsAndRejectionsInWorker();diff --git a/web/apps/albums/vendor/ente-base/date.ts b/web/apps/albums/vendor/ente-base/date.tsnew file mode 100644index 0000000000..1aea5aa2b1--- /dev/null+++ b/web/apps/albums/vendor/ente-base/date.ts@@ -0,0 +1,7 @@+/**+ * Return `true` if both the given dates have the same day.+ */+export const isSameDay = (first: Date, second: Date) =>+ first.getFullYear() === second.getFullYear() &&+ first.getMonth() === second.getMonth() &&+ first.getDate() === second.getDate();diff --git a/web/apps/albums/vendor/ente-base/electron.ts b/web/apps/albums/vendor/ente-base/electron.tsnew file mode 100644index 0000000000..1bc6634445--- /dev/null+++ b/web/apps/albums/vendor/ente-base/electron.ts@@ -0,0 +1,150 @@+import type { Electron } from "./types/ipc";++/**+ * A wrapper over a non-null assertion of `globalThis.electron`.+ *+ * This is useful where we have previously verified that the code path in which+ * we're running only executes when we're in electron (usually by directly+ * checking that `globalThis.electron` is defined somewhere up the chain).+ *+ * Generally, this should not be required - the check and the use should be+ * colocated, or the unwrapped non-null value saved somewhere. But sometimes+ * doing so requires code refactoring, so as an escape hatch we provide this+ * convenience function.+ *+ * It will throw if `globalThis.electron` is undefined.+ *+ * @see `global-electron.d.ts`.+ */+export const ensureElectron = (): Electron => {+ const et = globalThis.electron;+ if (et) return et;+ throw new Error(+ "Attempting to assert globalThis.electron in a non-electron context",+ );+};++const defaultTrustedWindowBlurSuppressionMs = 5 * 1e3;+let suppressMainWindowBlurUntil = 0;++/**+ * Temporarily suppress blur handling for trusted app-initiated native prompts.+ *+ * Native OS dialogs can blur the window without indicating user backgrounding+ * intent (for example, directory pickers). Consumers can gate blur-driven+ * actions during this short window.+ */+export const suppressMainWindowBlurForTrustedPrompt = (+ durationMs = defaultTrustedWindowBlurSuppressionMs,+) => {+ if (durationMs <= 0) return;+ suppressMainWindowBlurUntil = Math.max(+ suppressMainWindowBlurUntil,+ Date.now() + durationMs,+ );+};++export const shouldSuppressMainWindowBlur = () =>+ Date.now() < suppressMainWindowBlurUntil;++export const clearMainWindowBlurSuppression = () => {+ suppressMainWindowBlurUntil = 0;+};++type MainWindowFocusListener = () => void;+type MainWindowBlurListener = () => void;++const mainWindowFocusListeners = new Set<MainWindowFocusListener>();+let hasAttachedMainWindowFocusBridge = false;+const mainWindowBlurListeners = new Set<MainWindowBlurListener>();+let hasAttachedMainWindowBlurBridge = false;++const emitMainWindowFocus = () => {+ for (const listener of mainWindowFocusListeners) {+ listener();+ }+};++const attachMainWindowFocusBridgeIfNeeded = () => {+ if (hasAttachedMainWindowFocusBridge) return;+ const electron = globalThis.electron;+ if (!electron) return;+ electron.onMainWindowFocus(emitMainWindowFocus);+ hasAttachedMainWindowFocusBridge = true;+};++const detachMainWindowFocusBridgeIfNeeded = () => {+ if (+ !hasAttachedMainWindowFocusBridge ||+ mainWindowFocusListeners.size > 0+ ) {+ return;+ }++ const electron = globalThis.electron;+ if (electron) {+ electron.onMainWindowFocus(undefined);+ }+ hasAttachedMainWindowFocusBridge = false;+};++/**+ * Subscribe to main window focus events on Electron.+ *+ * This helper multiplexes listeners over Electron's single-callback API,+ * allowing multiple consumers to listen concurrently.+ */+export const subscribeMainWindowFocus = (+ listener: MainWindowFocusListener,+): (() => void) => {+ mainWindowFocusListeners.add(listener);+ attachMainWindowFocusBridgeIfNeeded();+ return () => {+ mainWindowFocusListeners.delete(listener);+ detachMainWindowFocusBridgeIfNeeded();+ };+};++const emitMainWindowBlur = () => {+ for (const listener of mainWindowBlurListeners) {+ listener();+ }+};++const attachMainWindowBlurBridgeIfNeeded = () => {+ if (hasAttachedMainWindowBlurBridge) return;+ const electron = globalThis.electron;+ if (!electron) return;+ if (typeof electron.onMainWindowBlur != "function") return;+ electron.onMainWindowBlur(emitMainWindowBlur);+ hasAttachedMainWindowBlurBridge = true;+};++const detachMainWindowBlurBridgeIfNeeded = () => {+ if (!hasAttachedMainWindowBlurBridge || mainWindowBlurListeners.size > 0) {+ return;+ }++ const electron = globalThis.electron;+ if (electron && typeof electron.onMainWindowBlur == "function") {+ electron.onMainWindowBlur(undefined);+ }+ hasAttachedMainWindowBlurBridge = false;+};++/**+ * Subscribe to main window blur events on Electron.+ *+ * This helper multiplexes listeners over Electron's single-callback API,+ * allowing multiple consumers to listen concurrently.+ */+export const subscribeMainWindowBlur = (+ listener: MainWindowBlurListener,+): (() => void) => {+ mainWindowBlurListeners.add(listener);+ attachMainWindowBlurBridgeIfNeeded();+ return () => {+ mainWindowBlurListeners.delete(listener);+ detachMainWindowBlurBridgeIfNeeded();+ };+};diff --git a/web/apps/albums/vendor/ente-base/env.ts b/web/apps/albums/vendor/ente-base/env.tsnew file mode 100644index 0000000000..1164164ba6--- /dev/null+++ b/web/apps/albums/vendor/ente-base/env.ts@@ -0,0 +1,37 @@+/**+ * A build is considered as a development build if either the NODE_ENV is+ * environment variable is set to 'development'.+ *+ * NODE_ENV is automatically set to 'development' when we run `yarn dev`. From+ * Next.js docs:+ *+ * > If the environment variable NODE_ENV is unassigned, Next.js automatically+ * assigns development when running the `next dev` command, or production for+ * all other commands.+ */+export const isDevBuild = process.env.NODE_ENV == "development";++/**+ * `true` if we're running in the default global context (aka the main thread)+ * of a web browser.+ *+ * In particular, this is `false` when we're running in a web worker,+ * irrespective of whether the worker is running in a Node.js context or a web+ * browser context.+ *+ * > We can be running in a browser context either if the user has the page open+ * in a web browser, or if we're the renderer process of an Electron app.+ *+ * Note that this cannot be a constant, otherwise it'll get inlined during SSR+ * with the wrong value.+ */+export const haveWindow = () => typeof window != "undefined";++/**+ * Return true if we are running in a [Web+ * Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)+ *+ * Note that this cannot be a constant, otherwise it'll get inlined during SSR+ * with the wrong value.+ */+export const inWorker = () => typeof importScripts == "function";diff --git a/web/apps/albums/vendor/ente-base/file-name.ts b/web/apps/albums/vendor/ente-base/file-name.tsnew file mode 100644index 0000000000..4b679d5a24--- /dev/null+++ b/web/apps/albums/vendor/ente-base/file-name.ts@@ -0,0 +1,105 @@+/**+ * The two parts of a file name - the name itself, and an (optional) extension.+ *+ * The extension does not include the dot.+ */+type FileNameComponents = [name: string, extension: string | undefined];++/**+ * Split a filename into its components - the name itself, and the extension (if+ * any) - returning both. The dot is not included in either.+ *+ * For example, `foo-bar.png` will be split into ["foo-bar", "png"].+ *+ * See {@link fileNameFromComponents} for the inverse operation.+ */+export const nameAndExtension = (fileName: string): FileNameComponents => {+ const i = fileName.lastIndexOf(".");+ // No extension+ if (i == -1) return [fileName, undefined];+ // A hidden file without an extension, e.g. ".gitignore"+ if (i == 0) return [fileName, undefined];+ // Both components present, just omit the dot.+ return [fileName.slice(0, i), fileName.slice(i + 1)];+};++/**+ * If the file name or path has an extension, return a lowercased version of it.+ *+ * This is handy when comparing the extension to a known set without worrying+ * about case sensitivity.+ *+ * See {@link nameAndExtension} for its more generic sibling.+ */+export const lowercaseExtension = (+ fileNameOrPath: string,+): string | undefined => {+ // We rely on the implementation of nameAndExtension using lastIndexOf to+ // allow us to also work on paths.+ const [, ext] = nameAndExtension(fileNameOrPath);+ return ext?.toLowerCase();+};++/**+ * Construct a file name from its components (name and extension).+ *+ * Inverse of {@link nameAndExtension}.+ */+export const fileNameFromComponents = (components: FileNameComponents) =>+ components.filter((x) => !!x).join(".");++/**+ * Return the file name portion from the given {@link path}.+ *+ * This tries to emulate the UNIX `basename` command. In particular, any+ * trailing slashes on the path are trimmed, so this function can be used to get+ * the name of the directory too.+ *+ * The path is assumed to use POSIX separators ("/").+ */+export const basename = (path: string) => {+ const pathComponents = path.split("/");+ for (let i = pathComponents.length - 1; i >= 0; i--) {+ const component = pathComponents[i];+ if (component && component.length > 0) return component;+ }+ return path;+};++/**+ * Return the directory portion from the given {@link path}.+ *+ * This tries to emulate the UNIX `dirname` command. In particular, any trailing+ * slashes on the path are trimmed, so this function can be used to get the path+ * leading up to a directory too.+ *+ * The path is assumed to use POSIX separators ("/").+ */+export const dirname = (path: string) => {+ const pathComponents = path.split("/");+ while (pathComponents.pop() == "") {+ /* no-op */+ }+ return pathComponents.join("/");+};++/**+ * Return a new path by joining two path components using the POSIX path+ * separator ("/").+ *+ * This is usually a trivial `p1/p2`, however it also handles the case where p1+ * already ends with a trailing slash. This can happen even if p1 is obtained+ * from a place which guarantees that only directory paths will be returned,+ * because p1 can be the path to a root folder (e.g. "/" on Linux, or "C:/" on+ * Windows), and the trivial join would then result in double slashes.+ *+ * @param p1 A path component that is expected to be using POSIX path+ * separators.+ *+ * @param p2 A path component that is expected to be using POSIX path+ * separators.+ *+ * @returns A path by joining p1 and p2 with a POSIX path separator if needed.+ */+export const joinPath = (p1: string, p2: string) =>+ p1.endsWith("/") ? p1 + p2 : `${p1}/${p2}`;diff --git a/web/apps/albums/vendor/ente-base/global-electron.d.ts b/web/apps/albums/vendor/ente-base/global-electron.d.tsnew file mode 100644index 0000000000..c5de87ea12--- /dev/null+++ b/web/apps/albums/vendor/ente-base/global-electron.d.ts@@ -0,0 +1,18 @@+import type { Electron } from "./types/ipc";++/**+ * Extend the global object's (`globalThis`) interface to state that it can+ * potentially hold a property called `electron`. It will be injected by our+ * preload.js script when we're running in the context of our desktop app.+ */+declare global {+ /**+ * Extra, desktop specific, APIs provided by our Node.js layer.+ *+ * This property will defined only when we're running inside our desktop+ * (Electron) app. It will expose a bunch of functions (see+ * {@link Electron}) that allow us to communicate with the Node.js layer of+ * our desktop app.+ */+ declare var electron: Electron | undefined;+}diff --git a/web/apps/albums/vendor/ente-base/http.ts b/web/apps/albums/vendor/ente-base/http.tsnew file mode 100644index 0000000000..d2942cb9ad--- /dev/null+++ b/web/apps/albums/vendor/ente-base/http.ts@@ -0,0 +1,314 @@+import { desktopAppVersion, isDesktop } from "ente-base/app";+import { wait } from "ente-utils/promise";+import { z } from "zod";+import { clientPackageName } from "./app";+import log from "./log";+import { ensureAuthToken } from "./token";++/**+ * Return headers that should be passed alongwith (almost) all authenticated+ * `fetch` calls that we make to our API servers.+ *+ * - The auth token+ * - The client package name.+ */+export const authenticatedRequestHeaders = async () => ({+ "X-Auth-Token": await ensureAuthToken(),+ "X-Client-Package": clientPackageName,+ ...(isDesktop && { "X-Client-Version": desktopAppVersion }),+});++/**+ * Return headers that should be passed alongwith (almost) all unauthenticated+ * `fetch` calls that we make to our remotes like our API servers (museum), or+ * to pre-signed URLs that are handled by the S3 storage buckets themselves.+ *+ * - The client package name.+ */+export const publicRequestHeaders = () => ({+ "X-Client-Package": clientPackageName,+ ...(isDesktop && { "X-Client-Version": desktopAppVersion }),+});++/**+ * A set of credentials needed to make public collections related API requests.+ */+export interface PublicAlbumsCredentials {+ /**+ * [Note: Public album access token]+ *+ * The public album access is a token that serves a similar purpose as the+ * "X-Auth-Token" for usual authenticated API requests that happen for a+ * logged in user, except:+ *+ * - It will be passed as the "X-Auth-Access-Token" header, and+ * - It also tells remote about the public album under consideration.+ *+ * This access token is variously referred to as the album token, or the+ * auth token, when the context is clear. The client obtains this from the+ * "t" query parameter of a public album URL, and then uses it both to:+ *+ * 1. Identify and authenticate itself with remote (this header).+ *+ * 2. Scope local storage per public album by using this access token as a+ * part of the local storage key. In this context it is sometimes also+ * referred to as a "collectionUID" by old code.+ */+ accessToken: string;+ /**+ * [Note: Password token for public albums requests].+ *+ * A password protected access token. This is only needed for albums that+ * are behind a password. In such cases, the client needs to fetch this+ * extra token from remote (in exchange for the public album's password),+ * and then pass it as the "X-Auth-Access-Token-JWT" header in authenticated+ * public collections related API requests.+ */+ accessTokenJWT?: string | undefined;+}++/**+ * Return headers that should be passed alongwith public collection related+ * authenticated `fetch` calls that we make to our API servers.+ *+ * - The auth token.+ * - The password protected auth token (if provided).+ * - The client package name.+ */+export const authenticatedPublicAlbumsRequestHeaders = ({+ accessToken,+ accessTokenJWT,+}: PublicAlbumsCredentials) => ({+ "X-Auth-Access-Token": accessToken,+ ...(accessTokenJWT && { "X-Auth-Access-Token-JWT": accessTokenJWT }),+ "X-Client-Package": clientPackageName,+});++/**+ * A custom Error that is thrown if a fetch fails with a non-2xx HTTP status.+ */+export class HTTPError extends Error {+ res: Response;+ details: Record<string, string>;++ constructor(res: Response) {+ // Trim off any query parameters from the URL before logging, it may+ // have tokens.+ //+ // Nb: res.url is URL obtained after any redirects, and thus is not+ // necessarily the same as the request's URL.+ const url = new URL(res.url);+ url.search = "";+ super(`HTTP ${res.status} ${res.statusText} (${url.pathname})`);++ const requestID = res.headers.get("x-request-id");+ const details = { url: url.href, ...(requestID && { requestID }) };++ // Cargo culted from+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition+ if (Error.captureStackTrace) Error.captureStackTrace(this, HTTPError);++ this.name = this.constructor.name;+ this.res = res;+ this.details = details;+ }+}++/**+ * A convenience method that throws an {@link HTTPError} if the given+ * {@link Response} does not have a HTTP 2xx status.+ */+export const ensureOk = (res: Response) => {+ if (!res.ok) {+ const e = new HTTPError(res);+ log.error(`${e.message} ${JSON.stringify(e.details)}`);+ throw e;+ }+};++/**+ * Return true if this is a HTTP error with the given {@link httpStatus}.+ */+export const isHTTPErrorWithStatus = (e: unknown, httpStatus: number) =>+ e instanceof HTTPError && e.res.status == httpStatus;++/**+ * Return true if this is a HTTP "client" error.+ *+ * This is a convenience matcher to check if {@link e} is an instance of+ * {@link HTTPError} with a 4xx status code. Such errors are client errors, and+ * (generally) retrying them will not help.+ */+export const isHTTP4xxError = (e: unknown) =>+ e instanceof HTTPError && e.res.status >= 400 && e.res.status <= 499;++/**+ * Return true if this is a HTTP 401 error.+ *+ * For authenticated requests, an HTTP "401 Unauthorized" indicates that the+ * credentials (auth token) is not valid.+ */+export const isHTTP401Error = (e: unknown) =>+ e instanceof HTTPError && e.res.status == 401;++/**+ * Return `true` if this is an error because of a HTTP failure response returned+ * by museum with the given "code" and HTTP status.+ *+ * > The function is async because it needs to parse the payload.+ *+ * For some known set of errors, museum returns a payload of the form+ *+ * {"code":"USER_NOT_REGISTERED","message":"User is not registered"}+ *+ * where the code can be used to match a specific reason for the HTTP request+ * failing. This function can be used as a predicate to check both the HTTP+ * status code and the "code" within the payload.+ */+export const isMuseumHTTPError = async (+ e: unknown,+ httpStatus: number,+ code: string,+) => {+ if (e instanceof HTTPError && e.res.status == httpStatus) {+ try {+ const payload = z+ .object({ code: z.string() })+ .parse(await e.res.json());+ return payload.code == code;+ } catch (e) {+ log.warn("Ignoring error when parsing error payload", e);+ return false;+ }+ }+ return false;+};++interface RetryAsyncOperationOpts {+ /**+ * An optional modification to the default wait times between retries.+ *+ * - default 1 orig + 3 retries (2s, 5s, 10s)+ * - "background" 1 orig + 3 retries (5s, 25s, 120s)+ *+ * default is fine for most operations, including interactive ones where we+ * don't want to wait too long before giving up. "background" is suitable+ * for non-interactive operations where we can wait for longer (thus better+ * handle remote hiccups) without degrading the user's experience.+ */+ retryProfile?: "background";+ /**+ * An optional function that is called with the corresponding error whenever+ * {@link op} rejects. It should throw the error if the retries should+ * immediately be aborted.+ */+ abortIfNeeded?: (error: unknown) => void;+}++/**+ * Retry a async operation on failure up to 4 times (1 original + 3 retries)+ * with exponential backoff.+ *+ * [Note: Retries of network requests should be idempotent]+ *+ * When dealing with network requests, avoid using this function directly, use+ * one of its wrappers like {@link retryEnsuringHTTPOk} instead. Those wrappers+ * ultimately use this function only, and there is nothing wrong with this+ * function generally, however since this function allows retrying arbitrary+ * promises, it is easy accidentally try and attempt retries of non-idemponent+ * requests, while the more restricted API of {@link retryEnsuringHTTPOk} and+ * other {@link HTTPRequestRetrier}s makes such misuse less likely.+ *+ * @param op A function that performs the operation, returning the promise for+ * its completion.+ *+ * @param opts Optional tweaks to the default implementation. See+ * {@link RetryAsyncOperationOpts}.+ *+ * @returns A promise that fulfills with to the result of a first successfully+ * fulfilled promise of the 4 (1 + 3) attempts, or rejects with the error+ * obtained either when {@link abortIfNeeded} throws, or with the error from the+ * last attempt otherwise.+ */+export const retryAsyncOperation = async <T>(+ op: () => Promise<T>,+ opts?: RetryAsyncOperationOpts,+): Promise<T> => {+ const { retryProfile, abortIfNeeded } = opts ?? {};+ const waitTimeBeforeNextTry =+ retryProfile == "background"+ ? [10000, 30000, 120000]+ : [2000, 5000, 10000];++ while (true) {+ try {+ return await op();+ } catch (e) {+ if (abortIfNeeded) {+ abortIfNeeded(e);+ }+ const t = waitTimeBeforeNextTry.shift();+ if (!t) throw e;+ log.warn("Will retry potentially transient request failure", e);+ await wait(t);+ }+ }+};++/**+ * A function that wraps the request(s) in retries if needed.+ *+ * See {@link retryEnsuringHTTPOk} for the canonical example. This typedef is to+ * allow us to talk about and pass functions that behave similar to+ * {@link retryEnsuringHTTPOk}, but perhaps with other additional checks.+ *+ * See also: [Note: Retries of network requests should be idempotent]+ */+export type HTTPRequestRetrier = (+ request: () => Promise<Response>,+ opts?: HTTPRequestRetrierOpts,+) => Promise<Response>;++type HTTPRequestRetrierOpts = Pick<RetryAsyncOperationOpts, "retryProfile">;++/**+ * A helper function to adapt {@link retryAsyncOperation} for HTTP fetches.+ *+ * This extends {@link retryAsyncOperation} by treating any non-200 OK status+ * (as matched by {@link ensureOk}) as an error that should be retried.+ */+export const retryEnsuringHTTPOk: HTTPRequestRetrier = (+ request: () => Promise<Response>,+ opts?: HTTPRequestRetrierOpts,+) =>+ retryAsyncOperation(async () => {+ const r = await request();+ ensureOk(r);+ return r;+ }, opts);++/**+ * A helper function to adapt {@link retryAsyncOperation} for HTTP fetches, but+ * treating any 4xx HTTP responses as irrecoverable failures.+ *+ * This is similar to {@link retryEnsuringHTTPOk}, except it stops retrying if+ * remote responds with a 4xx HTTP status.+ */+export const retryEnsuringHTTPOkOr4xx: HTTPRequestRetrier = (+ request: () => Promise<Response>,+ opts?: HTTPRequestRetrierOpts,+) =>+ retryAsyncOperation(+ async () => {+ const r = await request();+ ensureOk(r);+ return r;+ },+ {+ ...opts,+ abortIfNeeded(e) {+ if (isHTTP4xxError(e)) throw e;+ },+ },+ );diff --git a/web/apps/albums/vendor/ente-base/i18n-date.ts b/web/apps/albums/vendor/ente-base/i18n-date.tsnew file mode 100644index 0000000000..05cc4fd8af--- /dev/null+++ b/web/apps/albums/vendor/ente-base/i18n-date.ts@@ -0,0 +1,121 @@+/**+ * @file Various date formatters.+ *+ * Note that we rely on the current behaviour of a full reload on changing the+ * language. See: [Note: Changing locale causes a full reload].+ */+import i18n, { t } from "i18next";++const _dateFormat = new Intl.DateTimeFormat(i18n.language, {+ weekday: "short",+ day: "numeric",+ month: "short",+ year: "numeric",+});++const _dateWithoutYearFormat = new Intl.DateTimeFormat(i18n.language, {+ weekday: "short",+ day: "numeric",+ month: "short",+});++const _timeFormat = new Intl.DateTimeFormat(i18n.language, {+ timeStyle: "short",+});++/**+ * Return a locale aware formatted date from the given {@link Date}.+ *+ * The behaviour depends upon whether the given {@link date} falls within the+ * current calendar year.+ *+ * - For dates in the current year, year is omitted, e.g, "Fri, 21 Feb".+ *+ * - Otherwise, the year is included, e.g., "Fri, 21 Feb 2025".+ */+export const formattedDate = (date: Date) =>+ (isSameYear(date) ? _dateWithoutYearFormat : _dateFormat).format(date);++const isSameYear = (date: Date) =>+ new Date().getFullYear() === date.getFullYear();++/**+ * Return a locale aware formatted time from the given {@link Date}.+ *+ * Example: "11:51 AM"+ */+export const formattedTime = (date: Date) => _timeFormat.format(date);++/**+ * Return a locale aware formatted date and time from the given {@link Date},+ * using the year omission behavior as documented in {@link formattedDate}.+ *+ * Example:+ * - If within year: "Fri, 21 Feb at 11:51 AM".+ * - Otherwise: "Fri, 21 Feb 2025 at 11:51 AM"+ *+ * @param dateOrEpochMicroseconds A JavaScript Date or a numeric epoch+ * microseconds value.+ *+ * [Note: Remote timestamps are epoch microseconds]+ *+ * Remote talks in terms of epoch microseconds, while JavaScript dates are+ * underlain by epoch milliseconds.+ *+ * As a convenience, this function can be either be directly passed a JavaScript+ * date, or it can be given the raw epoch microseconds value and it'll convert+ * internally.+ */+export const formattedDateTime = (dateOrEpochMicroseconds: Date | number) =>+ _formattedDateTime(toDate(dateOrEpochMicroseconds));++const _formattedDateTime = (date: Date) =>+ [formattedDate(date), t("at"), formattedTime(date)].join(" ");++const toDate = (dm: Date | number) =>+ typeof dm == "number" ? new Date(dm / 1000) : dm;++let _relativeTimeFormat: Intl.RelativeTimeFormat | undefined;++/**+ * Return a locale aware relative version of the given date.+ *+ * Example: "in 23 days"+ *+ * @param dateOrEpochMicroseconds A JavaScript Date or a numeric epoch+ * microseconds value.+ *+ * See: [Note: Remote timestamps are epoch microseconds]+ */+export const formattedDateRelative = (+ dateOrEpochMicroseconds: Date | number,+) => {+ const units: [Intl.RelativeTimeFormatUnit, number][] = [+ ["year", 24 * 60 * 60 * 1000 * 365],+ ["month", (24 * 60 * 60 * 1000 * 365) / 12],+ ["day", 24 * 60 * 60 * 1000],+ ["hour", 60 * 60 * 1000],+ ["minute", 60 * 1000],+ ["second", 1000],+ ];++ const date = toDate(dateOrEpochMicroseconds);++ // Math.abs accounts for both past and future scenarios.+ const elapsed = Math.abs(date.getTime() - Date.now());++ // Lazily created, then cached, instance of RelativeTimeFormat.+ const relativeTimeFormat = (_relativeTimeFormat ??=+ new Intl.RelativeTimeFormat(i18n.language, {+ localeMatcher: "best fit",+ numeric: "always",+ style: "short",+ }));++ for (const [u, d] of units) {+ if (elapsed > d)+ return relativeTimeFormat.format(Math.round(elapsed / d), u);+ }++ return relativeTimeFormat.format(Math.round(elapsed / 1000), "second");+};diff --git a/web/apps/albums/vendor/ente-base/i18n.ts b/web/apps/albums/vendor/ente-base/i18n.tsnew file mode 100644index 0000000000..db154f2dab--- /dev/null+++ b/web/apps/albums/vendor/ente-base/i18n.ts@@ -0,0 +1,326 @@+import { isDevBuild } from "ente-base/env";+import log from "ente-base/log";+import { includes } from "ente-utils/type-guards";+import { getUserLocales } from "get-user-locale";+import i18n from "i18next";+import resourcesToBackend from "i18next-resources-to-backend";+import { initReactI18next } from "react-i18next";++/**+ * List of all {@link SupportedLocale}s.+ *+ * Locales are combinations of a language code, and an optional region code.+ *+ * For example, "en", "en-US", "en-IN" (Indian English), "pt" (Portuguese),+ * "pt-BR" (Brazilian Portuguese).+ *+ * In our Crowdin Project, we have work-in-progress translations into more+ * languages than this. When a translation reaches a high enough coverage, say+ * 90%, then we manually add it to this list of supported languages.+ */+export const supportedLocales = [+ "en-US" /* English */,+ "fr-FR" /* French */,+ "de-DE" /* German */,+ "ca-ES" /* Catalan */,+ "zh-CN" /* Simplified Chinese */,+ "nl-NL" /* Dutch */,+ "es-ES" /* Spanish */,+ "pt-PT" /* Portuguese */,+ "pt-BR" /* Portuguese, Brazilian */,+ "ru-RU" /* Russian */,+ "pl-PL" /* Polish */,+ "it-IT" /* Italian */,+ "lt-LT" /* Lithuanian */,+ "uk-UA" /* Ukrainian */,+ "vi-VN" /* Vietnamese */,+ "ja-JP" /* Japanese */,+ "ar-SA" /* Arabic */,+ "tr-TR" /* Turkish */,+ "cs-CZ" /* Czech */,+ "el-GR" /* Greek */,+] as const;++/** The type of {@link supportedLocales}. */+export type SupportedLocale = (typeof supportedLocales)[number];++const defaultLocale: SupportedLocale = "en-US";++/**+ * Load translations and add custom formatters.+ *+ * Localization and related concerns (aka "internationalization", or "i18n") for+ * our apps is handled by i18n framework.+ *+ * In addition to the base i18next package, we use two of its plugins:+ *+ * - i18next-http-backend, for loading the JSON files containing the translations+ * at runtime, and+ *+ * - react-i18next, which adds React specific APIs+ *+ * This function also adds our custom formatters. They can be used within the+ * translated strings by using `{{val, formatterName}}`. For more details, see+ * https://www.i18next.com/translation-function/formatting.+ *+ * Our custom formatters:+ *+ * - "date": Formats an epoch microsecond value into a string containing the+ * year, month and day of the the date. For example, under "en-US" it'll+ * produce a string like "July 19, 2024".+ */+export const setupI18n = async () => {+ const localeString = localStorage.getItem("locale") ?? undefined;+ const locale = closestSupportedLocale(localeString);++ // https://www.i18next.com/overview/api+ await i18n+ // i18next-resources-to-backend: Use webpack to bundle translation, but+ // still fetch them lazily using a dynamic import.+ //+ // The benefit of this is that, unlike the http backend that uses files+ // from the public folder, these JSON files are content hash named and+ // eminently cacheable.+ //+ // https://github.com/i18next/i18next-resources-to-backend+ .use(+ resourcesToBackend(+ (language: string, namespace: string) =>+ import(+ `../../../../packages/base/locales/${language}/${namespace}.json`+ ),+ ),+ )+ // react-i18next: React support+ // Pass the i18n instance to react-i18next.+ .use(initReactI18next)+ // Initialize i18next+ // Option docs: https://www.i18next.com/overview/configuration-options+ .init({+ debug: isDevBuild,+ // i18next calls it language, but it really is the locale+ lng: locale,+ // Tell i18next about the locales we support+ supportedLngs: supportedLocales,+ // Ask it to fetch only exact matches+ //+ // By default, if the lng was set to, say, en-GB, i18n would make+ // network requests for ["en-GB", "en", "dev"] (where dev is the+ // default fallback). By setting `load` to "currentOnly", we ask+ // i18next to only try and fetch "en-GB" (i.e. the exact match).+ load: "currentOnly",+ // Disallow empty strings as valid translations.+ //+ // This way, empty strings will fallback to `fallbackLng`+ returnEmptyString: false,+ // The language to use if translation for a particular key in the+ // current `lng` is not available.+ fallbackLng: defaultLocale,+ interpolation: {+ escapeValue: false, // not needed for react as it escapes by default+ },+ react: {+ useSuspense: false,+ // Allow the following tags (without any attributes) to be used+ // in translations. Such keys can then be rendered using the+ // Trans component, but without otherwise needing any other+ // input from our side.+ //+ // https://react.i18next.com/latest/trans-component+ transKeepBasicHtmlNodesFor: ["br", "p", "strong", "code"],+ },+ });++ // To use this in a translation, interpolate as `{{val, date}}`.+ i18n.services.formatter?.addCached("date", (locale) => {+ // The "long" dateStyle:+ //+ // - Includes: year (y), long-month (MMMM), day (d)+ // - English pattern examples: MMMM d, y ("September 14, 1999")+ //+ const formatter = Intl.DateTimeFormat(locale, { dateStyle: "long" });+ // Value is an epoch microsecond so that we can directly pass the+ // timestamps we get from our API responses. The formatter expects+ // milliseconds, so divide by 1000.+ //+ // See [Note: Remote timestamps are epoch microseconds].+ return (val) => formatter.format(val / 1000);+ });+};++/**+ * Return the closest / best matching {@link SupportedLocale}.+ *+ * It takes as input a {@link savedLocaleString}, which denotes the user's+ * explicitly chosen preference (which we then persist in local storage).+ * Subsequently, we use this to (usually literally) return the supported locale+ * that it represents.+ *+ * If {@link savedLocaleString} is `undefined`, it tries to deduce the closest+ * {@link SupportedLocale} that matches the browser's locale.+ */+const closestSupportedLocale = (+ savedLocaleString?: string,+): SupportedLocale => {+ const ss = savedLocaleString;+ if (ss && includes(supportedLocales, ss)) return ss;++ for (const ls of getUserLocales()) {+ // Exact match+ if (ls && includes(supportedLocales, ls)) return ls;++ // Language match+ if (ls.startsWith("en")) {+ return "en-US";+ } else if (ls.startsWith("fr")) {+ return "fr-FR";+ } else if (ls.startsWith("de")) {+ return "de-DE";+ } else if (ls.startsWith("ca")) {+ return "ca-ES";+ } else if (ls.startsWith("zh")) {+ return "zh-CN";+ } else if (ls.startsWith("nl")) {+ return "nl-NL";+ } else if (ls.startsWith("es")) {+ return "es-ES";+ } else if (ls.startsWith("pt-BR")) {+ // We'll never get here (it'd already be an exact match), just kept+ // to keep this list consistent.+ return "pt-BR";+ } else if (ls.startsWith("pt")) {+ return "pt-PT";+ } else if (ls.startsWith("ru")) {+ return "ru-RU";+ } else if (ls.startsWith("pl")) {+ return "pl-PL";+ } else if (ls.startsWith("it")) {+ return "it-IT";+ } else if (ls.startsWith("lt")) {+ return "lt-LT";+ } else if (ls.startsWith("uk")) {+ return "uk-UA";+ } else if (ls.startsWith("vi")) {+ return "vi-VN";+ } else if (ls.startsWith("ja")) {+ return "ja-JP";+ } else if (ls.startsWith("ar")) {+ return "ar-SA";+ } else if (ls.startsWith("tr")) {+ return "tr-TR";+ } else if (ls.startsWith("cs")) {+ return "cs-CZ";+ } else if (ls.startsWith("el")) {+ return "el-GR";+ }+ }++ // Fallback+ return defaultLocale;+};++/**+ * Return the locale that is currently being used to show the app's UI.+ *+ * Note that this may be different from the user's locale. For example, the+ * browser might be set to en-GB, but since we don't support that specific+ * variant of English, this value will be (say) en-US.+ */+export const getLocaleInUse = (): SupportedLocale => {+ const locale = i18n.resolvedLanguage;+ if (locale && includes(supportedLocales, locale)) {+ return locale;+ } else {+ // This shouldn't have happened. Log an error to attract attention.+ log.error(+ `Expected the i18next locale to be one of the supported values, but instead found ${locale}`,+ );+ return defaultLocale;+ }+};++/**+ * Set the locale that should be used to show the app's UI.+ *+ * This updates both the i18next state, and also the corresponding user+ * preference that is stored in local storage.+ */+export const setLocaleInUse = async (locale: SupportedLocale) => {+ localStorage.setItem("locale", locale);+ return i18n.changeLanguage(locale);+};++let _numberFormat: Intl.NumberFormat | undefined;++/**+ * Lazily created, cached, instance of NumberFormat used by+ * {@link formattedNumber}.+ *+ * See: [Note: Changing locale causes a full reload].+ */+const numberFormat = () =>+ (_numberFormat ??= new Intl.NumberFormat(i18n.language));++/**+ * Return the given {@link value} formatted for the current language and locale.+ *+ * In most cases, when a number needs to be displayed, it can be formatted as+ * part of the surrounding string using the {{count, number}} interpolation.+ * However, in some rare cases, we need to format a standalone number. For such+ * scenarios, this function can be used.+ */+export const formattedNumber = (value: number) => numberFormat().format(value);++let _listJoinFormat: Intl.ListFormat | undefined;++/**+ * Lazily created, cached, instance of NumberFormat used by+ * {@link formattedListJoin}.+ *+ * See: [Note: Changing locale causes a full reload].+ */+const listJoinFormat = () =>+ (_listJoinFormat ??= new Intl.ListFormat(i18n.language, {+ style: "narrow",+ }));++/**+ * Return the given {@link items} joined together into a single string using an+ * locale specific "comma like" separator.+ *+ * Usually this will just use a comma (plus space) as the list item separator,+ * but depending on the locale it might use a different separator too.+ *+ * e.g. ["Foo", "Bar"] becomes "Foo, Bar" in "en-US" and "Foo、Bar" in "zh".+ */+export const formattedListJoin = (value: string[]) =>+ listJoinFormat().format(value);++/**+ * A no-op marker for strings that, for various reasons, pending addition to the+ * translation dataset.+ *+ * This function does nothing, it just returns back the passed it string+ * verbatim. It is only kept as a way for us to keep track of strings which+ * we've not yet added to the list of strings that should be translated (e.g.+ * perhaps we're awaiting feedback on the copy).+ *+ * It is the sibling of the {@link t} function provided by i18next.+ *+ * See also: {@link ut}.+ */+export const pt = (s: string) => s;++/**+ * A no-op marker for strings that, for various reasons, are not translated.+ *+ * This function does nothing, it just returns back the passed it string+ * verbatim. It is only kept as a way for us to keep track of strings that are+ * not translated (and for some reason, are currently not meant to be), but+ * still are user visible.+ *+ * It is the sibling of the {@link t} function provided by i18next.+ *+ * See also: {@link pt}.+ */+export const ut = (s: string) => s;diff --git a/web/apps/albums/vendor/ente-base/id-worker.ts b/web/apps/albums/vendor/ente-base/id-worker.tsnew file mode 100644index 0000000000..593e2d236e--- /dev/null+++ b/web/apps/albums/vendor/ente-base/id-worker.ts@@ -0,0 +1,17 @@+import { customAlphabet } from "nanoid/non-secure";+import { alphabet } from "./id";++const nanoid = customAlphabet(alphabet, 22);++/**+ * This is a variant of the regular {@link newID} that can be used in web+ * workers.+ *+ * Web workers don't have access to a secure random generator, so we need to use+ * the non-secure variant.+ * https://github.com/ai/nanoid?tab=readme-ov-file#web-workers+ *+ * For many of our use cases, where we're not using these IDs for cryptographic+ * operations, this is okay. We also have an increased alphabet length.+ */+export const newNonSecureID = (prefix: string) => prefix + nanoid();diff --git a/web/apps/albums/vendor/ente-base/id.ts b/web/apps/albums/vendor/ente-base/id.tsnew file mode 100644index 0000000000..025d4344e0--- /dev/null+++ b/web/apps/albums/vendor/ente-base/id.ts@@ -0,0 +1,24 @@+import { customAlphabet } from "nanoid";++/**+ * Remove _ and - from the default set to have better looking IDs that can also+ * be selected in the editor quickly ("-" prevents this), and which we can+ * prefix unambiguously ("_" is used for that).+ *+ * To compensate, increase length from the default of 21 to 22.+ *+ * To play around with these, use https://zelark.github.io/nano-id-cc/+ */+export const alphabet =+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";++const nanoid = customAlphabet(alphabet, 22);++/**+ * Generate a new random identifier with the given prefix.+ *+ * Internally this uses [nanoids](https://github.com/ai/nanoid).+ *+ * See {@link newNonSecureID} for a variant that can be used in web workers.+ */+export const newID = (prefix: string) => prefix + nanoid();diff --git a/web/apps/albums/vendor/ente-base/kv.ts b/web/apps/albums/vendor/ente-base/kv.tsnew file mode 100644index 0000000000..3a05e6ffb1--- /dev/null+++ b/web/apps/albums/vendor/ente-base/kv.ts@@ -0,0 +1,186 @@+import { deleteDB, openDB, type DBSchema } from "idb";+import log from "./log";++/**+ * Key value store schema.+ *+ * [Note: KV DB]+ *+ * The use IndexedDB to store arbitrary key-value pairs. The functional+ * motivation is to allow these to also be accessed from web workers (local+ * storage is limited to the main thread).+ *+ * The "kv" database consists of one object store, "kv". Keys are strings.+ * Values can be arbitrary JSON objects.+ *+ * [Note: Avoiding IndexedDB flakiness by avoiding indexes]+ *+ * Sporadically, rarely, but definitely, we ran into issues with IndexedDB+ * losing data. e.g. saves from the ML web worker would complete successfully,+ * but the saves would not reflect on the main thread, and that data would just+ * get lost when the app would refresh.+ *+ * I'm not sure where the problem lay - in our own code, in the library that we+ * are using (idb), within IndexedDB itself, or in Electron/Chrome's+ * implementation of it (these cases all came up in the context of the ML code+ * that only ran in our desktop app).+ *+ * A piece of advice I randomly ran across on the internet was to keep it very+ * simple, and avoid all indexes. I also recalled that we did not see such+ * issues with our older (but now unmaintained) library, localforage, which also+ * doesn't use any indexes, and just has a flat single-store schema.+ *+ * So this may be superstition, but for now the approach I'm taking is to use+ * IndexedDB as a key value store only.+ */+interface KVDBSchema extends DBSchema {+ kv: {+ key: string;+ /**+ * Typescript doesn't have a native JSON type, so this needs to be+ * unknown+ */+ value: unknown;+ };+}++/**+ * A lazily-created, cached promise for KV DB.+ *+ * [Note: Caching IDB instances in separate execution contexts]+ *+ * We open the database once (on access), and thereafter save and reuse this+ * promise each time something wants to connect to it.+ *+ * This promise can subsequently get cleared if we need to relinquish our+ * connection (e.g. if another client wants to open the face DB with a newer+ * version of the schema).+ *+ * It can also get cleared on logout. In all such cases, it'll automatically get+ * recreated on next access.+ *+ * Note that this is module specific state, so each execution context (main+ * thread, web worker) that calls the functions in this module will its own+ * promise to the database. To ensure that all connections get torn down+ * correctly, we need to perform the following logout sequence:+ *+ * 1. Terminate all the workers which might have one of the instances in memory.+ * This closes their connections.+ *+ * 2. Delete the database on the main thread.+ */+let _kvDB: ReturnType<typeof openKVDB> | undefined;++const openKVDB = async () => {+ const db = await openDB<KVDBSchema>("kv", 1, {+ upgrade(db) {+ db.createObjectStore("kv");+ },+ blocking() {+ log.info(+ "Another client is attempting to open a new version of KV DB",+ );+ db.close();+ _kvDB = undefined;+ },+ blocked() {+ log.warn(+ "Waiting for an existing client to close their connection so that we can update the KV DB version",+ );+ },+ terminated() {+ log.warn("Our connection to KV DB was unexpectedly terminated");+ _kvDB = undefined;+ },+ });++ return db;+};++/**+ * @returns a lazily created, cached connection to the KV DB.+ */+const kvDB = () => (_kvDB ??= openKVDB());++/**+ * Clear all key values stored in the KV db.+ *+ * This is meant to be called during logout in the main thread.+ */+export const clearKVDB = async () => {+ try {+ if (_kvDB) (await _kvDB).close();+ } catch (e) {+ log.warn("Ignoring error when trying to close KV DB", e);+ }+ _kvDB = undefined;++ return deleteDB("kv", {+ blocked() {+ log.warn(+ "Waiting for an existing client to close their connection so that we can delete the KV DB",+ );+ },+ });+};++/**+ * Return the string value stored corresponding to {@link key}, or `undefined`+ * if there is no such entry.+ *+ * Typescript doesn't have a native JSON type, so the return value is type as an+ * `unknown`. For primitive types, you can avoid casting by using the+ * {@link getKVS} (string), {@link getKVN} (number) or {@link getKVB} (boolean)+ * methods that do an additional runtime check of the type.+ */+export const getKV = async (key: string) => {+ const db = await kvDB();+ return db.get("kv", key);+};++const _getKV = async <T extends string | number | boolean>(+ key: string,+ type: string,+): Promise<T | undefined> => {+ const db = await kvDB();+ const v = await db.get("kv", key);+ if (v === undefined) return undefined;+ if (typeof v != type)+ throw new Error(+ // This is just an error message, it is fine if stringification+ // produces nothing useful always, it might too in some cases.+ //+ // eslint-disable-next-line @typescript-eslint/no-base-to-string+ `Expected the value corresponding to key ${key} to be a ${type}, but instead got ${String(v)}`,+ );+ return v as T;+};++/** String variant of {@link getKV}. */+export const getKVS = async (key: string) => _getKV<string>(key, "string");++/** Numeric variant of {@link getKV}. */+export const getKVN = async (key: string) => _getKV<number>(key, "number");++/** Boolean variant of {@link getKV} */+export const getKVB = async (key: string) => _getKV<boolean>(key, "boolean");++/**+ * Save the given {@link value} corresponding to {@link key}, overwriting any+ * existing value.+ *+ * @param value Any arbitrary JSON object. Typescript doesn't have a native JSON+ * type, so this is typed as a unknown+ */+export const setKV = async (key: string, value: unknown) => {+ const db = await kvDB();+ await db.put("kv", value, key);+};++/**+ * Remove the entry corresponding to {@link key} (if any).+ */+export const removeKV = async (key: string) => {+ const db = await kvDB();+ await db.delete("kv", key);+};diff --git a/web/apps/albums/vendor/ente-base/log-web.ts b/web/apps/albums/vendor/ente-base/log-web.tsnew file mode 100644index 0000000000..a87f8ccfc1--- /dev/null+++ b/web/apps/albums/vendor/ente-base/log-web.ts@@ -0,0 +1,151 @@+import { isDevBuild } from "ente-base/env";+import log from "ente-base/log";+import { appName, appNames } from "./app";++/**+ * Log a standard startup banner.+ *+ * This helps us identify app starts and other environment details in the logs.+ *+ * @param userID The uid for the currently logged in user, if any.+ */+export const logStartupBanner = (userID?: number) => {+ // Log a warning if appName isn't what it claims to be. See the+ // documentation of `appName` for why this is needed.+ if (!appNames.includes(appName)) {+ log.warn(+ `App name "${appName}" is not one of the known app names: ${JSON.stringify(appNames)}`,+ );+ }++ const sha = process.env.gitSHA;+ const buildID = isDevBuild ? "dev " : sha ? `git ${sha} ` : "";+ log.info(`Starting ente-${appName}-web ${buildID}uid ${userID ?? 0}`);+};++/**+ * Attach handlers to log any unhandled exceptions and promise rejections.+ *+ * @param attach If true, attach handlers, and if false, remove them. This+ * allows us to use this in a React hook that cleans up after itself.+ */+export const logUnhandledErrorsAndRejections = (attach: boolean) => {+ const handleError = (event: ErrorEvent) => {+ // [Note: Spurious media chrome resize observer errors]+ //+ // When attaching media chrome controls to the DOM, we get an (AFAICT)+ // spurious error in the log. Ignore it. FWIW, the media control tests+ // themselves do the same.+ // https://github.com/muxinc/elements/blob/f602519f544509f15add8fcc8cbbf7379843dcd3/packages/mux-player/test/player.test.js#L6-L12C5+ if (+ event.message ==+ "ResizeObserver loop completed with undelivered notifications."+ ) {+ return;+ }++ log.error("Unhandled error", event.error ?? event.message);+ };++ const handleUnhandledRejection = (event: PromiseRejectionEvent) => {+ log.error("Unhandled promise rejection", event.reason);+ };++ if (attach) {+ window.addEventListener("error", handleError);+ window.addEventListener("unhandledrejection", handleUnhandledRejection);+ } else {+ window.removeEventListener("error", handleError);+ window.removeEventListener(+ "unhandledrejection",+ handleUnhandledRejection,+ );+ }+};++/**+ * Attach handlers to log any unhandled exceptions and promise rejections in web+ * workers.+ *+ * This is a variant of {@link logUnhandledErrorsAndRejections} that works in+ * web workers. It should be called at the top level of the main worker script.+ *+ * Note: When I tested this, attaching the onerror handler to the worker outside+ * the worker (e.g. when creating it in comlink-worker.ts) worked, but attaching+ * the "unhandledrejection" event there did not work. Attaching them to `self`+ * (the {@link WorkerGlobal}) worked.+ */+export const logUnhandledErrorsAndRejectionsInWorker = () => {+ const handleError = (event: ErrorEvent) => {+ log.error("Unhandled error", event.error);+ };++ const handleUnhandledRejection = (event: PromiseRejectionEvent) => {+ log.error("Unhandled promise rejection", event.reason);+ };++ self.addEventListener("error", handleError);+ self.addEventListener("unhandledrejection", handleUnhandledRejection);+};++interface LogEntry {+ timestamp: number;+ logLine: string;+}++const lsKey = "logs";++/**+ * Record {@link message} in a persistent log storage.+ *+ * These strings, alongwith associated timestamps, get added to a small ring+ * buffer, whose contents can be later be retrieved by using {@link savedLogs}.+ *+ * This ring buffer is persisted in the browser's local storage.+ */+export const logToDisk = (message: string) => {+ const maxCount = 1000;+ const log: LogEntry = { logLine: message, timestamp: Date.now() };+ try {+ const logs = logEntries();+ if (logs.length > maxCount) {+ logs.slice(logs.length - maxCount);+ }+ logs.push(log);+ localStorage.setItem(lsKey, JSON.stringify({ logs }));+ } catch (e) {+ console.error("Failed to persist log", e);+ if (e instanceof Error && e.name == "QuotaExceededError") {+ localStorage.removeItem(lsKey);+ }+ }+};++const logEntries = (): unknown[] => {+ const s = localStorage.getItem("logs");+ if (!s) return [];+ const o: unknown = JSON.parse(s);+ if (!(o && typeof o == "object" && "logs" in o && Array.isArray(o.logs))) {+ console.error("Unexpected log entries obtained from local storage", o);+ return [];+ }+ return o.logs;+};++/**+ * Return a string containing all recently saved log messages.+ *+ * @see {@link persistLog}.+ */+export const savedLogs = () => logEntries().map(formatEntry).join("\n");++const formatEntry = (e: unknown) => {+ if (e && typeof e == "object" && "timestamp" in e && "logLine" in e) {+ const timestamp = e.timestamp;+ const logLine = e.logLine;+ if (typeof timestamp == "number" && typeof logLine == "string") {+ return `[${new Date(timestamp).toISOString()}] ${logLine}`;+ }+ }+ return String(e);+};diff --git a/web/apps/albums/vendor/ente-base/log.ts b/web/apps/albums/vendor/ente-base/log.tsnew file mode 100644index 0000000000..cc4de0068b--- /dev/null+++ b/web/apps/albums/vendor/ente-base/log.ts@@ -0,0 +1,174 @@+import { inWorker } from "ente-base/env";+import { isDevBuild } from "./env";+import { logToDisk as webLogToDisk } from "./log-web";+import { workerBridge } from "./worker/worker-bridge";++/**+ * Whether logs go to disk or are always emitted to the console.+ */+let shouldLogToDisk = true;++/**+ * By default, logs get saved into a ring buffer in the browser's local storage.+ * However, in some contexts, e.g. when we're running as the cast app, there is+ * no mechanism for the user to retrieve these logs. So this function exists as+ * a way to disable the on disk logging and always use the console.+ */+export const disableDiskLogs = () => (shouldLogToDisk = false);++/**+ * Write a {@link message} to the on-disk log.+ *+ * This is used by the renderer process (via the contextBridge) to add entries+ * in the log that is saved on disk.+ */+export const logToDisk = (message: string) => {+ const electron = globalThis.electron;+ if (electron) electron.logToDisk(message);+ else if (inWorker()) workerLogToDisk(message);+ else webLogToDisk(message);+};++const workerLogToDisk = (message: string) => {+ workerBridge!.logToDisk(message).catch((e: unknown) => {+ console.error(+ "Failed to log a message from worker",+ e,+ "\nThe message was",+ message,+ );+ });+};++const messageWithError = (message: string, e?: unknown) => {+ if (!e) return message;++ let es: string;+ if (e instanceof Error) {+ // In practice, we expect ourselves to be called with Error objects, so+ // this is the happy path so to say.+ es = `${e.name}: ${e.message}`;+ const st = e.stack;+ if (st) {+ // On V8 (as of 2024), the stack trace begins by repeating the error's+ // name and message, trim that off.+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack+ es = st.startsWith(es)+ ? es.concat(st.slice(es.length)) /* retain the '\n' */+ : [es, st].join("\n");+ }+ } else {+ // For the rest rare cases, use the default string serialization of e.+ // eslint-disable-next-line @typescript-eslint/no-base-to-string+ es = String(e);+ }++ return `${message}: ${es}`;+};++const logError = (message: unknown, e?: unknown) => {+ const m =+ typeof message == "string"+ ? `[error] ${messageWithError(message, e)}`+ : `[error] ${messageWithError("Error", message)}`;+ console.error(m);+ if (shouldLogToDisk) logToDisk(m);+};++const logWarn = (message: string, e?: unknown) => {+ const m = `[warn] ${messageWithError(message, e)}`;+ console.error(m);+ if (shouldLogToDisk) logToDisk(m);+};++const logInfo = (...params: unknown[]) => {+ const message = params+ .map((p) => (typeof p == "string" ? p : JSON.stringify(p)))+ .join(" ");+ const m = `[info] ${message}`;+ if (isDevBuild || !shouldLogToDisk) console.log(m);+ if (shouldLogToDisk) logToDisk(m);+};++const logDebug = (param: () => unknown) => {+ if (isDevBuild) {+ const p = param();+ // Transform+ // log.debug(() => ["tag", {x: y}])+ // =>+ // console.log("[debug] tag", {x: y})+ if (Array.isArray(p)) {+ // tseslint is not happy with us for destructuring any, but this is+ // non-production dev build only code, so silence it and go ahead.+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ const [tag, ...rest] = p;+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument+ console.log(`[debug] ${tag}`, ...rest);+ } else {+ /* Let console.log serialize it */+ console.log("[debug]", p);+ }+ }+};++/**+ * Ente's logger.+ *+ * This is an object that provides functions to log at the corresponding levels:+ * error, warn, info or debug.+ *+ * Whenever we need to save a log message to disk,+ *+ * - When running under electron these messages are saved to the log maintained+ * by the electron app we're running under.+ *+ * - Otherwise such messages are written to a ring buffer in local storage.+ */+export default {+ /**+ * Log an error message with an optional associated error object.+ *+ * {@link e} is generally expected to be an `instanceof Error` but it can be+ * any arbitrary object that we obtain, say, when in a try-catch handler (in+ * JavaScript any arbitrary value can be thrown).+ *+ * If only one argument is specified, and it is not a string, then it is+ * taken as the error to be printed, paired with a generic message.+ *+ * The log is written to disk and printed to the browser console.+ */+ error: logError,+ /**+ * Sibling of {@link error}, with the same parameters and behaviour, except+ * it gets prefixed with a warning instead of an error tag.+ */+ warn: logWarn,+ /**+ * Log a message.+ *+ * This is meant as a replacement of {@link console.log}, and takes an+ * arbitrary number of arbitrary parameters that it then serializes.+ *+ * The log is written to disk. However, if logging to disk is disabled by+ * using {@link disableDiskLogs}, then the log is printed to the console.+ *+ * In development builds, the log is always printed to the browser console.+ */+ info: logInfo,+ /**+ * Log a debug message.+ *+ * To avoid running unnecessary code in release builds, this takes a+ * function to call to get the log message instead of directly taking the+ * message. The provided function will only be called in development builds.+ *+ * The function can return an arbitrary value which is serialized before+ * being logged. As a special case, arrays are spread, which allows one to+ * write `log.debug(() => ["tag", {x: y}])` and have that be printed as if+ * it were `console.log("[debug] tag", {x: y})`.+ *+ * This log is NOT written to disk. It is printed to the browser console,+ * but only in development builds.+ */+ debug: logDebug,+};diff --git a/web/apps/albums/vendor/ente-base/origins.ts b/web/apps/albums/vendor/ente-base/origins.tsnew file mode 100644index 0000000000..45877a620a--- /dev/null+++ b/web/apps/albums/vendor/ente-base/origins.ts@@ -0,0 +1,132 @@+import { getKVS } from "ente-base/kv";++/**+ * Return the origin (scheme, host, port triple) that should be used for making+ * API requests to museum.+ *+ * This defaults "https://api.ente.io", Ente's production API servers. but can+ * be overridden when self hosting or developing (see {@link customAPIOrigin}).+ */+export const apiOrigin = async () =>+ (await customAPIOrigin()) ?? "https://api.ente.io";++/**+ * A convenience function to construct an endpoint in a one-liner.+ *+ * This avoids us having to create a temporary variable or otherwise complicate+ * the call sites since async functions cannot be used inside template literals.+ *+ * @param path The URL path usually, but can be anything that needs to be+ * suffixed to the origin. It must begin with a "/".+ *+ * @param queryParams An optional object containing query params. This is+ * appended to the generated URL after funneling it through+ * {@link URLSearchParams}. Each value can be a `string` or `number` or+ * `boolean` - all of which are converted to `string`s by using `toString`+ *+ * > The boolean stringification yields "true" or "false".+ *+ * @returns path prefixed by {@link apiOrigin}.+ */+export const apiURL = async (+ path: string,+ queryParams?: Record<string, string | number | boolean>,+) => {+ let url = (await apiOrigin()) + path;+ if (queryParams) {+ const stringQP = Object.fromEntries(+ Object.entries(queryParams).map(([k, v]) => [k, v.toString()]),+ );+ const params = new URLSearchParams(stringQP);+ url = `${url}?${params.toString()}`;+ }+ return url;+};++/**+ * Return the overridden API origin, if one is defined by either (in priority+ * order):+ *+ * - Setting the custom server on the landing page (See: [Note: Configuring+ * custom server]); or by+ *+ * - Setting the `NEXT_PUBLIC_ENTE_ENDPOINT` environment variable.+ *+ * Otherwise return undefined.+ */+export const customAPIOrigin = async () =>+ (await getKVS("apiOrigin")) ??+ process.env.NEXT_PUBLIC_ENTE_ENDPOINT ??+ undefined;++/**+ * A convenience wrapper over {@link customAPIOrigin} that returns the only the+ * host part of the custom origin (if any).+ *+ * This is useful in places where we indicate the custom origin in the UI.+ */+export const customAPIHost = async () => {+ const origin = await customAPIOrigin();+ return origin ? new URL(origin).host : undefined;+};++/**+ * Return the origin that should be used for uploading files.+ *+ * This defaults to `https://uploader.ente.io`, serviced by a Cloudflare worker+ * (see infra/workers/uploader). But if a {@link customAPIOrigin} is set then+ * this value is set to the {@link customAPIOrigin} itself, effectively+ * bypassing the Cloudflare worker for non-Ente deployments.+ */+export const uploaderOrigin = async () =>+ (await customAPIOrigin()) ?? "https://uploader.ente.io";++/**+ * A static build time constant that is `true` if {@link albumsAppOrigin} has+ * been customized.+ */+export const isCustomAlbumsAppOrigin =+ !!process.env.NEXT_PUBLIC_ENTE_ALBUMS_ENDPOINT;++/**+ * Return the origin that serves public albums.+ *+ * Defaults to our production instance, "https://albums.ente.io", but can be+ * overridden by setting the `NEXT_PUBLIC_ENTE_ALBUMS_ENDPOINT` environment+ * variable.+ */+export const albumsAppOrigin = () =>+ process.env.NEXT_PUBLIC_ENTE_ALBUMS_ENDPOINT ?? "https://albums.ente.io";++/**+ * Return true if this build is Ente's official public albums deployment.+ */+export const isOfficialAlbumsApp =+ !!process.env.NEXT_PUBLIC_ENTE_OFFICIAL_ALBUMS_APP;++/**+ * A static build time constant that is `true` if {@link shareAppOrigin} has+ * been customized.+ */+export const isCustomShareAppOrigin =+ !!process.env.NEXT_PUBLIC_ENTE_SHARE_ENDPOINT;++/**+ * Return the origin that serves public locker (share app).+ *+ * Defaults to our production instance, "https://share.ente.io", but can be+ * overridden by setting the `NEXT_PUBLIC_ENTE_SHARE_ENDPOINT` environment+ * variable.+ */+export const shareAppOrigin = (): string =>+ process.env.NEXT_PUBLIC_ENTE_SHARE_ENDPOINT ?? "https://share.ente.io";++/**+ * Return the origin that serves the photos app.+ *+ * Defaults to our production instance, "https://web.ente.io", but can be+ * overridden by setting the `NEXT_PUBLIC_ENTE_PHOTOS_ENDPOINT` environment+ * variable.+ */+export const photosAppOrigin = (): string =>+ process.env.NEXT_PUBLIC_ENTE_PHOTOS_ENDPOINT ?? "https://web.ente.io";diff --git a/web/apps/albums/vendor/ente-base/session.ts b/web/apps/albums/vendor/ente-base/session.tsnew file mode 100644index 0000000000..f93b4f9c7e--- /dev/null+++ b/web/apps/albums/vendor/ente-base/session.ts@@ -0,0 +1,197 @@+import { z } from "zod";+import { decryptBox, encryptBox, generateKey } from "./crypto";+import log from "./log";++/**+ * Remove all data stored in session storage (data tied to the browser tab).+ *+ * See `docs/storage.md` for more details about session storage. Currently, only+ * the following entries are stored in session storage:+ *+ * - "encryptionKey"+ * - "keyEncryptionKey" (transient)+ */+export const clearSessionStorage = () => sessionStorage.clear();++/**+ * Schema of JSON string value for the "encryptionKey" and "keyEncryptionKey"+ * keys strings stored in session storage.+ */+const SessionKeyData = z.object({+ encryptedData: z.string(),+ key: z.string(),+ nonce: z.string(),+});++type SessionKeyData = z.infer<typeof SessionKeyData>;++const sessionKeyData = async (keyData: string): Promise<SessionKeyData> => {+ const key = await generateKey();+ const box = await encryptBox(keyData, key);+ return { key, ...box };+};++/**+ * Return the user's decrypted master key (as a base64 string) from session+ * storage, or throw if the session storage does not have the master key (which+ * likely indicates that the user is not logged in).+ */+export const ensureMasterKeyFromSession = async () => {+ const key = await masterKeyFromSession();+ if (!key) throw new Error("Master key not found in session");+ return key;+};++/**+ * Return `true` if the user's encrypted master key is present in the session.+ *+ * Use {@link masterKeyFromSession} to get the actual master key after+ * decrypting it. This function is a similar but quicker check to verify if we+ * have credentials at hand or not, however it doesn't attempt to verify that+ * the key present in the session can actually be decrypted.+ */+export const haveMasterKeyInSession = () =>+ !!sessionStorage.getItem("encryptionKey");++/**+ * Return the decrypted user's master key (as a base64 string) from session+ * storage if they are logged in, otherwise return `undefined`.+ *+ * See also {@link ensureMasterKeyFromSession}, which is usually what we need.+ */+export const masterKeyFromSession = async () => {+ const value = sessionStorage.getItem("encryptionKey");+ if (!value) return undefined;++ const { encryptedData, key, nonce } = SessionKeyData.parse(+ JSON.parse(value),+ );+ return decryptBox({ encryptedData, nonce }, key);+};++/**+ * Save the user's encrypted master key in the session storage. If we're running+ * in the context of our desktop app, also save it in the OS safe storage.+ *+ * See: [Note: Safe storage and interactive KEK attributes]+ *+ * @param masterKey The user's master key (as a base64 encoded string).+ */+export const saveMasterKeyInSessionAndSafeStore = async (masterKey: string) => {+ await saveKeyInSessionStore("encryptionKey", masterKey);+ try {+ await globalThis.electron?.saveMasterKeyInSafeStorage(masterKey);+ } catch (e) {+ // [Note: Safe storage is best effort]+ //+ // The user might be running on an OS which does not provide secure+ // storage. Practically this is rare, but it can happen, especially on+ // Linux if the app is run in a desktop environment without libsecret.+ //+ // So intercept failures to read and write to safe storage, and+ // gracefully degrade to how the web app behaves (ask the user for their+ // password in each session).+ log.warn("Failed to save master key in safe storage", e);+ }+};++/**+ * Save the provided key in session storage.+ *+ * @param keyName The name of the key use for the session storage entry.+ *+ * @param keyData The base64 encoded bytes of the key.+ */+const saveKeyInSessionStore = async (keyName: string, keyData: string) => {+ sessionStorage.setItem(+ keyName,+ JSON.stringify(await sessionKeyData(keyData)),+ );+};++/**+ * If we're running in the context of the desktop app, then read the master key+ * from the OS safe storage and put it into the session storage (if it is not+ * already present there).+ *+ * [Note: Safe storage and interactive KEK attributes]+ *+ * In the electron app we have the option of using the OS's safe storage (if+ * available) to store the master key so that the user does not have to reenter+ * their password each time they open the app.+ *+ * Such an ability is not present on browsers currently, so we need to ask the+ * user for their password to derive the KEK for decrypting their master key+ * each time they open the app in a new time (See: [Note: Key encryption key]).+ *+ * However, the default KEK parameters are not suitable for such frequent+ * interactive usage. So for the user's convenience, we also derive an new (so+ * called "intermediate") KEK using parameters suitable for interactive usage.+ * This KEK is not saved to remote, it is only maintained locally.+ *+ * In either case, eventually we want the encrypted key to be available in the+ * session for decrypting the user's files etc. In the web case, the page where+ * the user reenters their password will put it there, while on desktop+ * (assuming the key has already been saved to the OS safe storage), this+ * {@link updateSessionFromElectronSafeStorageIfNeeded} function will do it.+ */+export const updateSessionFromElectronSafeStorageIfNeeded = async () => {+ const electron = globalThis.electron;+ if (!electron) return;++ if (haveMasterKeyInSession()) return;++ let masterKey: string | undefined;+ try {+ masterKey = await electron.masterKeyFromSafeStorage();+ } catch (e) {+ // See: [Note: Safe storage is best effort]+ log.warn("Failed to read master key from safe storage", e);+ }+ if (masterKey) {+ await saveKeyInSessionStore("encryptionKey", masterKey);+ }+};++/**+ * Save the user's encypted key encryption key ("key") in session store+ * temporarily, until we get back here after completing the second factor.+ *+ * See: [Note: Stashing KEK in session store]+ *+ * @param kek The user's key encryption key (as a base64 string).+ */+export const stashKeyEncryptionKeyInSessionStore = (kek: string) =>+ saveKeyInSessionStore("keyEncryptionKey", kek);++/**+ * Return the decrypted user's key encryption key ("KEK") from session storage+ * if present, otherwise return `undefined`.+ *+ * The key (if it was present) is also removed from session storage.+ *+ * @returns the previously stashed key (if any) as a base64 string.+ *+ * [Note: Stashing KEK in session store]+ *+ * During login, if the user has set a second factor (passkey or TOTP), then we+ * need to redirect them to the accounts app or TOTP page to verify the second+ * factor. This second factor verification happens after password verification,+ * but simply storing the decrypted KEK in-memory wouldn't work because the+ * second factor redirect can happen to a separate accounts app altogether.+ *+ * So instead, we stash the encrypted KEK in session store (using+ * {@link stashKeyEncryptionKeyInSessionStore}), and after redirect, retrieve it+ * (after clearing it) using {@link unstashKeyEncryptionKeyFromSession}.+ */+export const unstashKeyEncryptionKeyFromSession = async () => {+ const value = sessionStorage.getItem("keyEncryptionKey");+ if (!value) return undefined;++ sessionStorage.removeItem("keyEncryptionKey");++ const { encryptedData, key, nonce } = SessionKeyData.parse(+ JSON.parse(value),+ );+ return decryptBox({ encryptedData, nonce }, key);+};diff --git a/web/apps/albums/vendor/ente-base/token.ts b/web/apps/albums/vendor/ente-base/token.tsnew file mode 100644index 0000000000..109322b339--- /dev/null+++ b/web/apps/albums/vendor/ente-base/token.ts@@ -0,0 +1,42 @@+import { getKVS, removeKV, setKV } from "./kv";++/**+ * Return the user's auth token, or throw an error.+ *+ * The user's auth token can be retrieved using {@link savedAuthToken}. This+ * function is a wrapper which throws an error if the token is not found (which+ * should only happen if the user is not logged in).+ */+export const ensureAuthToken = async () => {+ const token = await savedAuthToken();+ if (!token) throw new Error("Not logged in");+ return token;+};++/**+ * Return the user's auth token, if available.+ *+ * The user's auth token is stored in KV DB using {@link saveAuthToken} during+ * the login / signup flow. This function returns that saved auth token.+ *+ * The underlying data is stored in IndexedDB, and can be accessed from web+ * workers.+ *+ * If your code is running in a context where the user is already expected to be+ * logged in, use {@link ensureAuthToken} instead.+ */+export const savedAuthToken = () => getKVS("token");++/**+ * Save the user's auth token in KV DB.+ *+ * This is the setter corresponding to {@link savedAuthToken}.+ */+export const saveAuthToken = (token: string) => setKV("token", token);++/**+ * Remove the user's auth token from KV DB.+ *+ * See {@link saveAuthToken}.+ */+export const removeAuthToken = () => removeKV("token");diff --git a/web/apps/albums/vendor/ente-base/types/index.ts b/web/apps/albums/vendor/ente-base/types/index.tsnew file mode 100644index 0000000000..10dc83fa67--- /dev/null+++ b/web/apps/albums/vendor/ente-base/types/index.ts@@ -0,0 +1,7 @@+/**+ * A location, represented as a (latitude, longitude) pair.+ */+export interface Location {+ latitude: number;+ longitude: number;+}diff --git a/web/apps/albums/vendor/ente-base/types/ipc.ts b/web/apps/albums/vendor/ente-base/types/ipc.tsnew file mode 100644index 0000000000..795ae3d239--- /dev/null+++ b/web/apps/albums/vendor/ente-base/types/ipc.ts@@ -0,0 +1,921 @@+// Following are types shared with the Electron process. This list is manually+// kept in sync with `desktop/src/types/ipc.ts`.+//+// See [Note: types.ts <-> preload.ts <-> ipc.ts]++/**+ * Native provider used for desktop app lock authentication.+ *+ * `touchid` means we can use the platform-native auth prompt.+ * `none` means no supported native provider is currently available.+ */+export type NativeDeviceLockProvider = "touchid" | "none";++/**+ * Why native device lock is unavailable on this machine/session.+ */+export type NativeDeviceLockUnavailableReason =+ | "unsupported-platform"+ | "touchid-not-enrolled"+ | "touchid-temporarily-unavailable"+ | "touchid-api-error";++/**+ * Capability metadata used by the renderer to decide whether to show and use+ * "Device lock" as an app-lock mode.+ */+export interface NativeDeviceLockCapability {+ /** True when native auth can be prompted right now. */+ available: boolean;+ /** Which native provider backs authentication (if available). */+ provider: NativeDeviceLockProvider;+ /** Present when unavailable, with a machine-readable reason. */+ reason?: NativeDeviceLockUnavailableReason;+}++/**+ * Persisted desktop app-lock configuration.+ *+ * This excludes the passphrase hash material, which continues to live in the+ * renderer KV DB.+ */+export interface PersistedAppLockConfig {+ enabled: boolean;+ lockType: "pin" | "password" | "device" | "none";+ autoLockTimeMs: number;+}++/**+ * Extra APIs provided by our Node.js layer when our code is running inside our+ * desktop (Electron) app.+ *+ * This list is manually kept in sync with `desktop/src/preload.ts`. In case of+ * a mismatch, the types may lie. See also: [Note: types.ts <-> preload.ts <->+ * ipc.ts]+ *+ * These extra objects and functions will only be available when our code is+ * running as the renderer process in Electron. These can be accessed by using+ * the `electron` property of the window (See @{link globalElectron} for a+ * systematic way of getting at that).+ */+export interface Electron {+ // - General++ /**+ * Return the version of the desktop app.+ *+ * The return value is of the form `v1.2.3`.+ */+ appVersion: () => Promise<string>;++ /**+ * Log the given {@link message} to the on-disk log file maintained by the+ * desktop app.+ *+ * Note: Unlike the other functions exposed over the Electron bridge,+ * logToDisk is fire-and-forget and does not return a promise.+ */+ logToDisk: (message: string) => void;++ /**+ * Open the given {@link dirPath} in the system's folder viewer.+ *+ * For example, on macOS this'll open {@link dirPath} in Finder.+ */+ openDirectory: (dirPath: string) => Promise<void>;++ /**+ * Open the app's log directory in the system's folder viewer.+ *+ * @see {@link openDirectory}+ */+ openLogDirectory: () => Promise<void>;++ /**+ * Ask the user to select a directory on their local file system, and return+ * it path.+ *+ * The returned path is guaranteed to use POSIX separators ('/').+ *+ * We don't strictly need IPC for this, we can use a hidden <input> element+ * and trigger its click for the same behaviour (as we do for the+ * `useFileInput` hook that we use for uploads). However, it's a bit+ * cumbersome, and we anyways will need to IPC to get back its full path, so+ * it is just convenient to expose this direct method.+ */+ selectDirectory: () => Promise<string | undefined>;++ /**+ * Return the file system path that this File object points to.+ *+ * The returned path will use POSIX separators (even on Windows).+ *+ * This method is a bit different from the other methods on the Electron+ * object in the sense that there is no actual IPC happening - the+ * implementation of this method is completely in the preload script. Thus+ * we can pass it an otherwise unserializable File object.+ *+ * Consequently, it is also _not_ async.+ */+ pathForFile: (file: File) => string;++ /**+ * Perform any logout related cleanup of native side state.+ */+ logout: () => Promise<void>;++ /**+ * Return the previously saved user's master key from the persistent safe+ * storage accessible to the desktop app.+ *+ * The key is returned as a base64 encoded string.+ *+ * If the key is not found, return `undefined`.+ *+ * See also: {@link saveMasterKeyInSafeStorage}.+ */+ masterKeyFromSafeStorage: () => Promise<string | undefined>;++ /**+ * Save the given {@link masterKey} (encoded as a base64 string) to the+ * persistent safe storage accessible to the desktop app.+ */+ saveMasterKeyInSafeStorage: (masterKey: string) => Promise<void>;++ /**+ * Return true when the desktop app can currently use OS safe storage.+ */+ isSafeStorageAvailable: () => Promise<boolean>;++ /**+ * Return the persisted desktop app-lock configuration from safe storage, if+ * any.+ */+ appLockConfigFromSafeStorage: () => Promise<+ PersistedAppLockConfig | undefined+ >;++ /**+ * Save the given desktop app-lock configuration to safe storage.+ */+ saveAppLockConfigInSafeStorage: (+ config: PersistedAppLockConfig,+ ) => Promise<void>;++ /**+ * Remove any persisted desktop app-lock configuration from safe storage.+ */+ clearAppLockConfigFromSafeStorage: () => Promise<void>;++ /**+ * Set or clear the callback {@link cb} to invoke whenever the app comes+ * into the foreground. More precisely, the callback gets invoked when the+ * main window gets focus.+ *+ * Setting a callback clears any previous callbacks.+ *+ * @param cb The function to call when the main window gets focus. Pass+ * `undefined` to clear the callback.+ */+ onMainWindowFocus: (cb: (() => void) | undefined) => void;++ /**+ * Set or clear the callback {@link cb} to invoke whenever the app goes to+ * the background. More precisely, the callback gets invoked when the main+ * window blurs and the app is no longer focused.+ *+ * Setting a callback clears any previous callbacks.+ *+ * @param cb The function to call when the app is backgrounded. Pass+ * `undefined` to clear the callback.+ */+ onMainWindowBlur: (cb: (() => void) | undefined) => void;++ /**+ * Set or clear the callback {@link cb} to invoke whenever the app gets+ * asked to open a deeplink that begins with "ente://". This allows the+ * Node.js layer to ask the renderer to handle deeplinks and redirect itself+ * to a new location if needed.+ *+ * In particular, this is necessary for handling passkey authentication.+ * See: [Note: Passkey verification in the desktop app]+ *+ * Setting a callback clears any previous callbacks.+ *+ * @param cb The function to call when the app gets asked to open a+ * "ente://" URL. The URL string (a.k.a. "deeplink") we were asked to open+ * is passed to the function verbatim.+ */+ onOpenEnteURL: (cb: ((url: string) => void) | undefined) => void;++ /**+ * Get the persisted version for the last shown changelog.+ *+ * See: [Note: Conditions for showing "What's new"]+ */+ lastShownChangelogVersion: () => Promise<number | undefined>;++ /**+ * Save the given {@link version} to disk as the version of the last shown+ * changelog.+ *+ * The value is saved to a store which is not cleared during logout.+ *+ * @see {@link lastShownChangelogVersion}+ */+ setLastShownChangelogVersion: (version: number) => Promise<void>;++ /**+ * Return true if the auto launch on system startup is enabled.+ */+ isAutoLaunchEnabled: () => Promise<boolean>;++ /**+ * Toggle the auto launch on system startup behaviour.+ *+ * @see {@link isAutoLaunchEnabled}+ */+ toggleAutoLaunch: () => Promise<void>;++ /**+ * Return native device lock capability details for the current machine.+ *+ * Includes whether native auth is available, provider metadata, and a+ * reason when unavailable.+ */+ getNativeDeviceLockCapability: () => Promise<NativeDeviceLockCapability>;++ /**+ * Prompt native device lock authentication.+ *+ * The {@link reason} can be shown by the OS in the native auth prompt.+ * Returns true on successful authentication.+ */+ promptDeviceLock: (reason: string) => Promise<boolean>;++ // - App update++ /**+ * Set or clear the callback {@link cb} to invoke whenever a new+ * (actionable) app update is available. This allows the Node.js layer to+ * ask the renderer to show an "Update available" dialog to the user.+ *+ * Setting a callback clears any previous callbacks.+ */+ onAppUpdateAvailable: (+ cb: ((update: AppUpdate) => void) | undefined,+ ) => void;++ /**+ * Restart the app to apply the latest available update.+ *+ * This is expected to be called in response to {@link onAppUpdateAvailable}+ * if the user so wishes.+ */+ updateAndRestart: () => void;++ /**+ * Mute update notifications for the given {@link version}. This allows us+ * to implement the "Install on next launch" functionality in response to+ * the {@link onAppUpdateAvailable} event.+ */+ updateOnNextRestart: (version: string) => void;++ /**+ * Skip the app update with the given {@link version}.+ *+ * This is expected to be called in response to {@link onAppUpdateAvailable}+ * if the user so wishes. It will remember this {@link version} as having+ * been marked as skipped so that we don't prompt the user again.+ */+ skipAppUpdate: (version: string) => void;++ // - FS++ /**+ * A subset of file system access APIs.+ *+ * The renderer process, being a web process, does not have full access to+ * the local file system apart from files explicitly dragged and dropped (or+ * selected by the user in a native file open dialog).+ *+ * The main process, however, has full fil system access (limited only be an+ * OS level sandbox on the entire process).+ *+ * When we're running in the desktop app, we want to better utilize the+ * local file system access to provide more integrated features to the user;+ * things that are not currently possible using web technologies. For+ * example, continuous exports to an arbitrary user chosen location on disk,+ * or watching some folders for changes and syncing them automatically.+ *+ * Towards this end, this fs object provides some generic file system access+ * functions that are needed for such features (in some cases, there are+ * other feature specific methods too in the top level electron object).+ */+ fs: {+ /** Return true if there is an item at the given {@link path}. */+ exists: (path: string) => Promise<boolean>;++ /**+ * Equivalent of `mkdir -p`.+ *+ * Create a directory at the given path if it does not already exist.+ * Any parent directories in the path that don't already exist will also+ * be created recursively, i.e. this command is analogous to an running+ * `mkdir -p`.+ */+ mkdirIfNeeded: (dirPath: string) => Promise<void>;++ /** Rename {@link oldPath} to {@link newPath} */+ rename: (oldPath: string, newPath: string) => Promise<void>;++ /**+ * Equivalent of `rmdir`.+ *+ * Delete the directory at the {@link path} if it is empty.+ */+ rmdir: (path: string) => Promise<void>;++ /**+ * Equivalent of `rm`.+ *+ * Delete the file at {@link path}.+ */+ rm: (path: string) => Promise<void>;++ /** Read the string contents of a file at {@link path}. */+ readTextFile: (path: string) => Promise<string>;++ /**+ * Write a string to a file, replacing the file if it already exists.+ *+ * @param path The path of the file.+ * @param contents The string contents to write.+ */+ writeFile: (path: string, contents: string) => Promise<void>;++ /**+ * A variant of {@link writeFile} that first writes the file to a backup+ * file, and then renames the backup file to the actual path. This both+ * makes the write atomic (as far as the node's fs.rename guarantees+ * atomicity), and also keeps the backup file around for recovery if+ * something goes wrong during the rename.+ *+ * This behaviour of this function is tailored around for writes to the+ * "export_status.json" during exports.+ */+ writeFileViaBackup: (path: string, contents: string) => Promise<void>;++ /**+ * Return true if there is an item at {@link dirPath}, and it is as+ * directory.+ */+ isDir: (dirPath: string) => Promise<boolean>;++ /**+ * Return the last modified time (integral epoch milliseconds) of the+ * file system entry at {@link path}.+ */+ statMtime: (path: string) => Promise<number>;++ /**+ * Return the paths of all the files under the given folder.+ *+ * This function walks the directory tree starting at {@link folderPath}+ * and returns a list of the absolute paths of all the files that exist+ * therein. It will recursively traverse into nested directories, and+ * return the absolute paths of the files there too.+ *+ * The returned paths are guaranteed to use POSIX separators ('/').+ */+ findFiles: (folderPath: string) => Promise<string[]>;+ };++ // - Conversion++ /**+ * Try to convert an arbitrary image into JPEG using native layer tools.+ *+ * The behaviour is OS dependent. On macOS we use the `sips` utility, while+ * on Linux and Windows we use a `vips` bundled with our desktop app.+ *+ * @param imageData The raw image data (the contents of the image file).+ *+ * @returns JPEG data of the converted image.+ */+ convertToJPEG: (imageData: Uint8Array) => Promise<Uint8Array>;++ /**+ * Generate a JPEG thumbnail for the given image.+ *+ * The behaviour is OS dependent. On macOS we use the `sips` utility, while+ * on Linux and Windows we use a `vips` bundled with our desktop app.+ *+ * @param pathOrZipItem The file whose thumbnail we want to generate. It can+ * be provided as raw image data (the contents of the image file), or the+ * path to the image file, or a tuple containing the path of the zip file+ * along with the name of an entry in it.+ *+ * @param maxDimension The maximum width or height of the generated+ * thumbnail.+ *+ * @param maxSize Maximum size (in bytes) of the generated thumbnail.+ *+ * @returns JPEG data of the generated thumbnail.+ */+ generateImageThumbnail: (+ pathOrZipItem: string | ZipItem,+ maxDimension: number,+ maxSize: number,+ ) => Promise<Uint8Array>;++ /**+ * Execute a FFmpeg {@link command} on the given {@link pathOrZipItem}.+ *+ * This executes the command using a FFmpeg executable we bundle with our+ * desktop app. We also have a Wasm FFmpeg implementation that we use when+ * running on the web, which has a sibling function with the same+ * parameters. See [Note:FFmpeg in Electron].+ *+ * @param command An array of strings, each representing one positional+ * parameter in the command to execute. Placeholders for the input, output+ * and ffmpeg's own path are replaced before executing the command+ * (respectively {@link inputPathPlaceholder},+ * {@link outputPathPlaceholder}, {@link ffmpegPathPlaceholder}).+ *+ * @param pathOrZipItem The path to the input file on the user's local disk,+ * or the path to a zip file on the user's disk and the name of an entry in+ * it. In the second case, the data gets serialized to a temporary file, and+ * then that path (or if it was already a path) gets substituted in the+ * FFmpeg {@link command} in lieu of {@link inputPathPlaceholder}.+ *+ * @param outputFileExtension The extension (without the dot, e.g. "jpeg")+ * to use for the output file that we ask FFmpeg to create in+ * {@param command}. While this file will eventually get deleted, and we'll+ * just return its contents, for some FFmpeg command the extension matters+ * (e.g. conversion to a JPEG fails if the extension is arbitrary).+ *+ * @returns The contents of the output file produced by the ffmpeg command+ * (specified as {@link outputPathPlaceholder} in {@link command}).+ */+ ffmpegExec: (+ command: FFmpegCommand,+ pathOrZipItem: string | ZipItem,+ outputFileExtension: string,+ ) => Promise<Uint8Array>;++ /**+ * Determine the duration (in seconds) of the video present at+ * {@link pathOrZipItem} using ffmpeg.+ *+ * This is a bespoke variant of {@link ffmpegExec} for the sole purpose of+ * retrieving the video duration.+ *+ * @param pathOrZipItem The input file whose duration we want to determine.+ * For more details, see the documentation of the {@link ffmpegExec}+ * parameter with the same name.+ *+ * @returns The duration (in seconds) of the video referred to by+ * {@link pathOrZipItem}.+ */+ ffmpegDetermineVideoDuration: (+ pathOrZipItem: string | ZipItem,+ ) => Promise<number>;++ // - Utility process++ /**+ * Trigger the creation of a new utility process of the given {@link type},+ * terminating the older ones (if any).+ *+ * This creates a new Node.js utility process, and sets things up so that we+ * can communicate directly with that utility process using a+ * {@link MessagePort} that gets posted on the "utilityProcessPort/<type>"+ * channel.+ *+ * The code running in the utility process is determined by the specific+ * value of {@link type}. Thus, att the other end of that port will be an+ * object that conforms to:+ *+ * - {@link ElectronMLWorker} interface, when type is "ml".+ *+ * For more details about the IPC flow, see: [Note: ML IPC].+ *+ * Note: For simplicity of implementation, we assume that there is at most+ * one outstanding call to {@link triggerCreateUtilityProcess} for a given+ * {@link type}.+ */+ triggerCreateUtilityProcess: (type: UtilityProcessType) => void;++ // - Watch++ /**+ * Interface with the file system watcher running in our Node.js layer.+ *+ * [Note: Folder vs Directory in the context of FolderWatch-es]+ *+ * A note on terminology: The word "folder" is used to the top level root+ * folder for which a {@link FolderWatch} has been added. This folder is+ * also in 1-1 correspondence to be a directory on the user's disk. It can+ * have other, nested directories too (which may or may not be getting+ * mapped to separate Ente collections), but we'll not refer to these nested+ * directories as folders - only the root of the tree, which the user+ * dragged/dropped or selected to set up the folder watch, will be referred+ * to as a folder when naming things.+ */+ watch: {+ /**+ * Return the list of folder watches, pruning non-existing directories.+ *+ * The list of folder paths (and auxiliary details) is persisted in the+ * Node.js layer. The implementation of this function goes through the+ * list, permanently removes any watches whose on-disk directory is no+ * longer present, and returns this pruned list of watches.+ */+ get: () => Promise<FolderWatch[]>;++ /**+ * Add a new folder watch for the given {@link folderPath}.+ *+ * This adds a new entry in the list of watches (persisting them on+ * disk), and also starts immediately observing for file system events+ * that happen within {@link folderPath}.+ *+ * @param collectionMapping Determines how nested directories (if any)+ * get mapped to Ente collections.+ *+ * @returns The updated list of watches.+ */+ add: (+ folderPath: string,+ collectionMapping: CollectionMapping,+ ) => Promise<FolderWatch[]>;++ /**+ * Remove the pre-existing watch for the given {@link folderPath}.+ *+ * Persist this removal, and also stop listening for file system events+ * that happen within the {@link folderPath}.+ *+ * @returns The updated list of watches.+ */+ remove: (folderPath: string) => Promise<FolderWatch[]>;++ /**+ * Update the list of synced files for the folder watch associated+ * with the given {@link folderPath}.+ */+ updateSyncedFiles: (+ syncedFiles: FolderWatch["syncedFiles"],+ folderPath: string,+ ) => Promise<void>;++ /**+ * Update the list of ignored file paths for the folder watch+ * associated with the given {@link folderPath}.+ */+ updateIgnoredFiles: (+ ignoredFiles: FolderWatch["ignoredFiles"],+ folderPath: string,+ ) => Promise<void>;++ /**+ * Register the function to invoke when a file is added in one of the+ * folders we are watching.+ *+ * The callback function is passed the path to the file that was added,+ * and the folder watch it was associated with.+ *+ * The path is guaranteed to use POSIX separators ('/').+ */+ onAddFile: (f: (path: string, watch: FolderWatch) => void) => void;++ /**+ * Register the function to invoke when a file is removed in one of the+ * folders we are watching.+ *+ * The callback function is passed the path to the file that was+ * removed, and the folder watch it was associated with.+ *+ * The path is guaranteed to use POSIX separators ('/').+ */+ onRemoveFile: (f: (path: string, watch: FolderWatch) => void) => void;++ /**+ * Register the function to invoke when a directory is removed in one of+ * the folders we are watching.+ *+ * The callback function is passed the path to the directory that was+ * removed, and the folder watch it was associated with.+ *+ * The path is guaranteed to use POSIX separators ('/').+ */+ onRemoveDir: (f: (path: string, watch: FolderWatch) => void) => void;+ };++ // - Upload++ /**+ * Get the list of files that are present in the given zip file.+ *+ * @param zipPath The path of the zip file on the user's local file system.+ *+ * @returns A list of (zipPath, entryName) tuples, one for each file in the+ * given zip. Directories are traversed recursively, but the directory+ * entries themselves will be excluded from the returned list. File entries+ * whose file name begins with a dot (i.e. "hidden" files) will also be+ * excluded.+ *+ * To read the contents of the files themselves, see [Note: IPC streams].+ */+ listZipItems: (zipPath: string) => Promise<ZipItem[]>;++ /**+ * Return the size in bytes of the file at the given path or of a particular+ * entry within a zip file.+ */+ pathOrZipItemSize: (pathOrZipItem: string | ZipItem) => Promise<number>;++ /**+ * Return any pending uploads that were previously enqueued but haven't yet+ * been completed.+ *+ * Return undefined if there are no such pending uploads.+ *+ * The state of pending uploads is persisted in the Node.js layer. Or app+ * start, we read in this data from the Node.js layer via this IPC method.+ * The Node.js code returns the persisted data after filtering out any files+ * that no longer exist on disk.+ */+ pendingUploads: () => Promise<PendingUploads | undefined>;++ /**+ * Set the state of pending uploads.+ *+ * - Typically, this would be called at the start of an upload.+ *+ * - Thereafter, as each item gets uploaded one by one, we'd call+ * {@link markUploadedFile} or {@link markUploadedZipItem}.+ *+ * - Finally, once the upload completes (or gets cancelled), we'd call+ * {@link clearPendingUploads} to complete the circle.+ */+ setPendingUploads: (pendingUploads: PendingUploads) => Promise<void>;++ /**+ * Mark the given files (specified by their disk paths) as having been+ * uploaded.+ *+ * @param {@link path} The path to the file system file which was uploaded.+ *+ * @param {@link associatedPath} The path file (if any) of the file+ * associated with the file which was uploaded. This will be present only in+ * the case of live photos, where this will be set to the path of the video+ * component of the live photo on disk.+ *+ * @returns The last modified time (epoch milliseconds) of the file at+ * {@link path}.+ */+ markUploadedFile: (+ path: string,+ associatedPath?: string,+ ) => Promise<number>;++ /**+ * Mark the given {@link ZipItem}s as having been uploaded.+ *+ * @param {@link item} The {@link ZipItem} which was uploaded.+ *+ * @param {@link associatedItem} An optional extra {@link ZipItem}+ * associated with the {@link item} which was uploaded. This will be present+ * only in case of live photos, where this'll be set to the {@link ZipItem}+ * representing the video component of the live photo on disk.+ *+ * @returns The last modified time (epoch milliseconds) of the zip file+ * containing {@link item}.+ */+ markUploadedZipItem: (+ item: ZipItem,+ associatedItem?: ZipItem,+ ) => Promise<number>;++ /**+ * Clear any pending uploads.+ *+ * This is also taken by the Node.js layer as a signal to clear any cached+ * state it has kept around to speed up the upload.+ */+ clearPendingUploads: () => Promise<void>;+}++export type UtilityProcessType = "ml";++/**+ * The shape of the object exposed by the Node.js utility process listening on+ * the other side message port that the web layer obtains by doing+ * {@link triggerCreateUtilityProcess} with type "ml".+ */+export interface ElectronMLWorker {+ /**+ * Return the last modified time (epoch milliseconds) for the file at the+ * given {@link path} on the user's file system.+ */+ fsStatMtime: (path: string) => Promise<number>;++ /**+ * Return a CLIP embedding of the given image.+ *+ * See: [Note: Natural language search using CLIP]+ *+ * The input is a opaque float32 array representing the image. The layout+ * and exact encoding of the input is specific to the runtime (ONNX) and the+ * ML model (a MobileCLIP variant) we use. In particular, the image+ * pre-processing happens within our model itself.+ *+ * @returns A CLIP embedding (an array of 512 floating point values).+ */+ computeCLIPImageEmbedding: (+ input: Uint8ClampedArray,+ inputShape: number[],+ ) => Promise<Float32Array>;++ /**+ * Return a CLIP embedding of the given image if we already have the model+ * downloaded and prepped. If the model is not available return `undefined`.+ *+ * This differs from the other sibling ML functions in that it doesn't wait+ * for the model download to finish. It does trigger a model download, but+ * then immediately returns `undefined`. At some future point, when the+ * model downloaded finishes, calls to this function will start returning+ * the result we seek.+ *+ * The reason for doing it in this asymmetric way is because CLIP text+ * embeddings are used as part of deducing user initiated search results,+ * and we don't want to block that interaction on a large network request.+ *+ * See: [Note: Natural language search using CLIP]+ *+ * @param text The string whose embedding we want to compute.+ *+ * @returns A CLIP embedding.+ */+ computeCLIPTextEmbeddingIfAvailable: (+ text: string,+ ) => Promise<Float32Array | undefined>;++ /**+ * Detect faces in the given image using YOLO.+ *+ * Both the input and output are opaque binary data whose internal structure+ * is specific to our implementation and the model (YOLO) we use.+ */+ detectFaces: (+ input: Uint8ClampedArray,+ inputShape: number[],+ ) => Promise<Float32Array>;++ /**+ * Return a MobileFaceNet embeddings for the given faces.+ *+ * Both the input and output are opaque binary data whose internal structure+ * is specific to our implementation and the model (MobileFaceNet) we use.+ */+ computeFaceEmbeddings: (input: Float32Array) => Promise<Float32Array>;+}++/**+ * Data passed across the IPC bridge when an app update is available.+ */+export interface AppUpdate {+ /** `true` if the user automatically update to this (new) version */+ autoUpdatable: boolean;+ /** The new version that is available */+ version: string;+}++/**+ * A top level folder that was selected by the user for watching.+ *+ * The user can set up multiple such watches. Each of these can in turn be+ * syncing multiple on disk folders to one or more Ente collections (depending+ * on the value of {@link collectionMapping}).+ *+ * This type is passed across the IPC boundary. It is persisted on the Node.js+ * side.+ */+export interface FolderWatch {+ /**+ * Specify if nested files should all be mapped to the same single root+ * collection, or if there should be a collection per directory that has+ * files. @see {@link CollectionMapping}.+ */+ collectionMapping: CollectionMapping;+ /**+ * The path to the (root) folder we are watching.+ */+ folderPath: string;+ /**+ * Files that have already been uploaded.+ */+ syncedFiles: FolderWatchSyncedFile[];+ /**+ * Files (paths) that should be ignored when uploading.+ */+ ignoredFiles: string[];+ /**+ * Whether the folder is currently accessible on disk.+ *+ * Folders on ejected external drives will have this set to false. This+ * property is not persisted and is computed each time the watch list is+ * fetched.+ */+ isAccessible?: boolean;+}++/**+ * The ways in which directories are mapped to collection.+ *+ * This comes into play when we have nested directories that we are trying to+ * upload or watch on the user's local file system.+ */+export type CollectionMapping =+ /** All files go into a single collection named after the root directory. */+ | "root"+ /** Each file goes to a collection named after its parent directory. */+ | "parent";++/**+ * An on-disk file that was synced as part of a folder watch.+ */+export interface FolderWatchSyncedFile {+ path: string;+ uploadedFileID: number;+ collectionID: number;+}++/**+ * A particular file within a zip file.+ *+ * When the user uploads a zip file, we create a "zip item" for each entry+ * within the zip file. Each such entry is a tuple containing the (path to a zip+ * file itself, and the name of an entry within it).+ *+ * The name of the entry is not just the file name, but rather is the full path+ * of the file within the zip. That is, each entry name uniquely identifies a+ * particular file within the given zip.+ *+ * When `entryName` is a path within a nested directory, it is guaranteed to use+ * the POSIX path separator ("/") since that is the path separator required by+ * the ZIP format itself+ *+ * > 4.4.17.1 The name of the file, with optional relative path.+ * >+ * > The path stored MUST NOT contain a drive or device letter, or a leading+ * > slash. All slashes MUST be forward slashes '/' as opposed to backwards+ * > slashes '\' for compatibility with Amiga and UNIX file systems etc. If+ * > input came from standard input, there is no file name field.+ * >+ * > https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT+ */+export type ZipItem = [zipPath: string, entryName: string];++/**+ * State about pending and in-progress uploads.+ *+ * When the user starts an upload, we remember the files they'd selected (or+ * drag-dropped) so that we can resume if they restart the app in before the+ * uploads have been completed. This state is kept on the Electron side, and+ * this object is the IPC intermediary.+ */+export interface PendingUploads {+ /**+ * The collection to which we're uploading, or the root collection.+ *+ * This is name of the collection (when uploading to a singular collection)+ * or the root collection (when uploading to separate * albums) to which we+ * these uploads are meant to go to. See {@link CollectionMapping}.+ *+ * It will not be set if we're just uploading standalone files.+ */+ collectionName?: string;+ /**+ * Paths of regular files that need to be uploaded.+ */+ filePaths: string[];+ /**+ * {@link ZipItem} (zip path and entry name) that need to be uploaded.+ */+ zipItems: ZipItem[];+}++/**+ * A command that we can ask FFmpeg to run for us.+ *+ * [Note: Alternative FFmpeg command for HDR videos]+ *+ * Usually, this is a single command (specified as an array of strings+ * containing the "words" of the command). However, we can also provide two+ * alternative commands - one to run when the input is (heuristically) detected+ * as a HDR video, and one otherwise.+ */+export type FFmpegCommand = string[] | { default: string[]; hdr: string[] };diff --git a/web/apps/albums/vendor/ente-base/utils/web.ts b/web/apps/albums/vendor/ente-base/utils/web.tsnew file mode 100644index 0000000000..f0120f4a35--- /dev/null+++ b/web/apps/albums/vendor/ente-base/utils/web.ts@@ -0,0 +1,34 @@+/**+ * Download the asset at the given {@link url} to a file on the user's download+ * folder by appending a temporary <a> element to the DOM.+ *+ * @param url The URL that we want to download. The URL is revoked after+ * initiating the download.+ *+ * @param fileName The name of downloaded file.+ *+ * See also {@link saveStringAsFile}.+ */+export const saveAsFileAndRevokeObjectURL = (url: string, fileName: string) => {+ const a = document.createElement("a");+ a.style.display = "none";+ a.href = url;+ a.download = fileName;+ document.body.appendChild(a);+ a.click();+ URL.revokeObjectURL(url);+ a.remove();+};++/**+ * Save the given string {@link s} as a file in the user's download folder.+ *+ * @param s The string to save.+ *+ * @param fileName The name of the file that gets saved.+ */+export const saveStringAsFile = (s: string, fileName: string) => {+ const file = new Blob([s], { type: "text/plain" });+ const fileURL = URL.createObjectURL(file);+ saveAsFileAndRevokeObjectURL(fileURL, fileName);+};diff --git a/web/apps/albums/vendor/ente-base/worker/comlink-worker.ts b/web/apps/albums/vendor/ente-base/worker/comlink-worker.tsnew file mode 100644index 0000000000..44169c2e43--- /dev/null+++ b/web/apps/albums/vendor/ente-base/worker/comlink-worker.ts@@ -0,0 +1,74 @@+import { expose, wrap, type Remote } from "comlink";+import { ensureElectron } from "ente-base/electron";+import log, { logToDisk } from "ente-base/log";++/**+ * A minimal wrapper for a web {@link Worker}, proxying a class of type T.+ *+ * `comlink` is a library that simplifies working with web workers by+ * transparently proxying objects across the boundary instead of us needing to+ * work directly with the raw postMessage interface.+ *+ * This class is a thin wrapper over a common usage pattern of comlink. It takes+ * a web worker ({@link Worker}) that is expected to have {@link expose}-ed a+ * class of type T. It then makes available the main thread handle to this class+ * as the {@link remote} property.+ *+ * It also exposes an object of type {@link WorkerBridge} _to_ the code running+ * inside the web worker.+ *+ * It all gets a bit confusing sometimes, so here is a legend of the parties+ * involved:+ *+ * - ComlinkWorker (wraps the web worker)+ * - Web `Worker` (exposes class T)+ * - ComlinkWorker.remote (the exposed class T running inside the web worker)+ */+export class ComlinkWorker<T extends new () => InstanceType<T>> {+ /** The class (T) exposed by the web worker */+ public remote: Promise<Remote<InstanceType<T>>>;+ /** The web worker */+ public worker: Worker;+ /** An arbitrary name associated with this ComlinkWorker for debugging. */+ private name: string;++ constructor(name: string, worker: Worker) {+ this.name = name;+ this.worker = worker;++ worker.onerror = (event) => {+ log.error(+ `Got error event from worker: ${JSON.stringify({ event, name })}`,+ );+ };+ log.debug(() => `Created ${name} web worker`);+ const comlink = wrap<T>(worker);+ this.remote = new comlink() as Promise<Remote<InstanceType<T>>>;+ expose(workerBridge, worker);+ }++ public terminate() {+ this.worker.terminate();+ log.debug(() => `Terminated ${this.name} web worker`);+ }+}++/**+ * A set of utility functions that we expose to all web workers that we create.+ *+ * Inside the worker's code, this can be accessed by using the sibling+ * `workerBridge` object after importing it from `worker-bridge.ts`.+ *+ * Not all workers need access to all these functions, and this can indeed be+ * done in a more fine-grained, per-worker, manner if needed. For now, since it+ * is just a couple, we just inject them all to all workers.+ */+const workerBridge = {+ // Needed by all workers (likely, but not necessarily).+ logToDisk,+ // Needed by ML worker.+ convertToJPEG: (imageData: Uint8Array) =>+ ensureElectron().convertToJPEG(imageData),+};++export type WorkerBridge = typeof workerBridge;diff --git a/web/apps/albums/vendor/ente-base/worker/worker-bridge.ts b/web/apps/albums/vendor/ente-base/worker/worker-bridge.tsnew file mode 100644index 0000000000..eaf3028ea4--- /dev/null+++ b/web/apps/albums/vendor/ente-base/worker/worker-bridge.ts@@ -0,0 +1,15 @@+import { wrap } from "comlink";+import { inWorker } from "../env";+import type { WorkerBridge } from "./comlink-worker";++/**+ * The web worker side handle to the {@link WorkerBridge} exposed by the main+ * thread.+ *+ * This file is meant to be run inside a worker. Accessing the properties of+ * this object will be transparently (but asynchrorously) relayed to the+ * implementation of the {@link WorkerBridge} in `comlink-worker.ts`.+ */+export const workerBridge = inWorker()+ ? wrap<WorkerBridge>(globalThis)+ : undefined;diff --git a/web/apps/albums/vendor/ente-gallery/components/FileInfo.tsx b/web/apps/albums/vendor/ente-gallery/components/FileInfo.tsxnew file mode 100644index 0000000000..65d06e67cd--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/FileInfo.tsx@@ -0,0 +1,1185 @@+/* eslint-disable @typescript-eslint/ban-ts-comment */+/* TODO: Split this file to deal with the ente-new/photos imports.+1. Move common components into FileInfoComponents.tsx+2. Move the rest out to files in the apps themselves:+ - albums/SharedFileInfo+ - photos/FileInfo+*/++import CalendarTodayIcon from "@mui/icons-material/CalendarToday";+import CameraOutlinedIcon from "@mui/icons-material/CameraOutlined";+import CloseIcon from "@mui/icons-material/Close";+import DoneIcon from "@mui/icons-material/Done";+import EditIcon from "@mui/icons-material/Edit";+import FaceRetouchingNaturalIcon from "@mui/icons-material/FaceRetouchingNatural";+import FolderOutlinedIcon from "@mui/icons-material/FolderOutlined";+import LocationOnOutlinedIcon from "@mui/icons-material/LocationOnOutlined";+import PhotoOutlinedIcon from "@mui/icons-material/PhotoOutlined";+import TextSnippetOutlinedIcon from "@mui/icons-material/TextSnippetOutlined";+import VideocamOutlinedIcon from "@mui/icons-material/VideocamOutlined";+import {+ Box,+ Button,+ CircularProgress,+ Dialog,+ DialogContent,+ DialogTitle,+ IconButton,+ InputAdornment,+ Link,+ Stack,+ styled,+ TextField,+ Typography,+ type ButtonProps,+ type DialogProps,+} from "@mui/material";+import { LinkButtonUndecorated } from "ente-base/components/LinkButton";+import { type ButtonishProps } from "ente-base/components/mui";+import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";+import {+ SidebarDrawer,+ SidebarDrawerTitlebar,+} from "ente-base/components/mui/SidebarDrawer";+import { SingleInputForm } from "ente-base/components/SingleInputForm";+import { EllipsizedTypography } from "ente-base/components/Typography";+import {+ useModalVisibility,+ type ModalVisibilityProps,+} from "ente-base/components/utils/modal";+import { useBaseContext } from "ente-base/context";+import { haveWindow } from "ente-base/env";+import { nameAndExtension } from "ente-base/file-name";+import { formattedDate, formattedTime } from "ente-base/i18n-date";+import log from "ente-base/log";+import type { Location } from "ente-base/types";+import { CopyButton } from "ente-gallery/components/FileInfoComponents";+import { tagNumericValue, type RawExifTags } from "ente-gallery/services/exif";+import { formattedByteSize } from "ente-gallery/utils/units";+import { type EnteFile } from "ente-media/file";+import {+ fileCreationPhotoDate,+ fileFileName,+ fileLocation,+ type ParsedMetadata,+ type ParsedMetadataDate,+} from "ente-media/file-metadata";+import { FileType } from "ente-media/file-type";+import { AssignPersonDialog } from "ente-new/photos/components/AssignPersonDialog";+import { EditLocationDialog } from "ente-new/photos/components/EditLocationDialog";+import { FileDateTimePicker } from "ente-new/photos/components/FileDateTimePicker";+import { FilePeopleList } from "ente-new/photos/components/PeopleList";+import {+ usePeopleStateSnapshot,+ useSettingsSnapshot,+} from "ente-new/photos/components/utils/use-snapshot";+import {+ updateFileCaption,+ updateFileFileName,+ updateFilePublicMagicMetadata,+ updateFilesLocation,+} from "ente-new/photos/services/file";+import {+ addManualFileAssignmentsToPerson,+ getAnnotatedFacesForFile,+ isMLEnabled,+ type AnnotatedFaceID,+} from "ente-new/photos/services/ml";+import { updateMapEnabled } from "ente-new/photos/services/settings";+import { useFormik } from "formik";+import { t } from "i18next";+import React, { useEffect, useMemo, useRef, useState } from "react";++// Re-uses images from ~leaflet package.+import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.webpack.css";+import "leaflet/dist/leaflet.css";+// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-unused-expressions+haveWindow() && require("leaflet-defaulticon-compatibility");+const leaflet = haveWindow()+ ? // eslint-disable-next-line @typescript-eslint/no-require-imports+ (require("leaflet") as typeof import("leaflet"))+ : null;++/**+ * Exif data for a file, in a form suitable for use by {@link FileInfo}.+ *+ * TODO: Indicate missing exif (e.g. videos) better, both in the data type, and+ * in the UI (e.g. by omitting the entire row).+ */+export interface FileInfoExif {+ tags: RawExifTags | undefined;+ parsed: ParsedMetadata | undefined;+}++export type FileInfoProps = ModalVisibilityProps & {+ /**+ * The file whose information we are showing.+ */+ file: EnteFile;+ /**+ * Exif information for {@link file}.+ */+ exif: FileInfoExif | undefined;+ /**+ * If set, then controls to edit the file's metadata (name, date, caption)+ * will be shown.+ */+ allowEdits?: boolean;+ /**+ * If set, then an inline map will be shown (if the user has enabled it)+ * using the file's location.+ */+ allowMap?: boolean;+ /**+ * If set, then a clickable chip will be shown for each normal collection+ * that this file is a part of.+ *+ * Uses {@link fileCollectionIDs}, {@link collectionNameByID} and+ * {@link onSelectCollection}, so all of those props should also be set for+ * this to have an effect.+ */+ showCollections?: boolean;+ /**+ * A map from file IDs to the IDs of the collections that they're a part of.+ *+ * Used when {@link showCollections} is set.+ */+ fileCollectionIDs?: Map<number, number[]>;+ /**+ * A map from collection IDs to their name.+ *+ * Used when {@link showCollections} is set.+ */+ collectionNameByID?: Map<number, string>;+ /**+ * Called when the action on the file info drawer has changed some metadata+ * for a file.+ *+ * It should return a promise that settles when the changes have been+ * reflected locally. Until the promise settles the UI element that+ * triggered the change will show an activity indicator to the user.+ */+ onFileMetadataUpdate?: () => Promise<void>;+ /**+ * Called when an action on the file info drawer change the caption of the+ * given {@link EnteFile}.+ *+ * This hook allows the file viewer to update the caption it is displaying+ * for the given file. It is called in addition to, and after the settlement+ * of, {@link onFileMetadataUpdate} since the caption update requires a+ * special case refresh of the PhotoSwipe dialog.+ *+ * @param fileID The ID of the file whose caption was updated.+ *+ * @param newCaption The updated value of the file's caption.+ */+ onUpdateCaption: (fileID: number, newCaption: string) => void;+ /**+ * Called when the user selects a collection from among the collections that+ * the file belongs to.+ */+ onSelectCollection?: (collectionID: number) => void;+ /**+ * Called when the user selects a person in the file info panel.+ */+ onSelectPerson?: (personID: string) => void;+};++export const FileInfo: React.FC<FileInfoProps> = ({+ open,+ onClose,+ file,+ exif,+ allowEdits,+ allowMap,+ showCollections,+ fileCollectionIDs,+ collectionNameByID,+ onFileMetadataUpdate,+ onUpdateCaption,+ onSelectCollection,+ onSelectPerson,+}) => {+ const { mapEnabled } = useSettingsSnapshot();+ const peopleState = usePeopleStateSnapshot();+ const { onGenericError } = useBaseContext();++ const [annotatedFaces, setAnnotatedFaces] = useState<AnnotatedFaceID[]>([]);++ const { show: showRawExif, props: rawExifVisibilityProps } =+ useModalVisibility();+ const { show: showAssignPerson, props: assignPersonVisibilityProps } =+ useModalVisibility();+ const { show: showEditLocation, props: editLocationVisibilityProps } =+ useModalVisibility();++ const assignablePeople = useMemo(+ () =>+ (peopleState?.visiblePeople ?? []).filter(+ (p) => p.type == "cgroup" && !!p.name,+ ),+ [peopleState],+ );++ const manuallyAssignedPeople = useMemo(() => {+ if (!isMLEnabled()) return [];++ const detectedPersonIDs = new Set(+ annotatedFaces.map((f) => f.personID),+ );+ return (peopleState?.people ?? []).filter(+ (p) =>+ p.type == "cgroup" &&+ !!p.name &&+ p.cgroup.data.manuallyAssigned.includes(file.id) &&+ !detectedPersonIDs.has(p.id),+ );+ }, [peopleState, file.id, annotatedFaces]);++ const canAddPerson = isMLEnabled() && assignablePeople.length > 0;++ // Prefer the location in the EnteFile, then fall back to Exif.+ const fileLocationValue = fileLocation(file) ?? exif?.parsed?.location;++ const location = fileLocationValue;++ const annotatedExif = useMemo(() => annotateExif(exif), [exif]);++ useEffect(() => {+ if (!isMLEnabled()) return undefined;++ // Take a dependency on open so that we refresh the list of people by+ // calling `getAnnotatedFacesForFile` again when the file info dialog is+ // closed and reopened.+ //+ // This covers a scenario like:+ // - User opens file info panel+ // - Selects one of the faces+ // - Gives it a name+ // - Then opens the same file again, and reopens the file info panel.+ //+ // Since the `file` hasn't changed, this hook wouldn't rerun. So we also+ // take a dependency on the open state of the dialog, causing us to+ // rerun whenever reopened (even if for the same file).+ if (!open) return undefined;++ let didCancel = false;++ void getAnnotatedFacesForFile(file).then(+ (faces) => !didCancel && setAnnotatedFaces(faces),+ );++ return () => {+ didCancel = true;+ };+ }, [file, open]);++ const handleSelectFace = ({ personID, faceID }: AnnotatedFaceID) => {+ log.info(`Selected person ${personID} for faceID ${faceID}`);+ onSelectPerson?.(personID);+ };++ const handleAddPerson = async (personID: string) => {+ assignPersonVisibilityProps.onClose();+ try {+ await addManualFileAssignmentsToPerson(personID, [file.id]);+ } catch (e) {+ onGenericError(e);+ }+ };++ const handleEditLocationConfirm = async (newLocation: Location) => {+ try {+ await updateFilesLocation(+ [file],+ newLocation.latitude,+ newLocation.longitude,+ );+ await onFileMetadataUpdate?.();+ } catch (e) {+ onGenericError(e);+ }+ };++ const uploaderName = file.pubMagicMetadata?.data.uploaderName;++ return (+ <FileInfoSidebar {...{ open, onClose }}>+ <SidebarDrawerTitlebar+ onClose={onClose}+ onRootClose={onClose}+ title={t("info")}+ />+ <Stack sx={{ pt: 1, pb: 3, gap: "20px" }}>+ <Caption+ {...{+ file,+ allowEdits,+ onFileMetadataUpdate,+ onUpdateCaption,+ onClose,+ }}+ />+ <CreationTime {...{ file, allowEdits, onFileMetadataUpdate }} />+ <FileName+ {...{+ file,+ annotatedExif,+ allowEdits,+ onFileMetadataUpdate,+ }}+ />++ {annotatedExif?.takenOnDevice && (+ <InfoItem+ icon={<CameraOutlinedIcon />}+ title={annotatedExif.takenOnDevice}+ caption={createMultipartCaption(+ annotatedExif.fNumber,+ annotatedExif.exposureTime,+ annotatedExif.iso,+ )}+ />+ )}++ {location ? (+ <>+ <InfoItem+ icon={<LocationOnOutlinedIcon />}+ title={t("location")}+ caption={+ !mapEnabled || !allowMap ? (+ <Link+ href={openStreetMapLink(location)}+ target="_blank"+ rel="noopener"+ sx={{ fontWeight: "medium" }}+ >+ {t("view_on_map")}+ </Link>+ ) : (+ <LinkButtonUndecorated+ onClick={() => updateMapEnabled(false)}+ >+ {t("disable_map")}+ </LinkButtonUndecorated>+ )+ }+ trailingButton={+ <Stack direction="row" sx={{ gap: 1 }}>+ {allowEdits && (+ <EditButton+ onClick={showEditLocation}+ />+ )}+ <CopyButton+ size="medium"+ text={openStreetMapLink(location)}+ />+ </Stack>+ }+ />+ {allowMap && (+ <MapBox+ key={`${location.latitude}-${location.longitude}`}+ location={location}+ mapEnabled={mapEnabled}+ />+ )}+ </>+ ) : (+ allowEdits && (+ <InfoItem+ icon={<LocationOnOutlinedIcon />}+ title={t("location")}+ caption={+ <LinkButtonUndecorated+ onClick={showEditLocation}+ >+ {t("add_location_button")}+ </LinkButtonUndecorated>+ }+ />+ )+ )}+ <InfoItem+ icon={<TextSnippetOutlinedIcon />}+ title={t("details")}+ caption={+ !exif ? (+ <ActivityIndicator size={12} />+ ) : !exif.tags ? (+ t("no_exif")+ ) : (+ <LinkButtonUndecorated onClick={showRawExif}>+ {t("view_exif")}+ </LinkButtonUndecorated>+ )+ }+ />+ {isMLEnabled() &&+ (annotatedFaces.length > 0 ||+ manuallyAssignedPeople.length > 0 ||+ canAddPerson) && (+ <InfoItem icon={<FaceRetouchingNaturalIcon />}>+ <FilePeopleList+ file={file}+ annotatedFaceIDs={annotatedFaces}+ onSelectFace={handleSelectFace}+ manuallyAssignedPeople={manuallyAssignedPeople}+ onSelectPerson={onSelectPerson}+ onAddPerson={+ canAddPerson ? showAssignPerson : undefined+ }+ addPersonTitle={t("add_a_person")}+ addPersonLabel={t("add")}+ />+ </InfoItem>+ )}+ {showCollections &&+ fileCollectionIDs &&+ collectionNameByID &&+ onSelectCollection && (+ <Albums+ {...{+ file,+ fileCollectionIDs,+ collectionNameByID,+ onSelectCollection,+ }}+ />+ )}+ {uploaderName && (+ <Typography+ variant="small"+ sx={{ m: 2, textAlign: "right", color: "text.muted" }}+ >+ {t("added_by_name", { name: uploaderName })}+ </Typography>+ )}+ </Stack>+ <RawExif+ {...rawExifVisibilityProps}+ onInfoClose={onClose}+ tags={exif?.tags}+ fileName={fileFileName(file)}+ />++ {canAddPerson && (+ <AssignPersonDialog+ {...assignPersonVisibilityProps}+ people={assignablePeople}+ title={t("add_a_person")}+ onSelectPerson={handleAddPerson}+ />+ )}++ {allowEdits && (+ <EditLocationDialog+ {...editLocationVisibilityProps}+ files={[file]}+ onConfirm={handleEditLocationConfirm}+ />+ )}+ </FileInfoSidebar>+ );+};++/**+ * Some immediate fields of interest, in the form that we want to display on the+ * info panel for a file.+ */+type AnnotatedExif = Required<FileInfoExif> & {+ resolution?: string;+ megaPixels?: string;+ takenOnDevice?: string;+ fNumber?: string;+ exposureTime?: string;+ iso?: string;+};++const annotateExif = (+ fileInfoExif: FileInfoExif | undefined,+): AnnotatedExif | undefined => {+ if (!fileInfoExif || !fileInfoExif.tags || !fileInfoExif.parsed)+ return undefined;++ const info: AnnotatedExif = { ...fileInfoExif };++ const { width, height } = fileInfoExif.parsed;+ if (width && height) {+ info.resolution = `${width} x ${height}`;+ const mp = Math.round((width * height) / 1000000);+ if (mp) info.megaPixels = `${mp}MP`;+ }++ const { tags } = fileInfoExif;+ const { exif } = tags;++ if (exif) {+ if (exif.Make && exif.Model)+ info.takenOnDevice = `${exif.Make.description} ${exif.Model.description}`;++ if (exif.FNumber)+ info.fNumber = exif.FNumber.description; /* e.g. "f/16" */++ if (exif.ExposureTime)+ info.exposureTime = exif.ExposureTime.description; /* "1/10" */++ if (exif.ISOSpeedRatings)+ info.iso = `ISO${tagNumericValue(exif.ISOSpeedRatings)}`;+ }++ return info;+};++const FileInfoSidebar = styled(+ (props: Pick<DialogProps, "open" | "onClose" | "children">) => (+ <SidebarDrawer+ {...props}+ anchor="right"+ // See: [Note: Workarounds for unactionable ARIA warnings], but this+ // time with a different workaround.+ //+ // https://github.com/mui/material-ui/issues/43106#issuecomment-2514637251+ disableRestoreFocus={true}+ closeAfterTransition={true}+ />+ ),+)(({ theme }) => ({+ // [Note: Lighter backdrop for overlays on photo viewer]+ //+ // The default backdrop color we use for the drawer in light mode is too+ // "white" when used in the image gallery because unlike the rest of the app+ // the gallery retains a black background irrespective of the mode. So use a+ // lighter scrim when overlaying content directly atop the image gallery.+ //+ // We don't need to add this special casing for nested overlays (e.g.+ // dialogs initiated from the file info drawer itself) since now there is+ // enough "white" on the screen to warrant the stronger (default) backdrop.+ ...theme.applyStyles("light", {+ ".MuiBackdrop-root": {+ backgroundColor: theme.vars.palette.backdrop.faint,+ },+ }),+}));++interface InfoItemProps {+ /**+ * The icon associated with the info entry.+ */+ icon: React.ReactNode;+ /**+ * The primary content / title of the info entry.+ *+ * Only used if {@link children} are not specified.+ */+ title?: string;+ /**+ * The secondary information / subtext associated with the info entry.+ *+ * Only used if {@link children} are not specified.+ */+ caption?: React.ReactNode;+ /**+ * A component, usually a button (e.g. an "edit button"), shown at the+ * trailing edge of the info entry.+ */+ trailingButton?: React.ReactNode;+}++/**+ * An entry in the file info panel listing.+ */+const InfoItem: React.FC<React.PropsWithChildren<InfoItemProps>> = ({+ icon,+ title,+ caption,+ trailingButton,+ children,+}) => (+ <Stack+ direction="row"+ sx={{ alignItems: "flex-start", flex: 1, gap: "12px" }}+ >+ <InfoItemIconContainer>{icon}</InfoItemIconContainer>+ {children ? (+ <Box sx={{ flex: 1, mt: "4px" }}>{children}</Box>+ ) : (+ <Stack sx={{ flex: 1, mt: "4px", gap: "4px" }}>+ <Typography sx={{ wordBreak: "break-all" }}>{title}</Typography>+ <Typography+ variant="small"+ {...(typeof caption != "string" && { component: "div" })}+ sx={{ color: "text.muted" }}+ >+ {caption}+ </Typography>+ </Stack>+ )}+ {trailingButton}+ </Stack>+);++const InfoItemIconContainer = styled("div")(+ ({ theme }) => `+ width: 48px;+ aspect-ratio: 1;+ display: flex;+ justify-content: center;+ align-items: center;+ color: ${theme.vars.palette.stroke.muted}+`,+);++type EditButtonProps = ButtonishProps & {+ /**+ * If true, then an activity indicator is shown in place of the edit icon.+ */+ loading?: boolean;+};++const EditButton: React.FC<EditButtonProps> = ({ onClick, loading }) => (+ <IconButton onClick={onClick} disabled={!!loading} color="secondary">+ {!loading ? (+ <EditIcon />+ ) : (+ <CircularProgress size={"24px"} color="inherit" />+ )}+ </IconButton>+);++type CaptionProps = Pick<+ FileInfoProps,+ | "file"+ | "allowEdits"+ | "onFileMetadataUpdate"+ | "onUpdateCaption"+ | "onClose"+>;++const Caption: React.FC<CaptionProps> = ({+ file,+ allowEdits,+ onFileMetadataUpdate,+ onUpdateCaption,+ onClose,+}) => {+ const [isSaving, setIsSaving] = useState(false);++ const caption = file.pubMagicMetadata?.data.caption ?? "";++ const formik = useFormik<{ caption: string }>({+ initialValues: { caption },+ validate: ({ caption }) =>+ caption.length > 5000+ ? { caption: t("caption_character_limit") }+ : {},+ onSubmit: async ({ caption: newCaption }, { setFieldError }) => {+ if (newCaption == caption) return;+ setIsSaving(true);+ try {+ await updateFileCaption(file, newCaption);+ await onFileMetadataUpdate?.();+ onUpdateCaption(file.id, newCaption);+ setIsSaving(false);+ onClose();+ } catch (e) {+ log.error("Failed to update caption", e);+ setIsSaving(false);+ setFieldError("caption", t("generic_error"));+ }+ },+ });++ const { values, errors, handleChange, handleSubmit, resetForm } = formik;++ if (!caption.length && !allowEdits) {+ // Visually take up some space, otherwise the info panel for the shared+ // photos without a caption looks squished at the top.+ return <Box sx={{ minHeight: 2 }}></Box>;+ }++ return (+ <CaptionForm onSubmit={handleSubmit}>+ <TextField+ id="caption"+ name="caption"+ type="text"+ multiline+ maxRows={7}+ aria-label={t("description")}+ hiddenLabel+ fullWidth+ placeholder={t("caption_placeholder")}+ value={values.caption}+ onChange={handleChange("caption")}+ error={!!errors.caption}+ helperText={errors.caption}+ disabled={!allowEdits || isSaving}+ />+ {values.caption != caption && (+ <Stack direction="row" sx={{ justifyContent: "flex-end" }}>+ <IconButton+ type="submit"+ disabled={isSaving}+ // Prevent layout shift when we're showing progress.+ sx={{ minWidth: "48px" }}+ >+ {isSaving ? (+ <CircularProgress size="18px" color="inherit" />+ ) : (+ <DoneIcon />+ )}+ </IconButton>+ <IconButton onClick={() => resetForm()} disabled={isSaving}>+ <CloseIcon />+ </IconButton>+ </Stack>+ )}+ </CaptionForm>+ );+};++const CaptionForm = styled("form")(({ theme }) => ({+ padding: theme.spacing(1),+}));++type CreationTimeProps = Pick<+ FileInfoProps,+ "allowEdits" | "onFileMetadataUpdate"+> & { file: EnteFile };++const CreationTime: React.FC<CreationTimeProps> = ({+ file,+ allowEdits,+ onFileMetadataUpdate,+}) => {+ const { onGenericError } = useBaseContext();++ const [isEditing, setIsEditing] = useState(false);+ const [isSaving, setIsSaving] = useState(false);++ const originalDate = fileCreationPhotoDate(file);++ const saveEdits = async (pickedTime: ParsedMetadataDate) => {+ setIsEditing(false);++ const { dateTime, timestamp: editedTime } = pickedTime;+ if (editedTime == originalDate.getTime()) {+ // Same as before.+ return;+ }++ setIsSaving(true);+ try {+ // [Note: Don't modify offsetTime when editing date via picker]+ //+ // Use the updated date time (both in its canonical dateTime form,+ // and also as in the epoch timestamp), but don't use the offset.+ //+ // The offset here will be the offset of the computer where this+ // user is making this edit, not the offset of the place where the+ // photo was taken. In a future iteration of the date time editor,+ // we can provide functionality for the user to edit the associated+ // offset, but right now it is not even surfaced, so don't also+ // potentially overwrite it.+ await updateFilePublicMagicMetadata(file, { dateTime, editedTime });+ await onFileMetadataUpdate?.();+ } catch (e) {+ onGenericError(e);+ }+ setIsSaving(false);+ };++ return (+ <>+ <InfoItem+ icon={<CalendarTodayIcon />}+ title={formattedDate(originalDate)}+ caption={formattedTime(originalDate)}+ trailingButton={+ allowEdits && (+ <EditButton+ onClick={() => setIsEditing(true)}+ loading={isSaving}+ />+ )+ }+ />+ {isEditing && (+ <FileDateTimePicker+ initialValue={originalDate}+ onAccept={saveEdits}+ onDidClose={() => setIsEditing(false)}+ />+ )}+ </>+ );+};++type FileNameProps = Pick<+ FileInfoProps,+ "allowEdits" | "onFileMetadataUpdate"+> & { file: EnteFile; annotatedExif: AnnotatedExif | undefined };++const FileName: React.FC<FileNameProps> = ({+ file,+ annotatedExif,+ allowEdits,+ onFileMetadataUpdate,+}) => {+ const { show: showRename, props: renameVisibilityProps } =+ useModalVisibility();++ const fileName = fileFileName(file);++ const handleRename = async (newFileName: string) => {+ await updateFileFileName(file, newFileName);+ await onFileMetadataUpdate?.();+ };++ const icon =+ file.metadata.fileType == FileType.video ? (+ <VideocamOutlinedIcon />+ ) : (+ <PhotoOutlinedIcon />+ );++ const fileSize = file.info?.fileSize;+ const caption = createMultipartCaption(+ annotatedExif?.megaPixels,+ annotatedExif?.resolution,+ fileSize ? formattedByteSize(fileSize) : undefined,+ );++ return (+ <>+ <InfoItem+ icon={icon}+ title={fileName}+ caption={caption}+ trailingButton={+ allowEdits && <EditButton onClick={showRename} />+ }+ />+ <RenameFileDialog+ {...renameVisibilityProps}+ fileName={fileName}+ onRename={handleRename}+ />+ </>+ );+};++const createMultipartCaption = (+ p1: string | undefined,+ p2: string | undefined,+ p3: string | undefined,+) => (+ <Stack direction="row" sx={{ gap: 1 }}>+ {p1 && <div>{p1}</div>}+ {p2 && <div>{p2}</div>}+ {p3 && <div>{p3}</div>}+ </Stack>+);++type RenameFileDialogProps = ModalVisibilityProps & {+ /**+ * The current name of the file.+ */+ fileName: string;+ /**+ * Called when the user makes a change to the existing name and activates the+ * rename button on the dialog.+ *+ * @param newFileName The changed name. The extension currently cannot be+ * modified, but it is guaranteed the name component of {@link newFileName}+ * will be different from that of the {@link fileName} prop of the dialog.+ *+ * Until the promise settles, the dialog will show an activity indicator. If+ * the promise rejects, it will also show an error. If the promise is+ * fulfilled, then the dialog will also be closed.+ *+ * The dialog will also be closed if the user activates the rename button+ * without changing the name.+ */+ onRename: (newFileName: string) => Promise<void>;+};++const RenameFileDialog: React.FC<RenameFileDialogProps> = ({+ open,+ onClose,+ fileName,+ onRename,+}) => {+ const [name, extension] = nameAndExtension(fileName);++ const handleSubmit = async (newName: string) => {+ const newFileName = [newName, extension].filter((x) => !!x).join(".");+ if (newFileName != fileName) {+ await onRename(newFileName);+ }+ onClose();+ };++ return (+ <Dialog {...{ open, onClose }} fullWidth maxWidth="xs">+ <DialogTitle sx={{ "&&&": { paddingBlock: "26px 0px" } }}>+ {t("rename_file")}+ </DialogTitle>+ <DialogContent>+ <SingleInputForm+ label={t("file_name")}+ placeholder={t("file_name")}+ initialValue={name}+ submitButtonColor="primary"+ submitButtonTitle={t("rename")}+ onSubmit={handleSubmit}+ onCancel={onClose}+ slotProps={{+ input: {+ // Align the adornment text to the input text.+ sx: { alignItems: "baseline" },+ endAdornment: extension && (+ <InputAdornment position="end">+ {`.${extension}`}+ </InputAdornment>+ ),+ },+ }}+ />+ </DialogContent>+ </Dialog>+ );+};++const openStreetMapLink = ({ latitude, longitude }: Location) =>+ `https://www.openstreetmap.org/?mlat=${latitude}&mlon=${longitude}#map=15/${latitude}/${longitude}`;++const leafletAttributionPrefix =+ '<a href="https://leafletjs.com" target="_blank" rel="noopener noreferrer">Leaflet</a>';++interface MapBoxProps {+ location: Location;+ mapEnabled: boolean;+}++const MapBox: React.FC<MapBoxProps> = ({ location, mapEnabled }) => {+ const urlTemplate = "https://tile.openstreetmap.org/{z}/{x}/{y}.png";+ const attribution =+ '© <a target="_blank" rel="noopener noreferrer" href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';+ const zoom = 16;++ const mapBoxContainerRef = useRef<HTMLDivElement>(null);+ const mapRef = useRef<L.Map | null>(null);+ const markerRef = useRef<L.Marker | null>(null);++ useEffect(() => {+ if (!leaflet) return;+ if (!mapEnabled) {+ if (mapRef.current) {+ mapRef.current.remove();+ mapRef.current = null;+ markerRef.current = null;+ }+ return;+ }++ const mapContainer = mapBoxContainerRef.current;+ if (!mapContainer) return;++ const position: L.LatLngTuple = [location.latitude, location.longitude];+ if (!mapRef.current) {+ // @ts-ignore+ const map = leaflet.map(mapContainer).setView(position, zoom);+ map.attributionControl.setPrefix(leafletAttributionPrefix);+ // @ts-ignore+ leaflet.tileLayer(urlTemplate, { attribution }).addTo(map);+ // @ts-ignore+ markerRef.current = leaflet.marker(position).addTo(map);+ mapRef.current = map;+ } else {+ mapRef.current.setView(position, zoom);+ markerRef.current?.setLatLng(position);+ }+ return () => {+ if (mapRef.current) {+ mapRef.current.remove();+ mapRef.current = null;+ markerRef.current = null;+ }+ };+ }, [+ mapEnabled,+ location.latitude,+ location.longitude,+ zoom,+ attribution,+ urlTemplate,+ ]);++ return mapEnabled ? (+ <MapBoxContainer ref={mapBoxContainerRef} />+ ) : (+ <MapBoxEnableContainer>+ <ChipButton onClick={() => updateMapEnabled(true)}>+ {t("enable_map")}+ </ChipButton>+ </MapBoxEnableContainer>+ );+};++const MapBoxContainer = styled("div")`+ height: 200px;+ width: 100%;+`;++const MapBoxEnableContainer = styled(MapBoxContainer)(+ ({ theme }) => `+ position: relative;+ display: flex;+ justify-content: center;+ align-items: center;+ background-color: ${theme.vars.palette.fill.fainter};+`,+);++interface RawExifProps {+ open: boolean;+ onClose: () => void;+ onInfoClose: () => void;+ tags: RawExifTags | undefined;+ fileName: string;+}++const RawExif: React.FC<RawExifProps> = ({+ open,+ onClose,+ onInfoClose,+ tags,+ fileName,+}) => {+ if (!tags) {+ return <></>;+ }++ const handleRootClose = () => {+ onClose();+ onInfoClose();+ };++ const items: (readonly [string, string, string, string])[] = Object.entries(+ tags,+ )+ .map(([namespace, namespaceTags]) => {+ return Object.entries(namespaceTags).map(([tagName, tag]) => {+ const key = `${namespace}:${tagName}`;+ let description = "<...>";+ if (typeof tag == "string") {+ description = tag;+ } else if (typeof tag == "number") {+ description = `${tag}`;+ } else if (+ tag &&+ typeof tag == "object" &&+ "description" in tag &&+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ typeof tag.description == "string"+ ) {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access+ description = tag.description;+ }+ return [key, namespace, tagName, description] as const;+ });+ })+ .flat()+ .filter(([, , , description]) => description);++ return (+ <FileInfoSidebar open={open} onClose={onClose}>+ <SidebarDrawerTitlebar+ onClose={onClose}+ onRootClose={handleRootClose}+ title={t("exif")}+ caption={fileName}+ actionButton={+ <CopyButton size="small" text={JSON.stringify(tags)} />+ }+ />+ <Stack sx={{ gap: 2, py: 3, px: 1 }}>+ {items.map(([key, namespace, tagName, description]) => (+ <ExifItem key={key}>+ <Stack direction="row" sx={{ gap: 1 }}>+ <Typography+ variant="small"+ sx={{ color: "text.muted" }}+ >+ {tagName}+ </Typography>+ <Typography+ variant="tiny"+ sx={{ color: "text.faint" }}+ >+ {namespace}+ </Typography>+ </Stack>+ <EllipsizedTypography sx={{ width: "100%" }}>+ {description}+ </EllipsizedTypography>+ </ExifItem>+ ))}+ </Stack>+ </FileInfoSidebar>+ );+};++const ExifItem = styled("div")`+ padding-left: 8px;+ padding-right: 8px;+ display: flex;+ flex-direction: column;+ gap: 4px;+`;++type AlbumsProps = Required<+ Pick<+ FileInfoProps,+ "fileCollectionIDs" | "collectionNameByID" | "onSelectCollection"+ >+> & { file: EnteFile };++const Albums: React.FC<AlbumsProps> = ({+ file,+ fileCollectionIDs,+ collectionNameByID,+ onSelectCollection,+}) => (+ <InfoItem icon={<FolderOutlinedIcon />}>+ <Stack+ direction="row"+ sx={{+ gap: 1,+ flexWrap: "wrap",+ justifyContent: "flex-start",+ alignItems: "flex-start",+ }}+ >+ {fileCollectionIDs+ .get(file.id)+ ?.filter((collectionID) => collectionNameByID.has(collectionID))+ .map((collectionID) => (+ <ChipButton+ key={collectionID}+ onClick={() => onSelectCollection(collectionID)}+ >+ {collectionNameByID.get(collectionID)}+ </ChipButton>+ ))}+ </Stack>+ </InfoItem>+);++const ChipButton = styled((props: ButtonProps) => (+ <Button color="secondary" {...props} />+))(({ theme }) => ({ ...theme.typography.small, padding: "8px" }));diff --git a/web/apps/albums/vendor/ente-gallery/components/FileInfoComponents.tsx b/web/apps/albums/vendor/ente-gallery/components/FileInfoComponents.tsxnew file mode 100644index 0000000000..f6d1d05efb--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/FileInfoComponents.tsx@@ -0,0 +1,30 @@+import ContentCopyIcon from "@mui/icons-material/ContentCopy";+import DoneIcon from "@mui/icons-material/Done";+import { IconButton, Tooltip, type SvgIconProps } from "@mui/material";+import { useClipboardCopy } from "ente-base/components/utils/hooks";+import { t } from "i18next";++interface CopyButtonProps {+ /**+ * The text to copy when the button is clicked.+ */+ text: string;+ /**+ * The size of the icon.+ */+ size?: SvgIconProps["fontSize"];+}++export const CopyButton: React.FC<CopyButtonProps> = ({ text, size }) => {+ const [copied, handleClick] = useClipboardCopy(text);++ const Icon = copied ? DoneIcon : ContentCopyIcon;++ return (+ <Tooltip arrow open={copied} title={t("copied")}>+ <IconButton onClick={handleClick} color="secondary">+ <Icon fontSize={size} />+ </IconButton>+ </Tooltip>+ );+};diff --git a/web/apps/albums/vendor/ente-gallery/components/FullScreenDropZone.tsx b/web/apps/albums/vendor/ente-gallery/components/FullScreenDropZone.tsxnew file mode 100644index 0000000000..caa4445e0c--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/FullScreenDropZone.tsx@@ -0,0 +1,176 @@+import CloseIcon from "@mui/icons-material/Close";+import { IconButton, Stack, styled, Typography } from "@mui/material";+import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";+import { t } from "i18next";+import React, { useCallback, useEffect, useState } from "react";+import { type FileWithPath, useDropzone } from "react-dropzone";++const hasDraggedFiles = (+ dataTransfer: DataTransfer | null | undefined,+): boolean => {+ if (!dataTransfer) return false;++ for (const item of Array.from(dataTransfer.items)) {+ if (item.kind == "file") return true;+ }++ for (const type of Array.from(dataTransfer.types)) {+ if (type == "Files") return true;+ }++ return false;+};++interface FullScreenDropZoneProps {+ /**+ * Optional override to the message show to the user when a drag is in+ * progress.+ *+ * Default: t("upload_dropzone_hint")+ */+ message?: string;+ /**+ * If `true`, then drag and drop functionality is disabled.+ */+ disabled?: boolean;+ /**+ * Callback invoked when the user drags and drops files.+ *+ * It will only be called if there is at least one file in {@link files}.+ */+ onDrop: (files: FileWithPath[]) => void;+}++/**+ * A full screen container that accepts drag and drop of files, and also shows a+ * visual overlay to the user while a drag is in progress.+ *+ * It can serves as the root component of the gallery pages as the container+ * itself is a stack with flex 1, and so will fill all the height (and width)+ * available to it. The other contents of the screen can then be placed as its+ * children.+ *+ * It is meant to be used in tandem with "react-dropzone"; specifically, it+ * requires the `getRootProps` function returned by a call to+ * {@link useDropzone}.+ */+export const FullScreenDropZone: React.FC<+ React.PropsWithChildren<FullScreenDropZoneProps>+> = ({ message, disabled, onDrop, children }) => {+ const {+ // A function to call to get the props we should apply to the container,+ getRootProps,+ // ... the props we should apply to the <input> element,+ getInputProps,+ } = useDropzone({+ noClick: true,+ noKeyboard: true,+ disabled,+ onDrop(acceptedFiles) {+ setIsDropPending(false);+ // Invoked the `onDrop` callback only if there is at least 1 file.+ if (acceptedFiles.length) {+ // Create a regular array from the readonly array returned by+ // dropzone.+ onDrop([...acceptedFiles]);+ }+ },+ });++ const [isDragActive, setIsDragActive] = useState(false);+ const [isDropPending, setIsDropPending] = useState(false);++ const handleDragEnter = useCallback(+ (event: React.DragEvent<HTMLElement>) => {+ if (!hasDraggedFiles(event.dataTransfer)) return;+ setIsDragActive(true);+ },+ [],+ );++ const handleOverlayDrop = useCallback(+ (event: React.DragEvent<HTMLElement>) => {+ if (!hasDraggedFiles(event.dataTransfer)) {+ setIsDropPending(false);+ setIsDragActive(false);+ return;+ }+ setIsDropPending(true);+ setIsDragActive(false);+ },+ [],+ );++ const handleDragLeave = useCallback(() => {+ setIsDragActive(false);+ }, []);++ useEffect(() => {+ const handleKeydown = (event: KeyboardEvent) => {+ if (event.code == "Escape" && !isDropPending) handleDragLeave();+ };++ window.addEventListener("keydown", handleKeydown);+ return () => window.removeEventListener("keydown", handleKeydown);+ }, [isDropPending, handleDragLeave]);++ return (+ <>+ <input {...getInputProps()} />+ <Stack+ sx={{ flex: 1 }}+ {...getRootProps({ onDragEnter: handleDragEnter })}+ >+ {(isDragActive || isDropPending) && (+ <DropZoneOverlay+ onDrop={handleOverlayDrop}+ onDragLeave={handleDragLeave}+ >+ <CloseButton+ disabled={isDropPending}+ onClick={handleDragLeave}+ >+ <CloseIcon />+ </CloseButton>+ <Typography variant="h3">+ {isDropPending ? (+ <ActivityIndicator />+ ) : (+ (message ?? t("upload_dropzone_hint"))+ )}+ </Typography>+ </DropZoneOverlay>+ )}+ {children}+ </Stack>+ </>+ );+};++const DropZoneOverlay = styled(Stack)(+ ({ theme }) => `+ position: absolute;+ left: 0;+ top: 0;+ height: 100%;+ width: 100%;+ outline: none;+ justify-content: center;+ align-items: center;+ transition: border 0.24s ease-in-out;+ border-width: 5px;+ border-style: solid;+ border-color: ${theme.vars.palette.accent.light};+ background-color: ${theme.vars.palette.backdrop.base};+ backdrop-filter: blur(10px);+ /* Above the highest possible MUI z-index, that of the MUI tooltip+ See: https://mui.com/material-ui/customization/default-theme/ */+ z-index: calc(var(--mui-zIndex-tooltip) + 1);+`,+);++const CloseButton = styled(IconButton)`+ position: absolute;+ top: 10px;+ right: 10px;+`;diff --git a/web/apps/albums/vendor/ente-gallery/components/Upload.tsx b/web/apps/albums/vendor/ente-gallery/components/Upload.tsxnew file mode 100644index 0000000000..7f723875cf--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/Upload.tsx@@ -0,0 +1,7 @@+/**+ * The upload can be triggered by different buttons and flows in the UI, each of+ * which is referred to as an "intent".+ *+ * The "intent" does not change the eventual upload outcome, only the UX flow.+ */+export type UploadTypeSelectorIntent = "upload" | "import" | "collect";diff --git a/web/apps/albums/vendor/ente-gallery/components/utils/save-groups.ts b/web/apps/albums/vendor/ente-gallery/components/utils/save-groups.tsnew file mode 100644index 0000000000..9c068085b6--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/utils/save-groups.ts@@ -0,0 +1,248 @@+import { useSyncExternalStore } from "react";++/**+ * An object that keeps track of progress of a user-initiated download of a set+ * of files to the user's device.+ *+ * This "download" is distinct from the downloads the app does from remote (e.g.+ * when the user is viewing them).+ *+ * What we're doing here is perhaps more accurately described "a user initiated+ * download of files to the user's device", but that is too long, so we instead+ * refer to this process as "saving them".+ *+ * Note however that the app's UI itself takes the user perspective, so the+ * upper (UI) layers use the word "download", while this implementation layer+ * uses the word "save", and there is an unavoidable incongruity in the middle.+ */+export interface SaveGroup {+ /**+ * A randomly generated unique identifier of this set of saves.+ */+ id: number;+ /**+ * A callback to retry the download that created this save group.+ */+ retry?: () => void;+ /**+ * The user visible title of the save group.+ *+ * Depending on the context can either be an auto generated string (e.g "5+ * files"), or the name of the collection which is being downloaded.+ */+ title: string;+ /**+ * If this save group is associated with a {@link CollectionSummary}, then+ * the ID of that collection summary.+ *+ * The {@link SaveGroup} type is also used in the context of the albums app,+ * which does not use or need the concept of link {@link CollectionSummary},+ * we to avoid taking a dependency of the type we store these two relevant+ * properties - {@link collectionSummaryID} and+ * {@link isHiddenCollectionSummary} - inline.+ */+ collectionSummaryID?: number;+ /**+ * `true` if the collection summary associated with the save group is+ * hidden.+ */+ isHiddenCollectionSummary?: boolean;+ /**+ * The path to a directory on the user's file system that was selected by+ * the user to save the files in when they initiated the download on the+ * desktop app.+ *+ * This property is only set when running in the context of the desktop app.+ * The web app downloads to the user's default downloads folder, and when+ * running in the web app this property will not be set.+ */+ downloadDirPath?: string;+ /**+ * The total number of files to save to the user's device.+ */+ total: number;+ /**+ * The number of files that have been saved so far.+ */+ success: number;+ /**+ * The number of failures.+ */+ failed: number;+ /**+ * An {@link AbortController} that can be used to cancel the save.+ */+ canceller: AbortController;+ /**+ * The reason for the failure, if any.+ *+ * This is used to show a more specific error message to the user.+ * - "network_offline": The network went offline during download+ * - "file_error": One or more individual files failed to download+ * - undefined: No specific reason (generic error)+ */+ failureReason?: "network_offline" | "file_error";+ /**+ * `true` when we expect the ZIP download to span multiple parts, so part+ * numbers should be shown from the first part.+ */+ includeZipNumber?: boolean;+ /**+ * `true` when the ZIP file is being downloaded from memory to the user's+ * device. This is only relevant for web downloads where files are first+ * collected into a ZIP in memory, then saved to the device.+ */+ isDownloadingZip?: boolean;+ /**+ * The current ZIP part number being processed. Only relevant for web+ * downloads where files are batched into multiple ZIP parts.+ */+ currentPart?: number;+}++/**+ * Return `true` if there are no files in this save group that are pending.+ */+export const isSaveComplete = ({ total, success, failed }: SaveGroup) =>+ total == success + failed;++/**+ * Return `true` if there are no files in this save group that are pending, but+ * one or more files had failed to download.+ */+export const isSaveCompleteWithErrors = (group: SaveGroup) =>+ group.failed > 0 && isSaveComplete(group);++/**+ * Return `true` if this save was cancelled on a user request.+ */+export const isSaveCancelled = (group: SaveGroup) =>+ group.canceller.signal.aborted;++/**+ * A function that can be used to add a save group.+ *+ * It returns a function that can subsequently be used to update the save group+ * by applying a transform to it (see {@link UpdateSaveGroup}). The UI will+ * react and update itself on updates done this way.+ */+export type AddSaveGroup = (+ group: Pick<+ SaveGroup,+ | "title"+ | "collectionSummaryID"+ | "isHiddenCollectionSummary"+ | "downloadDirPath"+ | "total"+ | "includeZipNumber"+ | "canceller"+ | "retry"+ >,+) => UpdateSaveGroup;++/**+ * A function that can be used to update a instance of a save group by applying+ * the provided transform.+ *+ * This is obtained by a call to an instance of {@link AddSaveGroup}. The UI+ * will update itself to reflect the changes made by the transform.+ */+export type UpdateSaveGroup = (+ tranform: (prev: SaveGroup) => SaveGroup,+) => void;++/**+ * A function that can be used to remove a save group.+ *+ * Save groups can be removed both on user actions - if the user presses the+ * close button to discard the notification showing the status of the save group+ * (cancelling it if needed) - or programmatically, if it is found that there+ * are no files that need saving for a particular request.+ */+export type RemoveSaveGroup = (saveGroup: SaveGroup) => void;++/**+ * Keep save groups outside the component tree so remounts can rehydrate+ * in-progress downloads after route changes.+ */+type SaveGroupsListener = () => void;++let saveGroupsSnapshot: SaveGroup[] = [];+const listeners = new Set<SaveGroupsListener>();++// Notify subscribers after the snapshot changes.+const emitChange = () => {+ for (const listener of listeners) listener();+};++// Return the current snapshot for external-store consumers.+const getSnapshot = () => saveGroupsSnapshot;++// Register a listener and return its unsubscribe cleanup.+const subscribe = (listener: SaveGroupsListener) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+};++const setSaveGroupsSnapshot = (+ next: SaveGroup[] | ((currentSaveGroups: SaveGroup[]) => SaveGroup[]),+) => {+ saveGroupsSnapshot =+ typeof next == "function" ? next(saveGroupsSnapshot) : next;+ emitChange();+};++const addSaveGroup: AddSaveGroup = (saveGroup) => {+ const id = Math.random();+ setSaveGroupsSnapshot((groups) => [+ ...groups,+ { ...saveGroup, id, success: 0, failed: 0 },+ ]);++ return (tx: (group: SaveGroup) => SaveGroup) => {+ setSaveGroupsSnapshot((groups) =>+ groups.map((g) => (g.id == id ? tx(g) : g)),+ );+ };+};++const removeSaveGroup: RemoveSaveGroup = ({ id }) =>+ setSaveGroupsSnapshot((groups) => groups.filter((g) => g.id != id));++export const resetSaveGroups = () => {+ if (!saveGroupsSnapshot.length) return;++ saveGroupsSnapshot = [];+ emitChange();+};++/**+ * A custom React hook that manages a list of active {@link SaveGroup}s, and+ * provides functions to add and remove entries to the list.+ */+export const useSaveGroups = () => {+ const saveGroups = useSyncExternalStore(+ subscribe,+ getSnapshot,+ getSnapshot,+ );++ return {+ saveGroups,+ onAddSaveGroup: addSaveGroup,+ onRemoveSaveGroup: removeSaveGroup,+ };+};++/**+ * Return save-group actions without subscribing to progress updates.+ *+ * Use this in components that only need to initiate or dismiss downloads,+ * otherwise every save progress update will re-render the caller.+ */+export const useSaveGroupsActions = () => ({+ onAddSaveGroup: addSaveGroup,+ onRemoveSaveGroup: removeSaveGroup,+});diff --git a/web/apps/albums/vendor/ente-gallery/components/utils/use-file-input.ts b/web/apps/albums/vendor/ente-gallery/components/utils/use-file-input.tsnew file mode 100644index 0000000000..a137b34ad3--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/utils/use-file-input.ts@@ -0,0 +1,124 @@+import { useCallback, useEffect, useRef } from "react";++interface UseFileInputParams {+ /**+ * If `true`, the file open dialog will ask the user to select directories.+ * Otherwise it'll ask the user to select files (default).+ */+ directory?: boolean;+ /**+ * If specified, it'll restrict the type of files that the user can select+ * by setting the "accept" attribute of the underlying HTML input element we+ * use to surface the file selector dialog. For value of accept can be an+ * extension or a MIME type (See+ * https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept).+ */+ accept?: string;+ /**+ * A callback that is invoked when the user selects files.+ *+ * It will be passed the list of {@link File}s that the user selected.+ *+ * This will be a list even if the user selected directories - in that case,+ * it will be the recursive list of files within this directory.+ *+ * If the user selected no items, then {@link onCancel} will be invoked.+ */+ onSelect: (selectedFiles: File[]) => void;+ /**+ * A callback that is invoked when the user cancels on the file / directory+ * dialog.+ */+ onCancel: () => void;+}++interface UseFileInputResult {+ /**+ * A function to call to get the properties that should be passed to a dummy+ * `input` element that needs to be created to anchor the select file+ * dialog. This input HTML element is not going to be visible, but it needs+ * to be part of the DOM for {@link openSelector} to have effect.+ */+ getInputProps: () => React.HTMLAttributes<HTMLInputElement>;+ /**+ * A function that can be called to open the select file / directory dialog.+ */+ openSelector: () => void;+}++/**+ * Wrap a open file selector into an easy to use package.+ *+ * Returns a {@link UseFileInputResult} which contains a function to get the+ * props for an input element, a function to open the file selector, and the+ * list of selected files.+ *+ * See the documentation of {@link UseFileInputParams} and+ * {@link UseFileInputResult} for more details.+ */+export const useFileInput = ({+ directory,+ accept,+ onSelect,+ onCancel,+}: UseFileInputParams): UseFileInputResult => {+ const inputRef = useRef<HTMLInputElement | null>(null);++ useEffect(() => {+ // React (as of 19) doesn't support attaching the onCancel event handler+ // via props, so do it using its ref.+ //+ // https://github.com/facebook/react/issues/27858+ inputRef.current!.addEventListener("cancel", onCancel);+ return () => {+ // Use optional chaining to avoid spurious errors during HMR.+ inputRef.current?.removeEventListener("cancel", onCancel);+ };+ }, [onCancel]);++ const openSelector = useCallback(() => {+ inputRef.current!.value = "";+ inputRef.current!.click();+ }, []);++ const handleChange: React.ChangeEventHandler<HTMLInputElement> = (+ event,+ ) => {+ const files = event.target.files;+ if (files?.length) {+ onSelect([...files]);+ } else {+ onCancel();+ }+ };++ // [Note: webkitRelativePath]+ //+ // If the webkitdirectory attribute of an <input> HTML element is set then+ // the File objects that we get will have `webkitRelativePath` property+ // containing the relative path to the selected directory.+ //+ // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory+ //+ // These paths use the POSIX path separator ("/").+ // https://stackoverflow.com/questions/62806233/when-using-webkitrelativepath-is-the-path-separator-operating-system-specific+ //+ const directoryOpts = directory+ ? { directory: "", webkitdirectory: "" }+ : {};++ const getInputProps = useCallback(+ () => ({+ type: "file",+ multiple: true,+ style: { display: "none" },+ ...directoryOpts,+ ref: inputRef,+ onChange: handleChange,+ ...(accept && { accept }),+ }),+ [directoryOpts, accept, handleChange],+ );++ return { getInputProps, openSelector };+};diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/AddNameModal.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/AddNameModal.tsxnew file mode 100644index 0000000000..a67c3d5844--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/AddNameModal.tsx@@ -0,0 +1,404 @@+import CloseIcon from "@mui/icons-material/Close";+import {+ Box,+ Button,+ Dialog,+ IconButton,+ styled,+ TextField,+ Typography,+} from "@mui/material";+import { type ModalVisibilityProps } from "ente-base/components/utils/modal";+import { t } from "i18next";+import React, { useState } from "react";++// =============================================================================+// Icons+// =============================================================================++const LikeIllustration: React.FC = () => (+ <svg+ width="126"+ height="121"+ viewBox="0 0 126 121"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M84.7129 23.0781C96.7222 23.0784 105.29 32.8476 105.29 44.499C105.29 53.3449 99.7258 62.2116 93.4453 69.4932C87.0622 76.8936 79.4391 83.2238 74.3574 87.0557C69.973 90.3616 64.031 90.3614 59.6465 87.0557C54.5648 83.2238 46.9408 76.8937 40.5576 69.4932C34.2771 62.2116 28.7129 53.3449 28.7129 44.499C28.713 32.8474 37.2813 23.0781 49.291 23.0781C54.9545 23.0782 60.4297 24.9062 67.001 30.9004C73.5726 24.9056 79.0491 23.0781 84.7129 23.0781Z"+ fill="#08C225"+ stroke="#232323"+ strokeWidth="5.73358"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ <mask+ id="mask0_add_name"+ style={{ maskType: "alpha" }}+ maskUnits="userSpaceOnUse"+ x="31"+ y="25"+ width="72"+ height="62"+ >+ <path+ d="M61.3721 84.7662C51.3787 77.2306 31.5801 60.0026 31.5801 44.4993C31.5801 34.2522 39.0372 25.9453 49.2909 25.9453C54.6041 25.9453 59.9173 27.7313 67.0016 34.8751C74.086 27.7313 79.3992 25.9453 84.7124 25.9453C94.9659 25.9453 102.423 34.2522 102.423 44.4993C102.423 60.0026 82.6247 77.2306 72.6312 84.7662C69.2683 87.3019 64.735 87.3019 61.3721 84.7662Z"+ fill="#08C225"+ />+ </mask>+ <g mask="url(#mask0_add_name)">+ <path+ d="M47.5975 41.0431C46.8515 39.3306 47.9859 37.1849 50.1312 36.2504C52.2765 35.316 54.6203 35.9467 55.3662 37.6591C56.1121 39.3716 54.9777 41.5173 52.8324 42.4518C50.6872 43.3862 48.3434 42.7555 47.5975 41.0431Z"+ fill="white"+ />+ <path+ d="M44.5677 45.0545C44.3136 44.4712 44.7025 43.7391 45.4364 43.4194C46.1704 43.0997 46.9713 43.3135 47.2254 43.8968C47.4795 44.4802 47.0906 45.2123 46.3567 45.532C45.6227 45.8517 44.8218 45.6379 44.5677 45.0545Z"+ fill="white"+ />+ <path+ d="M102.994 32.271C101.622 55.1395 78.9821 78.0073 50.9683 82.581C49.2531 88.2982 42.3926 93.7861 42.3926 95.1582C42.3926 96.5303 48.1097 107.926 50.9683 113.453L89.8447 101.447L115 66.5725C113.094 57.9969 106.196 31.3563 102.994 32.271Z"+ fill="#46A030"+ />+ <path+ d="M59.7039 28.2666C34.9591 23.1218 29.8137 47.7054 32.6723 55.1377L23.1143 51.7074C21.3992 47.3243 18.1976 37.9863 19.1123 35.6995C20.0271 33.4126 22.1615 16.833 23.1143 8.829L55.1302 3.68359L96.8651 13.9744C97.6274 18.1664 98.4659 26.8936 95.7217 28.2666C80.2855 22.5506 66.5644 33.9826 66.5644 33.4109C66.5644 32.9535 68.4701 30.5523 69.423 29.4089C66.3738 29.0281 60.1612 28.2666 59.7039 28.2666Z"+ fill="white"+ />+ </g>+ <path+ d="M20.9639 58.8477C14.9399 61.182 10.9104 66.0874 11.263 71.48C10.9104 66.0874 6.28324 61.7544 -9.80907e-05 60.2184C6.02383 57.884 10.0533 52.9787 9.70073 47.5861C10.0533 52.9787 14.6805 57.3117 20.9639 58.8477Z"+ fill="#08C225"+ />+ <path+ d="M119.579 91.9746C111.591 92.7003 105.114 97.1692 103.689 103.722C105.114 97.1692 101.077 90.4145 94.1117 86.438C102.099 85.7122 108.576 81.2434 110.001 74.6902C108.576 81.2434 112.613 87.9981 119.579 91.9746Z"+ fill="#08C225"+ />+ <path+ d="M112.728 9.21189C108.334 9.91374 104.912 12.6353 104.37 16.3181C104.912 12.6353 102.421 9.04853 98.4114 7.10627C102.806 6.40442 106.228 3.68284 106.77 7.55054e-05C106.228 3.68284 108.719 7.26962 112.728 9.21189Z"+ fill="#08C225"+ />+ </svg>+);++const CommentIllustration: React.FC = () => (+ <svg+ width="146"+ height="104"+ viewBox="0 0 146 104"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M62.4161 23.9825C69.5416 21.6377 77.2027 21.4587 84.4301 23.4677C91.6577 25.4768 98.1278 29.5846 103.021 35.2705C107.914 40.9564 111.011 47.9656 111.921 55.4117C112.83 62.8579 111.511 70.4066 108.131 77.1033C104.75 83.8 99.4603 89.3444 92.929 93.0344C86.3977 96.7244 78.9186 98.3952 71.438 97.8347C65.5124 97.3907 59.9955 95.6061 55.1766 92.7912L36.6137 95.1736C35.7803 95.2805 34.9485 94.962 34.4004 94.3252C33.8523 93.6882 33.6604 92.8183 33.8903 92.0101L39.0115 74.0065C36.9468 68.823 36.0051 63.1057 36.4493 57.1772C37.0098 49.6966 39.7764 42.5499 44.3984 36.6414C49.0204 30.733 55.2905 26.3274 62.4161 23.9825Z"+ fill="#08C225"+ stroke="#232323"+ strokeWidth="5"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ <mask+ id="mask0_add_name_comment"+ style={{ maskType: "alpha" }}+ maskUnits="userSpaceOnUse"+ x="36"+ y="24"+ width="74"+ height="72"+ >+ <path+ d="M71.6249 95.341C78.6125 95.8645 85.5985 94.3043 91.6993 90.8575C97.8002 87.4107 102.742 82.2321 105.899 75.9768C109.057 69.7214 110.289 62.6702 109.439 55.7147C108.59 48.7592 105.696 42.2119 101.126 36.9007C96.5551 31.5895 90.512 27.753 83.7608 25.8763C77.0096 23.9996 69.8535 24.167 63.1974 26.3573C56.5414 28.5477 50.6843 32.6626 46.3669 38.1817C42.0494 43.7008 39.4656 50.3762 38.942 57.3639C38.5044 63.2051 39.5049 68.8185 41.6537 73.8587L36.2949 92.6938L55.7183 90.2015C60.382 93.0774 65.7876 94.9037 71.6249 95.341Z"+ fill="#08C225"+ />+ </mask>+ <g mask="url(#mask0_add_name_comment)">+ <path+ d="M90.785 29.2779C55.9844 19.5648 41.0889 44.5028 37.9912 58.186L34.2834 72.1186C32.1784 72.553 27.1513 72.4724 23.883 68.6747C19.7976 63.9275 7.9607 55.936 8.75491 45.336C9.54911 34.736 9.85699 18.7723 10.8726 17.072C11.6851 15.7117 48.8217 4.51972 67.2885 -0.90625L123.817 3.32912C127.307 16.0258 125.586 38.991 90.785 29.2779Z"+ fill="white"+ />+ <path+ d="M68.1126 36.8926C67.7871 34.8769 69.5702 32.9123 72.0953 32.5044C74.6204 32.0966 76.9313 33.4 77.2568 35.4157C77.5824 37.4313 75.7993 39.3959 73.2742 39.8038C70.7491 40.2116 68.4382 38.9082 68.1126 36.8926Z"+ fill="white"+ />+ <path+ d="M63.6068 40.3106C63.4959 39.624 64.1063 38.9542 64.9702 38.8147C65.834 38.6752 66.6242 39.1187 66.7351 39.8054C66.846 40.492 66.2356 41.1618 65.3718 41.3013C64.5079 41.4408 63.7177 40.9973 63.6068 40.3106Z"+ fill="white"+ />+ <path+ d="M35.0516 84.4974C50.0736 86.3458 84.2825 85.3953 100.941 66.8061C117.601 48.217 131.472 23.1618 129.517 33.958C128.008 42.824 108.57 103.778 97.3574 108.665C83.3409 114.774 55.5151 127.853 46.4893 128.205C37.4635 128.557 25.3268 115.992 24.0509 114.477C22.775 112.962 24.2879 103.196 26.2494 99.9921C27.959 97.1997 26.5317 91.4899 26.2742 90.6394C26.2622 90.6323 26.2542 90.6209 26.2503 90.6048C26.2237 90.4942 26.2362 90.514 26.2742 90.6394C26.7756 90.9343 34.2208 83.5106 35.0516 84.4974Z"+ fill="#24B41F"+ />+ <path+ d="M63.1172 64.2407C65.5626 64.2849 67.581 62.3384 67.6253 59.8929C67.6695 57.4475 65.723 55.4291 63.2775 55.3849C60.8321 55.3406 58.8137 57.2871 58.7694 59.7326C58.7252 62.1781 60.6717 64.1964 63.1172 64.2407Z"+ fill="#232323"+ />+ <path+ d="M75.293 64.4555C77.7384 64.4998 79.7568 62.5532 79.801 60.1078C79.8453 57.6623 77.8988 55.644 75.4533 55.5997C73.0078 55.5554 70.9895 57.502 70.9452 59.9474C70.901 62.3929 72.8475 64.4112 75.293 64.4555Z"+ fill="#232323"+ />+ <path+ d="M87.4707 64.6821C89.9162 64.7263 91.9345 62.7798 91.9788 60.3343C92.023 57.8889 90.0765 55.8705 87.631 55.8263C85.1856 55.782 83.1672 57.7285 83.123 60.174C83.0787 62.6195 85.0252 64.6378 87.4707 64.6821Z"+ fill="#232323"+ />+ </g>+ <path+ d="M20.1099 75.4512C14.3314 77.6905 10.4661 82.396 10.8043 87.5689C10.4661 82.396 6.02735 78.2395 0 76.7661C5.77852 74.5268 9.64385 69.8213 9.30562 64.6484C9.64385 69.8213 14.0826 73.9778 20.1099 75.4512Z"+ fill="#08C225"+ />+ <path+ d="M145.699 62.5334C138.037 63.2295 131.824 67.5164 130.457 73.8026C131.824 67.5164 127.951 61.0368 121.27 57.2223C128.932 56.5261 135.145 52.2393 136.512 45.9531C135.145 52.2393 139.017 58.7188 145.699 62.5334Z"+ fill="#08C225"+ />+ <path+ d="M51.1361 8.83653C46.9208 9.50979 43.6377 12.1205 43.1181 15.6532C43.6377 12.1205 41.2488 8.67983 37.4023 6.81669C41.6176 6.14343 44.9007 3.53273 45.4202 0C44.9007 3.53273 47.2896 6.97339 51.1361 8.83653Z"+ fill="#08C225"+ />+ </svg>+);++// =============================================================================+// Types+// =============================================================================++export interface AddNameModalProps extends ModalVisibilityProps {+ /**+ * Called when user submits their name.+ */+ onSubmit: (name: string) => void;+ /**+ * The type of action being performed (like or comment).+ * Defaults to 'like'.+ */+ actionType?: "like" | "comment";+ /**+ * Called after the modal's exit animation completes.+ */+ onExited?: () => void;+}++/**+ * Modal dialog for adding a name when liking or commenting on a photo anonymously.+ */+export const AddNameModal: React.FC<AddNameModalProps> = ({+ open,+ onClose,+ onSubmit,+ actionType = "like",+ onExited,+}) => {+ const [name, setName] = useState("");+ const isComment = actionType === "comment";++ const handleSubmit = () => {+ if (name.trim()) {+ onSubmit(name.trim());+ setName("");+ }+ };++ const handleClose = () => {+ setName("");+ onClose();+ };++ return (+ <StyledDialog+ open={open}+ onClose={handleClose}+ slotProps={{ transition: { onExited } }}+ >+ <DialogWrapper>+ <CloseButton onClick={handleClose}>+ <CloseIcon sx={{ fontSize: 20 }} />+ </CloseButton>++ <ContentContainer>+ <IllustrationWrapper>+ {isComment ? (+ <CommentIllustration />+ ) : (+ <LikeIllustration />+ )}+ </IllustrationWrapper>++ <TitleSection>+ <Title>{t("set_your_name")}</Title>+ <Subtitle>{t("set_your_name_subtitle")}</Subtitle>+ </TitleSection>++ <StyledTextField+ fullWidth+ placeholder={t("name_placeholder")}+ variant="standard"+ value={name}+ onChange={(e) => setName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ handleSubmit();+ }+ }}+ autoFocus+ slotProps={{ htmlInput: { maxLength: 50 } }}+ />++ <SubmitButton+ variant="contained"+ fullWidth+ onClick={handleSubmit}+ hasName={!!name.trim()}+ >+ {isComment ? t("set_name") : t("set_name_and_like")}+ </SubmitButton>+ </ContentContainer>+ </DialogWrapper>+ </StyledDialog>+ );+};++// =============================================================================+// Styled Components+// =============================================================================++const StyledDialog = styled(Dialog)(({ theme }) => ({+ "& .MuiDialog-paper": {+ width: 381,+ maxWidth: "calc(100% - 32px)",+ borderRadius: 28,+ backgroundColor: "#fff",+ padding: 0,+ margin: 16,+ overflow: "visible",+ boxShadow: "none",+ border: "1px solid #E0E0E0",+ ...theme.applyStyles("dark", {+ backgroundColor: "#1b1b1b",+ border: "1px solid rgba(255, 255, 255, 0.18)",+ }),+ },+ "& .MuiBackdrop-root": { backgroundColor: "rgba(0, 0, 0, 0.5)" },+}));++const DialogWrapper = styled(Box)(() => ({+ position: "relative",+ padding: "48px 16px 16px 16px",+}));++const CloseButton = styled(IconButton)(({ theme }) => ({+ position: "absolute",+ top: 11,+ right: 12,+ backgroundColor: "#FAFAFA",+ color: "#000",+ padding: 10,+ "&:hover": { backgroundColor: "#F0F0F0" },+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.12)",+ color: "#fff",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.16)" },+ }),+}));++const ContentContainer = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 16,+}));++const IllustrationWrapper = styled(Box)(() => ({+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ marginBottom: 8,+}));++const TitleSection = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 9,+ textAlign: "center",+ marginBottom: 8,+}));++const Title = styled(Typography)(({ theme }) => ({+ fontWeight: 600,+ fontSize: 24,+ lineHeight: "28px",+ letterSpacing: "-0.48px",+ color: "#000",+ ...theme.applyStyles("dark", { color: "#fff" }),+}));++const Subtitle = styled(Typography)(({ theme }) => ({+ fontWeight: 500,+ fontSize: 14,+ lineHeight: "20px",+ color: "#666666",+ maxWidth: 295,+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.7)" }),+}));++const StyledTextField = styled(TextField)(({ theme }) => ({+ "& .MuiInput-root": {+ height: 54,+ backgroundColor: "#FAFAFA",+ borderRadius: 12,+ "&::before": { borderBottom: "1px solid #E0E0E0" },+ "&::after": { borderBottom: "2px solid #08C225" },+ "&:hover:not(.Mui-disabled)::before": {+ borderBottom: "1px solid #BDBDBD",+ },+ },+ "& .MuiInputBase-input": {+ padding: "0 16px",+ height: "100%",+ boxSizing: "border-box",+ fontSize: 16,+ color: "#000",+ "&::placeholder": { color: "#999", opacity: 1 },+ },+ ...theme.applyStyles("dark", {+ "& .MuiInput-root": {+ backgroundColor: "rgba(255, 255, 255, 0.08)",+ "&::before": { borderBottom: "1px solid rgba(255, 255, 255, 0.3)" },+ "&:hover:not(.Mui-disabled)::before": {+ borderBottom: "1px solid rgba(255, 255, 255, 0.5)",+ },+ },+ "& .MuiInputBase-input": {+ color: "#fff",+ "&::placeholder": { color: "rgba(255, 255, 255, 0.5)" },+ },+ }),+}));++const SubmitButton = styled(Button)<{ hasName: boolean }>(+ ({ hasName, theme }) => ({+ display: "flex",+ padding: "20px 16px",+ justifyContent: "center",+ alignItems: "center",+ gap: 8,+ flex: "1 0 0",+ borderRadius: 20,+ backgroundColor: hasName ? "#08C225" : "rgba(0, 0, 0, 0.04)",+ fontSize: 16,+ fontWeight: 500,+ textTransform: "none",+ color: hasName ? "#fff" : "#999",+ boxShadow: "none",+ "&:hover": {+ backgroundColor: hasName ? "#07A820" : "rgba(0, 0, 0, 0.08)",+ boxShadow: "none",+ },+ ...theme.applyStyles("dark", {+ backgroundColor: hasName ? "#08C225" : "rgba(255, 255, 255, 0.08)",+ color: hasName ? "#fff" : "rgba(255, 255, 255, 0.5)",+ "&:hover": {+ backgroundColor: hasName+ ? "#07A820"+ : "rgba(255, 255, 255, 0.12)",+ },+ }),+ }),+);diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/CommentsSidebar.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/CommentsSidebar.tsxnew file mode 100644index 0000000000..c26add8e5a--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/CommentsSidebar.tsx@@ -0,0 +1,2526 @@+import CloseIcon from "@mui/icons-material/Close";+import {+ Avatar,+ Box,+ CircularProgress,+ Drawer,+ IconButton,+ Menu,+ MenuItem,+ Stack,+ styled,+ TextField,+ Typography,+} from "@mui/material";+import { type ModalVisibilityProps } from "ente-base/components/utils/modal";+import type { PublicAlbumsCredentials } from "ente-base/http";+import log from "ente-base/log";+import { isOfficialAlbumsApp } from "ente-base/origins";+import { downloadManager } from "ente-gallery/services/download";+import { getAvatarColor } from "ente-gallery/utils/avatar-colors";+import type { EnteFile } from "ente-media/file";+import {+ addPublicComment,+ deletePublicComment,+} from "ente-new/albums/services/public-comment";+import {+ addPublicCommentReaction,+ createAnonIdentity,+ deletePublicReaction,+ getStoredAnonIdentity,+} from "ente-new/albums/services/public-reaction";+import { getCollectionByID } from "ente-new/photos/services/collection";+import type { CollectionSummaries } from "ente-new/photos/services/collection-summary";+import {+ addComment,+ deleteComment,+ type Comment,+} from "ente-new/photos/services/comment";+import {+ addCommentReaction,+ deleteReaction,+} from "ente-new/photos/services/reaction";+import { type UnifiedReaction } from "ente-new/photos/services/social";+import i18n, { t } from "i18next";+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { AddNameModal } from "./AddNameModal";+import { PublicCommentModal } from "./PublicCommentModal";+import { PublicLikeModal } from "./PublicLikeModal";++// =============================================================================+// Icons+// =============================================================================++const SendIcon: React.FC = () => (+ <svg+ width="18"+ height="16"+ viewBox="0 0 15 13"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M2.03872 4.50697L2.47372 5.26697C2.75072 5.75197 2.88872 5.99397 2.88872 6.25997C2.88872 6.52597 2.75072 6.76797 2.47372 7.25197L2.03872 8.01297C0.800717 10.18 0.181717 11.263 0.663717 11.801C1.14672 12.338 2.29072 11.838 4.57672 10.838L10.8527 8.09197C12.6477 7.30697 13.5457 6.91397 13.5457 6.25997C13.5457 5.60597 12.6477 5.21297 10.8527 4.42797L4.57672 1.68197C2.29072 0.681968 1.14672 0.181968 0.663717 0.718968C0.181717 1.25597 0.800717 2.33897 2.03872 4.50697Z"+ stroke="currentColor"+ />+ </svg>+);++const ReplyIcon: React.FC = () => (+ <svg+ width="12"+ height="9"+ viewBox="0 0 12 9"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M4.5241 0.242677C4.62341 0.34442 4.67919 0.482337 4.67919 0.626134C4.67919 0.76993 4.62341 0.907847 4.5241 1.00959L1.89369 3.70102H7.68483C8.3587 3.70102 9.35854 3.9036 10.2042 4.52653C11.0775 5.17045 11.7507 6.23762 11.7507 7.86116C11.7507 8.00507 11.6948 8.14309 11.5953 8.24485C11.4959 8.34661 11.361 8.40378 11.2203 8.40378C11.0797 8.40378 10.9448 8.34661 10.8453 8.24485C10.7459 8.14309 10.69 8.00507 10.69 7.86116C10.69 6.59069 10.1844 5.84982 9.58481 5.40776C8.95761 4.94544 8.18899 4.78627 7.68483 4.78627H1.89369L4.5241 7.4777C4.5762 7.52738 4.61799 7.58728 4.64698 7.65384C4.67597 7.72041 4.69155 7.79226 4.69281 7.86512C4.69406 7.93798 4.68096 8.01035 4.65429 8.07791C4.62762 8.14548 4.58792 8.20686 4.53756 8.25839C4.4872 8.30991 4.42722 8.35053 4.36118 8.37782C4.29515 8.40512 4.22442 8.41852 4.15321 8.41723C4.082 8.41595 4.01178 8.4 3.94673 8.37034C3.88167 8.34068 3.82313 8.29792 3.77457 8.24461L0.23908 4.6271C0.139767 4.52536 0.0839844 4.38744 0.0839844 4.24364C0.0839844 4.09985 0.139767 3.96193 0.23908 3.86019L3.77457 0.242677C3.87401 0.141061 4.0088 0.0839844 4.14934 0.0839844C4.28987 0.0839844 4.42466 0.141061 4.5241 0.242677Z"+ fill="currentColor"+ stroke="currentColor"+ strokeWidth="0.166667"+ />+ </svg>+);++interface HeartIconProps {+ filled?: boolean;+ small?: boolean;+}++const HeartIcon: React.FC<HeartIconProps> = ({ filled, small }) => (+ <svg+ width={small ? "13" : "16"}+ height={small ? "11" : "14"}+ viewBox="0 0 16 14"+ fill={filled ? "#08C225" : "none"}+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M6.63749 12.3742C4.66259 10.885 0.75 7.4804 0.75 4.41664C0.75 2.39161 2.22368 0.75 4.25 0.75C5.3 0.75 6.35 1.10294 7.75 2.51469C9.15 1.10294 10.2 0.75 11.25 0.75C13.2763 0.75 14.75 2.39161 14.75 4.41664C14.75 7.4804 10.8374 10.885 8.86251 12.3742C8.19793 12.8753 7.30207 12.8753 6.63749 12.3742Z"+ stroke={filled ? "#08C225" : "currentColor"}+ strokeWidth="1.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+);++const DeleteIcon: React.FC = () => (+ <svg+ width="13"+ height="15"+ viewBox="0 0 13 15"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M11.5 2.83203L11.0869 9.51543C10.9813 11.223 10.9285 12.0768 10.5005 12.6906C10.2889 12.9941 10.0165 13.2502 9.70047 13.4427C9.0614 13.832 8.206 13.832 6.49513 13.832C4.78208 13.832 3.92553 13.832 3.28603 13.442C2.96987 13.2492 2.69733 12.9926 2.48579 12.6886C2.05792 12.0738 2.0063 11.2188 1.90307 9.50883L1.5 2.83203M0.5 2.83333H12.5M9.2038 2.83333L8.74873 1.89449C8.4464 1.27084 8.2952 0.959013 8.03447 0.76454C7.97667 0.7214 7.9154 0.683027 7.85133 0.6498C7.5626 0.5 7.21607 0.5 6.523 0.5C5.81253 0.5 5.45733 0.5 5.16379 0.65608C5.09873 0.690673 5.03665 0.7306 4.97819 0.775447C4.71443 0.9778 4.56709 1.30103 4.27241 1.94751L3.86861 2.83333M4.83203 10.166V6.16602M8.16797 10.166V6.16602"+ stroke="currentColor"+ strokeLinecap="round"+ />+ </svg>+);++const ChevronDownIcon: React.FC = () => (+ <svg+ width="22"+ height="22"+ viewBox="0 0 20 20"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ style={{ marginLeft: -6, transform: "translateY(-2px)" }}+ >+ <path+ d="M10.0007 12.5004L6.46484 8.96544L7.64401 7.78711L10.0007 10.1438L12.3573 7.78711L13.5365 8.96544L10.0007 12.5004Z"+ fill="currentColor"+ />+ </svg>+);++const PersonIcon: React.FC = () => (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M12 12C14.21 12 16 10.21 16 8C16 5.79 14.21 4 12 4C9.79 4 8 5.79 8 8C8 10.21 9.79 12 12 12ZM12 14C9.33 14 4 15.34 4 18V20H20V18C20 15.34 14.67 14 12 14Z"+ fill="currentColor"+ />+ </svg>+);++// =============================================================================+// Types+// =============================================================================++/** Collection info for the dropdown. */+interface CollectionInfo {+ id: number;+ name: string;+ commentCount: number;+ coverFile?: EnteFile;+}++// =============================================================================+// Utility Functions+// =============================================================================++const formatTimeAgo = (timestampMicros: number): string => {+ // Server timestamps are in microseconds, convert to milliseconds+ const timestampMs = Math.floor(timestampMicros / 1000);+ const now = Date.now();+ const diff = now - timestampMs;+ const minutes = Math.floor(diff / 60000);+ if (minutes < 1) return t("just_now");+ if (minutes < 60) return t("minutes_ago", { count: minutes });+ const hours = Math.floor(minutes / 60);+ if (hours < 24) return t("hours_ago", { count: hours });+ const days = Math.floor(hours / 24);+ if (days < 7) return t("days_ago", { count: days });++ // For 7+ days, show actual date using locale-aware formatting+ const date = new Date(timestampMs);+ const currentYear = new Date(now).getFullYear();+ const locale = i18n.language;+ if (date.getFullYear() === currentYear) {+ return date.toLocaleDateString(locale, {+ month: "short",+ day: "numeric",+ });+ }+ return date.toLocaleDateString(locale, {+ month: "short",+ day: "numeric",+ year: "numeric",+ });+};++const getParentComment = (+ parentID: string | undefined,+ comments: Comment[],+): Comment | undefined => {+ if (!parentID) return undefined;+ return comments.find((c) => c.id === parentID);+};++/**+ * Truncates comment text to first 100 characters of the first line.+ * Adds "..." if multiline or if first line exceeds 100 chars.+ */+const truncateCommentText = (text: string): string => {+ const lines = text.split("\n");+ const firstLine = lines[0] ?? text;+ const isMultiline = lines.length > 1;+ if (firstLine.length > 100) {+ return firstLine.slice(0, 100) + "...";+ }+ return isMultiline ? firstLine + "..." : firstLine;+};++// =============================================================================+// Shared Comment Components+// =============================================================================++interface CommentHeaderProps {+ userName: string;+ timestamp: number;+ avatarSize?: number;+ isMaskedEmail?: boolean;+ /** Key used for computing avatar color (e.g., anonUserID for anonymous users). */+ avatarColorKey?: string;+}++/**+ * Header component showing avatar, username, and timestamp.+ * Used consistently for both root comments and replies.+ */+const CommentHeader: React.FC<CommentHeaderProps> = ({+ userName,+ timestamp,+ avatarSize = 32,+ isMaskedEmail,+ avatarColorKey,+}) => (+ <CommentHeaderContainer>+ <Avatar+ sx={{+ width: avatarSize,+ height: avatarSize,+ fontSize: 14,+ bgcolor: getAvatarColor(avatarColorKey ?? userName),+ color: "#fff",+ }}+ >+ {isMaskedEmail ? <PersonIcon /> : userName[0]?.toUpperCase()}+ </Avatar>+ <UserName>{userName}</UserName>+ <Separator>•</Separator>+ <Timestamp>{formatTimeAgo(timestamp)}</Timestamp>+ </CommentHeaderContainer>+);++interface QuotedReplyProps {+ parentComment: Comment;+ isOwn: boolean;+ currentUserID?: number;+ userIDToEmail?: Map<number, string>;+ anonUserNames?: Map<string, string>;+ currentAnonUserID?: string;+}++/**+ * Shows the quoted parent comment inside a reply bubble.+ */+const QuotedReply: React.FC<QuotedReplyProps> = ({+ parentComment,+ isOwn,+ currentUserID,+ userIDToEmail,+ anonUserNames,+ currentAnonUserID,+}) => {+ // Get the author name+ const getAuthorName = (): string => {+ // Check if this is the current user (logged in or anonymous)+ if (parentComment.userID === currentUserID) {+ return t("you");+ }+ if (+ parentComment.anonUserID &&+ parentComment.anonUserID === currentAnonUserID+ ) {+ return t("you");+ }++ // For anonymous users, look up in anonUserNames+ if (parentComment.anonUserID) {+ return (+ anonUserNames?.get(parentComment.anonUserID) ??+ `${t("anonymous")} ${parentComment.anonUserID.slice(-4)}`+ );+ }++ // For registered users, look up email+ const email = userIDToEmail?.get(parentComment.userID);+ return email ?? t("user");+ };++ return (+ <QuotedReplyContainer isOwn={isOwn}>+ <Typography+ sx={(theme) => ({+ fontWeight: 600,+ fontSize: 12,+ color: isOwn ? "rgba(255,255,255,0.9)" : "#666",+ ...(!isOwn &&+ theme.applyStyles("dark", {+ color: "rgba(255, 255, 255, 0.7)",+ })),+ })}+ >+ {getAuthorName()}+ </Typography>+ {parentComment.isDeleted ? (+ <Typography+ sx={(theme) => ({+ fontSize: 12,+ fontStyle: "italic",+ color: isOwn ? "rgba(255,255,255,0.8)" : "#888",+ ...(!isOwn &&+ theme.applyStyles("dark", {+ color: "rgba(255, 255, 255, 0.5)",+ })),+ })}+ >+ (deleted)+ </Typography>+ ) : (+ <Typography+ sx={(theme) => ({+ fontSize: 12,+ color: isOwn ? "rgba(255,255,255,0.8)" : "#888",+ ...(!isOwn &&+ theme.applyStyles("dark", {+ color: "rgba(255, 255, 255, 0.5)",+ })),+ })}+ >+ {truncateCommentText(parentComment.text)}+ </Typography>+ )}+ </QuotedReplyContainer>+ );+};++// =============================================================================+// Main Component+// =============================================================================++export interface CommentsSidebarProps extends ModalVisibilityProps {+ /**+ * The file whose comments are being displayed.+ */+ file?: EnteFile;+ /**+ * The currently active collection ID (when viewing from within a collection).+ */+ activeCollectionID?: number;+ /**+ * A mapping from file IDs to the IDs of collections they belong to.+ */+ fileNormalCollectionIDs?: Map<number, number[]>;+ /**+ * Collection summaries indexed by their IDs.+ */+ collectionSummaries?: CollectionSummaries;+ /**+ * The current user's ID.+ */+ currentUserID?: number;+ /**+ * Pre-fetched comments by collection ID.+ */+ prefetchedComments?: Map<number, Comment[]>;+ /**+ * Pre-fetched reactions by collection ID (includes both file and comment reactions).+ */+ prefetchedReactions?: Map<number, UnifiedReaction[]>;+ /**+ * Pre-fetched user ID to email mapping.+ */+ prefetchedUserIDToEmail?: Map<number, string>;+ /**+ * Called when a comment is successfully added. The parent should update its+ * comments state to include this new comment.+ */+ onCommentAdded?: (comment: Comment) => void;+ /**+ * Called when a comment is successfully deleted. The parent should update its+ * comments state to mark this comment as deleted.+ */+ onCommentDeleted?: (collectionID: number, commentID: string) => void;+ /**+ * Called when a comment reaction is added. The parent should update its+ * reactions state to include this new reaction.+ */+ onCommentReactionAdded?: (reaction: UnifiedReaction) => void;+ /**+ * Called when a comment reaction is deleted. The parent should update its+ * reactions state to remove this reaction.+ */+ onCommentReactionDeleted?: (+ collectionID: number,+ reactionID: string,+ ) => void;+ /**+ * If set, the sidebar will scroll to and highlight this comment.+ */+ highlightCommentID?: string;+ /**+ * Public album credentials for anonymous commenting.+ * Required when viewing a public album (no logged in user).+ */+ publicAlbumsCredentials?: PublicAlbumsCredentials;+ /**+ * The decrypted collection key (base64 encoded) for encrypting comments.+ * Required when viewing a public album (no logged in user).+ */+ collectionKey?: string;+ /**+ * Map of anonymous user ID to decrypted user name.+ */+ anonUserNames?: Map<string, string>;+ /**+ * Called when user clicks "Join album to like" in the public like modal.+ * Should trigger the join album flow (with mobile deep link fallback).+ */+ onJoinAlbum?: () => void;+ /**+ * Whether the "Join album" option is enabled for this public link.+ * When false, the "Join album and like/comment" buttons will be hidden.+ */+ enableJoin?: boolean;+}++/**+ * A sidebar panel for displaying and managing comments on a file.+ */+interface ContextMenuState {+ comment: Comment;+ anchorEl: HTMLElement;+ isLiked: boolean;+}++export const CommentsSidebar: React.FC<CommentsSidebarProps> = ({+ open,+ onClose,+ file,+ activeCollectionID,+ fileNormalCollectionIDs,+ collectionSummaries,+ currentUserID,+ prefetchedComments,+ prefetchedReactions,+ prefetchedUserIDToEmail,+ onCommentAdded,+ onCommentDeleted,+ onCommentReactionAdded,+ onCommentReactionDeleted,+ highlightCommentID,+ publicAlbumsCredentials,+ collectionKey,+ anonUserNames,+ onJoinAlbum,+ enableJoin = true,+}) => {+ const [commentText, setCommentText] = useState("");+ const [replyingTo, setReplyingTo] = useState<Comment | null>(null);+ const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(+ null,+ );+ const [collectionDropdownOpen, setCollectionDropdownOpen] = useState(false);+ const [comments, setComments] = useState<Comment[]>([]);+ const [showPublicCommentModal, setShowPublicCommentModal] = useState(false);+ const [showAddNameModal, setShowAddNameModal] = useState(false);+ const [showPublicLikeModal, setShowPublicLikeModal] = useState(false);+ const [pendingCommentLike, setPendingCommentLike] =+ useState<Comment | null>(null);+ /** Tracks whether the AddNameModal was triggered by a comment like action */+ const [addNameForCommentLike, setAddNameForCommentLike] = useState(false);+ /** Tracks whether the user has set up their anonymous identity for commenting */+ const [hasAnonIdentity, setHasAnonIdentity] = useState(false);+ const [loading, setLoading] = useState(false);+ const [sending, setSending] = useState(false);+ const hasLoadedRef = useRef(false);+ const inputRef = useRef<HTMLInputElement>(null);+ const commentsContainerRef = useRef<HTMLDivElement>(null);+ // Ref to preserve isLiked state during context menu close animation+ const contextMenuIsLikedRef = useRef(false);++ // Comments grouped by collection: collectionID -> comments+ const [commentsByCollection, setCommentsByCollection] = useState<+ Map<number, Comment[]>+ >(new Map());++ // Selected collection for viewing comments (when in gallery view)+ const [selectedCollectionID, setSelectedCollectionID] = useState<+ number | undefined+ >(undefined);++ // Thumbnail URLs for each collection's cover file: collectionID -> URL+ const [thumbnailURLs, setThumbnailURLs] = useState<Map<number, string>>(+ new Map(),+ );++ // Comment reactions: commentID -> reactionID (for current user's likes)+ const [likedComments, setLikedComments] = useState<Map<string, string>>(+ new Map(),+ );++ // All reactions by collection: collectionID -> reactions array+ const [reactionsByCollection, setReactionsByCollection] = useState<+ Map<number, UnifiedReaction[]>+ >(new Map());++ // Track whether we've scrolled to the highlight comment for this open+ const hasScrolledToHighlightRef = useRef(false);++ // Focus input when replying to a comment+ useEffect(() => {+ if (replyingTo && inputRef.current) {+ inputRef.current.focus();+ }+ }, [replyingTo]);++ // Reset tracking refs when sidebar closes+ useEffect(() => {+ if (!open) {+ hasScrolledToHighlightRef.current = false;+ hasLoadedRef.current = false;+ }+ }, [open]);++ // Scroll to and highlight the target comment when opening from feed+ useEffect(() => {+ if (+ !open ||+ !highlightCommentID ||+ hasScrolledToHighlightRef.current ||+ !commentsContainerRef.current ||+ loading ||+ comments.length === 0+ ) {+ return;+ }++ let highlightTimeout: ReturnType<typeof setTimeout> | undefined;+ let fadeTimeout: ReturnType<typeof setTimeout> | undefined;+ let cleanupTimeout: ReturnType<typeof setTimeout> | undefined;+ let blinkInterval: ReturnType<typeof setInterval> | undefined;++ // Wait for DOM to update after comments state change+ const initialTimeout = setTimeout(() => {+ const commentWrapper = commentsContainerRef.current?.querySelector(+ `[data-comment-id="${highlightCommentID}"]`,+ );+ if (commentWrapper) {+ hasScrolledToHighlightRef.current = true;++ // Scroll to the comment+ commentWrapper.scrollIntoView({+ behavior: "smooth",+ block: "center",+ });++ // Find the bubble element inside the wrapper+ const bubbleElement = commentWrapper.querySelector<HTMLElement>(+ "[data-comment-bubble]",+ );++ if (bubbleElement) {+ // Wait for scroll to mostly complete, then apply blink highlight+ highlightTimeout = setTimeout(() => {+ const computedStyle = getComputedStyle(bubbleElement);+ const originalBg = computedStyle.backgroundColor;++ // Parse the RGB values to create 80% opacity version+ const rgbMatch = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(+ originalBg,+ );+ if (!rgbMatch) return;++ const [, r, g, b] = rgbMatch;+ const dimmedBg = `rgba(${r}, ${g}, ${b}, 0.6)`;++ bubbleElement.style.transition =+ "background-color 0.2s ease-in-out";++ let isDimmed = false;+ blinkInterval = setInterval(() => {+ isDimmed = !isDimmed;+ bubbleElement.style.backgroundColor = isDimmed+ ? dimmedBg+ : originalBg;+ }, 300);++ // Stop blinking after 1.5 seconds+ fadeTimeout = setTimeout(() => {+ if (blinkInterval) clearInterval(blinkInterval);+ bubbleElement.style.backgroundColor = originalBg;++ // Clean up transition style+ cleanupTimeout = setTimeout(() => {+ bubbleElement.style.transition = "";+ bubbleElement.style.backgroundColor = "";+ }, 200);+ }, 1500);+ }, 400);+ }+ }+ }, 100);++ return () => {+ clearTimeout(initialTimeout);+ if (highlightTimeout) clearTimeout(highlightTimeout);+ if (fadeTimeout) clearTimeout(fadeTimeout);+ if (cleanupTimeout) clearTimeout(cleanupTimeout);+ if (blinkInterval) clearInterval(blinkInterval);+ };+ }, [open, highlightCommentID, loading, comments]);++ // Reset state when the file changes to avoid showing stale data+ useEffect(() => {+ setSelectedCollectionID(undefined);+ setComments([]);+ setCommentsByCollection(new Map());+ setReactionsByCollection(new Map());+ setLikedComments(new Map());+ hasLoadedRef.current = false;+ }, [file?.id]);++ // Check if opened from a collection context+ const hasCollectionContext =+ activeCollectionID !== undefined && activeCollectionID !== 0;++ // Get all collections the file belongs to+ const fileCollectionIDs = useMemo(() => {+ if (!file) return [];+ return fileNormalCollectionIDs?.get(file.id) ?? [];+ }, [file, fileNormalCollectionIDs]);++ // Check if this is a public album+ const isPublicAlbum = isOfficialAlbumsApp || !!publicAlbumsCredentials;++ // Build collection info list with comment counts and cover files (shared albums only)+ const collectionsInfo = useMemo((): CollectionInfo[] => {+ // For public albums, use the file's collection directly+ if (isPublicAlbum && file) {+ return [+ {+ id: file.collectionID,+ name: "Album",+ commentCount:+ commentsByCollection+ .get(file.collectionID)+ ?.filter((c) => !c.isDeleted).length ?? 0,+ coverFile: file,+ },+ ];+ }++ return fileCollectionIDs+ .filter((collectionID) =>+ collectionSummaries+ ?.get(collectionID)+ ?.attributes.has("shared"),+ )+ .map((collectionID) => {+ const summary = collectionSummaries?.get(collectionID);+ return {+ id: collectionID,+ name: summary?.name ?? `Album ${collectionID}`,+ commentCount:+ commentsByCollection+ .get(collectionID)+ ?.filter((c) => !c.isDeleted).length ?? 0,+ coverFile: summary?.coverFile,+ };+ });+ }, [+ isPublicAlbum,+ file,+ fileCollectionIDs,+ collectionSummaries,+ commentsByCollection,+ ]);++ // Collections sorted by comment count (descending) for dropdown+ const sortedCollectionsInfo = useMemo(() => {+ return [...collectionsInfo].sort(+ (a, b) => b.commentCount - a.commentCount,+ );+ }, [collectionsInfo]);++ // Currently selected collection info+ const selectedCollectionInfo = useMemo(() => {+ const targetID = hasCollectionContext+ ? activeCollectionID+ : selectedCollectionID;+ return (+ collectionsInfo.find((c) => c.id === targetID) ??+ sortedCollectionsInfo[0]+ );+ }, [+ hasCollectionContext,+ activeCollectionID,+ selectedCollectionID,+ collectionsInfo,+ sortedCollectionsInfo,+ ]);++ // Check if the current user can delete a given comment.+ // User can delete if: they authored the comment, OR they are owner/admin of the collection.+ const canDeleteComment = useCallback(+ (comment: Comment): boolean => {+ // Comment author can always delete their own comment+ // For logged-in users, check userID+ if (comment.userID === currentUserID) {+ return true;+ }+ // For anonymous users, check anonUserID+ if (selectedCollectionInfo) {+ const storedIdentity = getStoredAnonIdentity(+ selectedCollectionInfo.id,+ );+ if (+ storedIdentity &&+ comment.anonUserID === storedIdentity.anonUserID+ ) {+ return true;+ }+ }++ // Check if user is owner or admin of the selected collection+ const collectionID = selectedCollectionInfo?.id;+ if (!collectionID || !collectionSummaries) {+ return false;+ }++ const summary = collectionSummaries.get(collectionID);+ if (!summary) {+ return false;+ }++ // User is owner (not sharedIncoming) or admin (sharedIncomingAdmin)+ return (+ !summary.attributes.has("sharedIncoming") ||+ summary.attributes.has("sharedIncomingAdmin")+ );+ },+ [currentUserID, selectedCollectionInfo, collectionSummaries],+ );++ // Load comments and reactions from prefetched data.+ const loadComments = useCallback(() => {+ if (!file || !open || !prefetchedComments) return;++ // Only show loading spinner on initial load, not during polling refresh+ const isInitialLoad = !hasLoadedRef.current;+ if (isInitialLoad) {+ setLoading(true);+ }++ try {+ // Use prefetched data+ setCommentsByCollection(prefetchedComments);+ setReactionsByCollection(prefetchedReactions ?? new Map());++ // Set comments for the currently selected collection+ if (hasCollectionContext && activeCollectionID) {+ const activeComments =+ prefetchedComments.get(activeCollectionID) ?? [];+ setComments(activeComments);+ } else {+ // For gallery view, only auto-select on initial load.+ // Use functional update to check current selection without+ // adding selectedCollectionID as a dependency.+ setSelectedCollectionID((currentSelection) => {+ if (currentSelection !== undefined) {+ // Already have a selection, don't change it.+ // The useEffect that watches selectedCollectionID will+ // update the displayed comments.+ return currentSelection;+ }++ // Initial selection: find collection with most comments+ // Only consider shared collections (non-shared ones won't appear in the UI)+ // For public albums, skip the shared check since there's no collectionSummaries+ let maxCount = -1;+ let bestCollectionID: number | undefined;+ for (const [+ collectionID,+ collectionComments,+ ] of prefetchedComments) {+ // Skip non-shared collections (except for public albums)+ if (!isPublicAlbum) {+ const isShared = collectionSummaries+ ?.get(collectionID)+ ?.attributes.has("shared");+ if (!isShared) continue;+ }++ const count = collectionComments.filter(+ (c) => !c.isDeleted,+ ).length;+ if (count > maxCount) {+ maxCount = count;+ bestCollectionID = collectionID;+ }+ }+ if (bestCollectionID !== undefined) {+ setComments(+ prefetchedComments.get(bestCollectionID) ?? [],+ );+ }+ return bestCollectionID;+ });+ }+ } catch (e) {+ log.error("Failed to load comments", e);+ } finally {+ if (isInitialLoad) {+ hasLoadedRef.current = true;+ setLoading(false);+ }+ }+ }, [+ file,+ open,+ prefetchedComments,+ prefetchedReactions,+ hasCollectionContext,+ activeCollectionID,+ collectionSummaries,+ isPublicAlbum,+ ]);++ // Load comments when the sidebar opens+ useEffect(() => {+ if (open) {+ loadComments();+ }+ }, [open, loadComments]);++ // Set initial selected collection to the one with most comments (gallery view)+ useEffect(() => {+ if (+ open &&+ !hasCollectionContext &&+ selectedCollectionID === undefined &&+ commentsByCollection.size > 0+ ) {+ // Find the collection with the most comments+ // Only consider shared collections (non-shared ones won't appear in the UI)+ // For public albums, skip the shared check since there's no collectionSummaries+ let maxCount = -1;+ let bestCollectionID: number | undefined;+ for (const [+ collectionID,+ collectionComments,+ ] of commentsByCollection) {+ // Skip non-shared collections (except for public albums)+ if (!isPublicAlbum) {+ const isShared = collectionSummaries+ ?.get(collectionID)+ ?.attributes.has("shared");+ if (!isShared) continue;+ }++ const count = collectionComments.filter(+ (c) => !c.isDeleted,+ ).length;+ if (count > maxCount) {+ maxCount = count;+ bestCollectionID = collectionID;+ }+ }+ if (bestCollectionID !== undefined) {+ setSelectedCollectionID(bestCollectionID);+ }+ }+ }, [+ open,+ hasCollectionContext,+ selectedCollectionID,+ commentsByCollection,+ collectionSummaries,+ isPublicAlbum,+ ]);++ // Update displayed comments when selected collection changes (gallery view)+ useEffect(() => {+ if (!hasCollectionContext && selectedCollectionID !== undefined) {+ const collectionComments =+ commentsByCollection.get(selectedCollectionID) ?? [];+ setComments(collectionComments);+ }+ }, [hasCollectionContext, selectedCollectionID, commentsByCollection]);++ // Update hasAnonIdentity when collection changes (for public albums)+ useEffect(() => {+ if (isPublicAlbum && selectedCollectionInfo) {+ const storedIdentity = getStoredAnonIdentity(+ selectedCollectionInfo.id,+ );+ setHasAnonIdentity(!!storedIdentity);+ }+ }, [isPublicAlbum, selectedCollectionInfo]);++ // Fetch thumbnails for each collection's cover file+ useEffect(() => {+ if (!open || collectionsInfo.length === 0) {+ return;+ }++ let didCancel = false;++ const fetchThumbnails = async () => {+ const urls = new Map<number, string>();+ for (const collection of collectionsInfo) {+ if (collection.coverFile) {+ try {+ const url =+ await downloadManager.renderableThumbnailURL(+ collection.coverFile,+ );+ if (!didCancel && url) {+ urls.set(collection.id, url);+ }+ } catch (e) {+ log.warn(+ `Failed to fetch thumbnail for collection ${collection.id}`,+ e,+ );+ }+ }+ }+ if (!didCancel) {+ setThumbnailURLs(urls);+ }+ };++ void fetchThumbnails();++ return () => {+ didCancel = true;+ };+ }, [open, collectionsInfo]);++ // Build liked comments map from reactions when selected collection changes+ useEffect(() => {+ // Don't reset state on close - preserves UI during exit animation+ if (!open) return;+ if (!selectedCollectionInfo) {+ setLikedComments(new Map());+ return;+ }++ const reactions = reactionsByCollection.get(selectedCollectionInfo.id);+ if (!reactions) {+ setLikedComments(new Map());+ return;+ }++ // Get stored anon identity for public albums+ const storedIdentity = isPublicAlbum+ ? getStoredAnonIdentity(selectedCollectionInfo.id)+ : undefined;++ // Find comment reactions that are likes from the current user (or anon user)+ const newLikedComments = new Map<string, string>();+ for (const reaction of reactions) {+ if (reaction.commentID && reaction.reactionType === "green_heart") {+ // Check if this is the current user's reaction+ const isCurrentUserReaction =+ reaction.userID === currentUserID ||+ (storedIdentity &&+ reaction.anonUserID === storedIdentity.anonUserID);+ if (isCurrentUserReaction) {+ newLikedComments.set(reaction.commentID, reaction.id);+ }+ }+ }+ setLikedComments(newLikedComments);+ }, [+ open,+ selectedCollectionInfo,+ reactionsByCollection,+ currentUserID,+ isPublicAlbum,+ ]);++ const handleSend = async () => {+ if (!commentText.trim() || !file || !selectedCollectionInfo) return;++ // For public albums, check if we already have an anon identity+ if (isPublicAlbum) {+ const storedIdentity = getStoredAnonIdentity(+ selectedCollectionInfo.id,+ );+ if (storedIdentity && publicAlbumsCredentials && collectionKey) {+ // User already has identity, send directly+ await sendPublicComment(commentText.trim());+ } else {+ // Show modal to choose anonymous or join album+ setShowPublicCommentModal(true);+ }+ return;+ }++ // For authenticated users, send via API+ const text = commentText.trim();+ const collectionID = selectedCollectionInfo.id;++ setSending(true);+ try {+ const collection = await getCollectionByID(collectionID);++ const newCommentID = await addComment(+ collectionID,+ file.id,+ text,+ collection.key,+ replyingTo?.id,+ );++ // Add the new comment to local state+ const newComment: Comment = {+ id: newCommentID,+ collectionID,+ fileID: file.id,+ text,+ parentCommentID: replyingTo?.id,+ isDeleted: false,+ userID: currentUserID ?? 0,+ createdAt: Date.now() * 1000, // Microseconds to match server format+ updatedAt: Date.now() * 1000,+ };+ setComments((prev) => [...prev, newComment]);+ setCommentsByCollection((prev) => {+ const next = new Map(prev);+ const existing = next.get(collectionID) ?? [];+ next.set(collectionID, [...existing, newComment]);+ return next;+ });++ setCommentText("");+ setReplyingTo(null);++ // Notify parent to update its comments state+ onCommentAdded?.(newComment);++ // Scroll to bottom after adding comment+ setTimeout(() => {+ if (commentsContainerRef.current) {+ commentsContainerRef.current.scrollTop = 0;+ }+ }, 0);+ } catch (e) {+ log.error("Failed to add comment", e);+ } finally {+ setSending(false);+ }+ };++ /**+ * Send a comment to the public album API using stored anonymous identity.+ */+ const sendPublicComment = async (text: string) => {+ if (+ !file ||+ !selectedCollectionInfo ||+ !publicAlbumsCredentials ||+ !collectionKey+ ) {+ return;+ }++ const collectionID = selectedCollectionInfo.id;+ const storedIdentity = getStoredAnonIdentity(collectionID);+ if (!storedIdentity) {+ log.error("No stored identity for public comment");+ return;+ }++ setSending(true);+ try {+ const newCommentID = await addPublicComment(+ publicAlbumsCredentials,+ collectionID,+ file.id,+ text,+ collectionKey,+ replyingTo?.id,+ storedIdentity,+ );++ // Add the new comment to local state+ const newComment: Comment = {+ id: newCommentID,+ collectionID,+ fileID: file.id,+ text,+ parentCommentID: replyingTo?.id,+ isDeleted: false,+ userID: 0, // Anonymous user+ anonUserID: storedIdentity.anonUserID,+ createdAt: Date.now() * 1000, // Microseconds to match server format+ updatedAt: Date.now() * 1000,+ };+ setComments((prev) => [...prev, newComment]);+ setCommentsByCollection((prev) => {+ const next = new Map(prev);+ const existing = next.get(collectionID) ?? [];+ next.set(collectionID, [...existing, newComment]);+ return next;+ });++ setCommentText("");+ setReplyingTo(null);++ // Notify parent to update its comments state+ onCommentAdded?.(newComment);++ // Scroll to bottom after adding comment+ setTimeout(() => {+ if (commentsContainerRef.current) {+ commentsContainerRef.current.scrollTop = 0;+ }+ }, 0);+ } catch (e) {+ log.error("Failed to add public comment", e);+ } finally {+ setSending(false);+ }+ };++ const handleCommentAnonymously = () => {+ setShowPublicCommentModal(false);+ setShowAddNameModal(true);+ };++ const handleJoinAlbumToComment = () => {+ setShowPublicCommentModal(false);+ onJoinAlbum?.();+ };++ const handleLikeAnonymously = () => {+ setShowPublicLikeModal(false);+ setAddNameForCommentLike(true);+ setShowAddNameModal(true);+ };++ const handleJoinAlbumToLike = () => {+ setShowPublicLikeModal(false);+ setPendingCommentLike(null);+ onJoinAlbum?.();+ };++ const handleNameSubmit = async (name: string) => {+ setShowAddNameModal(false);++ if (+ !selectedCollectionInfo ||+ !publicAlbumsCredentials ||+ !collectionKey+ ) {+ setPendingCommentLike(null);+ setAddNameForCommentLike(false);+ return;+ }++ const collectionID = selectedCollectionInfo.id;++ // Check if this is for a comment like action+ if (addNameForCommentLike && pendingCommentLike) {+ try {+ // Create anonymous identity with the provided name+ const identity = await createAnonIdentity(+ publicAlbumsCredentials,+ collectionID,+ name,+ collectionKey,+ );++ // Now like the comment using the new identity+ const reactionID = await addPublicCommentReaction(+ publicAlbumsCredentials,+ collectionID,+ pendingCommentLike.id,+ "green_heart",+ collectionKey,+ identity,+ pendingCommentLike.fileID,+ );+ const newReaction: UnifiedReaction = {+ id: reactionID,+ collectionID,+ commentID: pendingCommentLike.id,+ reactionType: "green_heart",+ userID: 0,+ anonUserID: identity.anonUserID,+ isDeleted: false,+ createdAt: Date.now() * 1000,+ updatedAt: Date.now() * 1000,+ };+ setLikedComments((prev) => {+ const next = new Map(prev);+ next.set(pendingCommentLike.id, reactionID);+ return next;+ });+ setReactionsByCollection((prev) => {+ const next = new Map(prev);+ const reactions = next.get(collectionID) ?? [];+ next.set(collectionID, [...reactions, newReaction]);+ return next;+ });+ onCommentReactionAdded?.(newReaction);+ setHasAnonIdentity(true);+ } catch (e) {+ log.error("Failed to create identity and like comment", e);+ } finally {+ setPendingCommentLike(null);+ setAddNameForCommentLike(false);+ }+ return;+ }++ // Handle comment action - just create identity, don't send comment+ // User will type and send the comment afterwards+ try {+ await createAnonIdentity(+ publicAlbumsCredentials,+ collectionID,+ name,+ collectionKey,+ );+ // Identity created, user can now type and send comments+ setHasAnonIdentity(true);+ } catch (e) {+ log.error("Failed to create anonymous identity", e);+ }+ };++ // Check if user needs to set up identity before commenting (public album without identity)+ const needsIdentityToComment =+ isPublicAlbum && selectedCollectionInfo && !hasAnonIdentity;++ const handleReply = (commentToReply: Comment) => {+ setReplyingTo(commentToReply);++ // For public albums, check if we have an identity+ if (needsIdentityToComment) {+ setShowPublicCommentModal(true);+ }+ };++ // Handler for clicking the comment input area on public albums+ const handleInputClick = () => {+ if (needsIdentityToComment) {+ setShowPublicCommentModal(true);+ }+ };++ // Handler for keydown: Enter to send, Shift+Enter for new line+ const handleCommentKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ void handleSend();+ }+ };++ const handleCollectionSelect = (collectionID: number) => {+ setSelectedCollectionID(collectionID);+ setCollectionDropdownOpen(false);+ };++ const handleContextMenu = (+ e: React.MouseEvent,+ targetComment: Comment,+ bubbleElement: HTMLElement,+ ) => {+ const selection = window.getSelection();+ if (selection && selection.toString().length > 0) {+ return;+ }+ e.preventDefault();+ const isLiked = likedComments.has(targetComment.id);+ contextMenuIsLikedRef.current = isLiked;+ setContextMenu({+ comment: targetComment,+ anchorEl: bubbleElement,+ isLiked,+ });+ };++ const handleCloseContextMenu = () => {+ setContextMenu(null);+ };++ const handleLikeComment = async (targetComment: Comment) => {+ if (!selectedCollectionInfo) return;++ const collectionID = selectedCollectionInfo.id;+ const existingReactionID = likedComments.get(targetComment.id);++ try {+ if (isPublicAlbum) {+ // Public album - use public APIs+ if (!publicAlbumsCredentials || !collectionKey) {+ log.error(+ "Missing credentials for public album comment like",+ );+ return;+ }++ const storedIdentity = getStoredAnonIdentity(collectionID);+ if (!storedIdentity) {+ // No identity - show modal to set name+ setPendingCommentLike(targetComment);+ setShowPublicLikeModal(true);+ return;+ }++ if (existingReactionID) {+ // Unlike - delete the reaction+ await deletePublicReaction(+ publicAlbumsCredentials,+ collectionID,+ existingReactionID,+ storedIdentity,+ );+ setLikedComments((prev) => {+ const next = new Map(prev);+ next.delete(targetComment.id);+ return next;+ });+ setReactionsByCollection((prev) => {+ const next = new Map(prev);+ const reactions = next.get(collectionID) ?? [];+ next.set(+ collectionID,+ reactions.filter(+ (r) => r.id !== existingReactionID,+ ),+ );+ return next;+ });+ onCommentReactionDeleted?.(+ collectionID,+ existingReactionID,+ );+ } else {+ // Like - add a reaction+ const reactionID = await addPublicCommentReaction(+ publicAlbumsCredentials,+ collectionID,+ targetComment.id,+ "green_heart",+ collectionKey,+ storedIdentity,+ targetComment.fileID,+ );+ const newReaction: UnifiedReaction = {+ id: reactionID,+ collectionID,+ commentID: targetComment.id,+ reactionType: "green_heart",+ userID: 0,+ anonUserID: storedIdentity.anonUserID,+ isDeleted: false,+ createdAt: Date.now() * 1000,+ updatedAt: Date.now() * 1000,+ };+ setLikedComments((prev) => {+ const next = new Map(prev);+ next.set(targetComment.id, reactionID);+ return next;+ });+ setReactionsByCollection((prev) => {+ const next = new Map(prev);+ const reactions = next.get(collectionID) ?? [];+ next.set(collectionID, [...reactions, newReaction]);+ return next;+ });+ onCommentReactionAdded?.(newReaction);+ }+ } else {+ // Authenticated user - use regular APIs+ const collection = await getCollectionByID(collectionID);++ if (existingReactionID) {+ // Unlike - delete the reaction+ await deleteReaction(existingReactionID);+ setLikedComments((prev) => {+ const next = new Map(prev);+ next.delete(targetComment.id);+ return next;+ });+ setReactionsByCollection((prev) => {+ const next = new Map(prev);+ const reactions = next.get(collectionID) ?? [];+ next.set(+ collectionID,+ reactions.filter(+ (r) => r.id !== existingReactionID,+ ),+ );+ return next;+ });+ onCommentReactionDeleted?.(+ collectionID,+ existingReactionID,+ );+ } else {+ // Like - add a reaction+ const reactionID = await addCommentReaction(+ collectionID,+ targetComment.id,+ "green_heart",+ collection.key,+ targetComment.fileID,+ );+ const newReaction: UnifiedReaction = {+ id: reactionID,+ collectionID,+ commentID: targetComment.id,+ reactionType: "green_heart",+ userID: currentUserID ?? 0,+ isDeleted: false,+ createdAt: Date.now() * 1000,+ updatedAt: Date.now() * 1000,+ };+ setLikedComments((prev) => {+ const next = new Map(prev);+ next.set(targetComment.id, reactionID);+ return next;+ });+ setReactionsByCollection((prev) => {+ const next = new Map(prev);+ const reactions = next.get(collectionID) ?? [];+ next.set(collectionID, [...reactions, newReaction]);+ return next;+ });+ onCommentReactionAdded?.(newReaction);+ }+ }+ } catch (e) {+ log.error("Failed to toggle comment like", e);+ }+ };++ const handleContextMenuAction = async (+ action: "like" | "reply" | "delete",+ ) => {+ if (!contextMenu || !selectedCollectionInfo) return;+ const targetComment = contextMenu.comment;+ setContextMenu(null);++ switch (action) {+ case "like":+ await handleLikeComment(targetComment);+ break;+ case "reply":+ handleReply(targetComment);+ break;+ case "delete":+ try {+ // Use public API for anonymous users in public albums+ if (isPublicAlbum && publicAlbumsCredentials) {+ const storedIdentity = getStoredAnonIdentity(+ selectedCollectionInfo.id,+ );+ if (storedIdentity) {+ await deletePublicComment(+ publicAlbumsCredentials,+ targetComment.collectionID,+ targetComment.id,+ storedIdentity,+ );+ } else {+ log.error(+ "No stored identity for public comment delete",+ );+ return;+ }+ } else {+ await deleteComment(targetComment.id);+ }++ // Update local state+ setComments((prev) =>+ prev.map((c) =>+ c.id === targetComment.id+ ? { ...c, isDeleted: true }+ : c,+ ),+ );+ setCommentsByCollection((prev) => {+ const next = new Map(prev);+ const collectionComments =+ next.get(targetComment.collectionID) ?? [];+ next.set(+ targetComment.collectionID,+ collectionComments.map((c) =>+ c.id === targetComment.id+ ? { ...c, isDeleted: true }+ : c,+ ),+ );+ return next;+ });++ // Notify parent to update its comments state+ onCommentDeleted?.(+ targetComment.collectionID,+ targetComment.id,+ );+ } catch (e) {+ log.error("Failed to delete comment", e);+ }+ break;+ }+ };++ // Filter out deleted comments and sort by timestamp (newest first for column-reverse layout)+ const sortedComments = [...comments]+ .filter((c) => !c.isDeleted)+ .sort((a, b) => b.createdAt - a.createdAt);++ const showOverlay = contextMenu || collectionDropdownOpen;++ return (+ <SidebarDrawer open={open} onClose={onClose} anchor="right">+ <DrawerContentWrapper>+ {showOverlay && (+ <ContextMenuOverlay+ onClick={() => {+ handleCloseContextMenu();+ setCollectionDropdownOpen(false);+ }}+ />+ )}+ <Header>+ {hasCollectionContext ? (+ <Typography+ sx={(theme) => ({+ color: "#000",+ fontWeight: 600,+ ...theme.applyStyles("dark", { color: "#fff" }),+ })}+ >+ {loading+ ? "Loading..."+ : `${sortedComments.length} ${t("comments")}`}+ </Typography>+ ) : collectionsInfo.length > 1 ? (+ <Box+ sx={{+ position: "relative",+ zIndex: collectionDropdownOpen ? 12 : "auto",+ }}+ >+ <CollectionDropdownButton+ onClick={() =>+ setCollectionDropdownOpen(+ !collectionDropdownOpen,+ )+ }+ >+ <Box sx={{ position: "relative" }}>+ {selectedCollectionInfo &&+ thumbnailURLs.get(+ selectedCollectionInfo.id,+ ) ? (+ <CollectionThumbnail+ src={thumbnailURLs.get(+ selectedCollectionInfo.id,+ )}+ alt=""+ />+ ) : (+ <CollectionThumbnailPlaceholder />+ )}+ <CollectionBadge>+ {selectedCollectionInfo?.commentCount ??+ 0}+ </CollectionBadge>+ </Box>+ <Typography+ sx={(theme) => ({+ color: "#000",+ fontWeight: 600,+ fontSize: 14,+ lineHeight: "20px",+ marginBottom: "4px",+ ...theme.applyStyles("dark", {+ color: "#fff",+ }),+ })}+ >+ {selectedCollectionInfo?.name ?? "Album"}+ </Typography>+ <ChevronDownIcon />+ </CollectionDropdownButton>+ {collectionDropdownOpen && (+ <CollectionDropdownMenu>+ {sortedCollectionsInfo.map((collection) => (+ <CollectionDropdownItem+ key={collection.id}+ onClick={() =>+ handleCollectionSelect(+ collection.id,+ )+ }+ >+ <Box sx={{ position: "relative" }}>+ {thumbnailURLs.get(+ collection.id,+ ) ? (+ <CollectionThumbnail+ src={thumbnailURLs.get(+ collection.id,+ )}+ alt=""+ />+ ) : (+ <CollectionThumbnailPlaceholder />+ )}+ <CollectionBadge>+ {collection.commentCount}+ </CollectionBadge>+ </Box>+ <Typography+ sx={(theme) => ({+ color: "#000",+ fontWeight: 600,+ fontSize: 14,+ lineHeight: "20px",+ marginBottom: "4px",+ ...theme.applyStyles(+ "dark",+ { color: "#fff" },+ ),+ })}+ >+ {collection.name}+ </Typography>+ </CollectionDropdownItem>+ ))}+ </CollectionDropdownMenu>+ )}+ </Box>+ ) : (+ <Typography+ sx={(theme) => ({+ color: "#000",+ fontWeight: 600,+ ...theme.applyStyles("dark", { color: "#fff" }),+ })}+ >+ {loading+ ? "Loading..."+ : `${sortedComments.length} ${t("comments")}`}+ </Typography>+ )}+ <CloseButton onClick={onClose}>+ <CloseIcon sx={{ fontSize: 22 }} />+ </CloseButton>+ </Header>++ <CommentsContainer ref={commentsContainerRef}>+ {loading ? (+ <LoadingContainer>+ <CircularProgress size={32} />+ </LoadingContainer>+ ) : sortedComments.length === 0 ? (+ <EmptyMessage>{t("no_comments_yet")}</EmptyMessage>+ ) : (+ sortedComments.map((comment, index) => {+ // Check if this is the current user's comment+ // For logged-in users, check userID+ // For anonymous users, check anonUserID against stored identity+ const storedIdentity = selectedCollectionInfo+ ? getStoredAnonIdentity(+ selectedCollectionInfo.id,+ )+ : undefined;+ const isCurrentAnonUser = !!(+ storedIdentity &&+ comment.anonUserID === storedIdentity.anonUserID+ );+ const commentIsOwn =+ comment.userID === currentUserID ||+ isCurrentAnonUser;++ // With column-reverse, visual order is reversed from array order+ // Visual "above" = higher index, visual "below" = lower index+ const prevComment = sortedComments[index + 1];+ const nextComment = sortedComments[index - 1];++ // 10 minutes in microseconds (server timestamps are in microseconds)+ const GROUP_TIME_THRESHOLD = 10 * 60 * 1000 * 1000;++ // Comments are in same sequence if same user AND within 10 minutes+ // For anon users, also check if they have the same anonUserID+ const isSameUser = (a: Comment, b: Comment) => {+ if (a.anonUserID && b.anonUserID) {+ return a.anonUserID === b.anonUserID;+ }+ return a.userID === b.userID;+ };+ const isSameSequenceAsPrev =+ prevComment &&+ isSameUser(prevComment, comment) &&+ comment.createdAt - prevComment.createdAt <=+ GROUP_TIME_THRESHOLD;+ const isSameSequenceAsNext =+ nextComment &&+ isSameUser(nextComment, comment) &&+ nextComment.createdAt - comment.createdAt <=+ GROUP_TIME_THRESHOLD;++ const isFirstInSequence = !isSameSequenceAsPrev;+ const isLastInSequence = !isSameSequenceAsNext;+ const showHeader =+ isFirstInSequence && !commentIsOwn;+ const parentComment = comment.parentCommentID+ ? getParentComment(+ comment.parentCommentID,+ comments,+ )+ : undefined;++ const showOwnTimestamp =+ commentIsOwn && isFirstInSequence;++ // Get the display name, avatar color key, and masked email status for the comment author+ const getCommentAuthorInfo = (): {+ name: string;+ avatarColorKey: string;+ isMaskedEmail: boolean;+ } => {+ // If anonymous user, check anonUserNames map+ if (comment.anonUserID) {+ const anonName =+ anonUserNames?.get(+ comment.anonUserID,+ ) ??+ `${t("anonymous")} ${comment.anonUserID.slice(-4)}`;+ return {+ name: anonName,+ // Use name for avatar color (varying length like mobile emails)+ avatarColorKey: anonName,+ isMaskedEmail: false,+ };+ }+ // For registered users, use email+ const emailFromMap =+ prefetchedUserIDToEmail?.get(+ comment.userID,+ );+ const email = emailFromMap ?? t("user");+ return {+ name: email,+ // Use email or userID for avatar color+ avatarColorKey: emailFromMap+ ? emailFromMap+ : String(comment.userID),+ isMaskedEmail: email.startsWith("*"),+ };+ };++ const authorInfo = getCommentAuthorInfo();++ return (+ <Box key={comment.id}>+ {showHeader && (+ <CommentHeader+ userName={authorInfo.name}+ timestamp={comment.createdAt}+ isMaskedEmail={+ authorInfo.isMaskedEmail+ }+ avatarColorKey={+ authorInfo.avatarColorKey+ }+ />+ )}+ {showOwnTimestamp && (+ <OwnTimestamp>+ {formatTimeAgo(comment.createdAt)}+ </OwnTimestamp>+ )}+ <CommentBubbleWrapper+ data-comment-id={comment.id}+ isOwn={commentIsOwn}+ isFirstOwn={+ !showOwnTimestamp &&+ commentIsOwn &&+ !!prevComment &&+ prevComment.userID !==+ currentUserID &&+ prevComment.anonUserID !==+ storedIdentity?.anonUserID+ }+ isLastOwn={isLastInSequence}+ isHighlighted={+ contextMenu?.comment.id ===+ comment.id+ }+ >+ <CommentBubbleInner+ onContextMenu={(e) => {+ const bubbleElement =+ e.currentTarget.querySelector<HTMLElement>(+ "[data-comment-bubble]",+ );+ if (bubbleElement) {+ handleContextMenu(+ e,+ comment,+ bubbleElement,+ );+ }+ }}+ >+ <CommentBubble+ isOwn={commentIsOwn}+ data-comment-bubble+ >+ {parentComment && (+ <QuotedReply+ parentComment={+ parentComment+ }+ isOwn={commentIsOwn}+ currentUserID={+ currentUserID+ }+ userIDToEmail={+ prefetchedUserIDToEmail+ }+ anonUserNames={+ anonUserNames+ }+ currentAnonUserID={+ storedIdentity?.anonUserID+ }+ />+ )}+ <CommentText+ isOwn={commentIsOwn}+ >+ {comment.text}+ </CommentText>+ </CommentBubble>+ </CommentBubbleInner>+ </CommentBubbleWrapper>+ </Box>+ );+ })+ )}+ <StyledMenu+ anchorEl={contextMenu?.anchorEl}+ open={Boolean(contextMenu)}+ onClose={handleCloseContextMenu}+ anchorOrigin={{+ vertical: "bottom",+ horizontal: "right",+ }}+ transformOrigin={{+ vertical: "top",+ horizontal: "right",+ }}+ >+ <StyledMenuItem+ onClick={() => handleContextMenuAction("like")}+ >+ <HeartIcon small />+ <span>+ {contextMenuIsLikedRef.current+ ? t("unlike")+ : t("like")}+ </span>+ </StyledMenuItem>+ <StyledMenuItem+ onClick={() => handleContextMenuAction("reply")}+ >+ <ReplyIcon />+ <span>{t("reply")}</span>+ </StyledMenuItem>+ {contextMenu &&+ canDeleteComment(contextMenu.comment) && (+ <StyledMenuItem+ onClick={() =>+ handleContextMenuAction("delete")+ }+ sx={(theme) => ({+ "&:hover": {+ backgroundColor: "#F24F4F",+ color: "#fff",+ },+ ...theme.applyStyles("dark", {+ "&:hover": {+ backgroundColor: "#C53030",+ color: "#fff",+ },+ }),+ })}+ >+ <DeleteIcon />+ <span>{t("delete")}</span>+ </StyledMenuItem>+ )}+ </StyledMenu>+ </CommentsContainer>++ <InputContainer>+ {replyingTo && (+ <ReplyingToBar>+ <ReplyingToContent>+ <Box sx={{ flex: 1, minWidth: 0 }}>+ <Typography+ sx={(theme) => ({+ fontSize: 12,+ color: "#666",+ ...theme.applyStyles("dark", {+ color: "rgba(255, 255, 255, 0.7)",+ }),+ })}+ >+ Replying to{" "}+ {(() => {+ // Check for anonymous user+ if (replyingTo.anonUserID) {+ const storedIdentity =+ selectedCollectionInfo+ ? getStoredAnonIdentity(+ selectedCollectionInfo.id,+ )+ : undefined;+ if (+ storedIdentity &&+ replyingTo.anonUserID ===+ storedIdentity.anonUserID+ ) {+ return t("yourself");+ }+ return (+ anonUserNames?.get(+ replyingTo.anonUserID,+ ) ?? t("user")+ );+ }+ // Regular user+ return replyingTo.userID ===+ currentUserID+ ? t("yourself")+ : (prefetchedUserIDToEmail?.get(+ replyingTo.userID,+ ) ?? t("user"));+ })()}+ ...+ </Typography>+ <Typography+ sx={(theme) => ({+ fontSize: 14,+ color: "#000",+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ ...theme.applyStyles("dark", {+ color: "#fff",+ }),+ })}+ >+ {truncateCommentText(replyingTo.text)}+ </Typography>+ </Box>+ <IconButton+ size="small"+ onClick={() => {+ setReplyingTo(null);+ inputRef.current?.focus();+ }}+ sx={(theme) => ({+ color: "#666",+ p: 0,+ mt: -0.25,+ mr: -0.25,+ flexShrink: 0,+ "&:hover": {+ backgroundColor: "transparent",+ },+ ...theme.applyStyles("dark", {+ color: "rgba(255, 255, 255, 0.7)",+ }),+ })}+ >+ <CloseIcon sx={{ fontSize: 16 }} />+ </IconButton>+ </ReplyingToContent>+ </ReplyingToBar>+ )}+ <InputWrapper+ onClick={handleInputClick}+ sx={+ needsIdentityToComment+ ? (theme) => ({+ cursor: "pointer",+ borderRadius: "20px",+ overflow: "hidden",+ transition: "background-color 0.15s ease",+ "&:hover": {+ backgroundColor:+ "rgba(0, 0, 0, 0.04)",+ ...theme.applyStyles("dark", {+ backgroundColor:+ "rgba(255, 255, 255, 0.08)",+ }),+ },+ "& .MuiInputBase-root, & .MuiInputBase-input":+ { cursor: "pointer" },+ })+ : undefined+ }+ >+ <StyledTextField+ fullWidth+ multiline+ minRows={1}+ autoFocus={!needsIdentityToComment}+ placeholder={t("say_something_nice_placeholder")}+ variant="standard"+ value={commentText}+ onChange={(e) => setCommentText(e.target.value)}+ onKeyDown={handleCommentKeyDown}+ inputRef={inputRef}+ slotProps={{ htmlInput: { maxLength: 280 } }}+ />+ </InputWrapper>+ <SendButton onClick={handleSend} disabled={sending}>+ {sending ? (+ <CircularProgress+ size={18}+ sx={{ color: "inherit" }}+ />+ ) : (+ <SendIcon />+ )}+ </SendButton>+ </InputContainer>+ </DrawerContentWrapper>++ {/* Public album modals */}+ <PublicCommentModal+ open={showPublicCommentModal}+ onClose={() => setShowPublicCommentModal(false)}+ onCommentAnonymously={handleCommentAnonymously}+ onJoinAlbumToComment={handleJoinAlbumToComment}+ enableJoin={enableJoin}+ />+ <PublicLikeModal+ open={showPublicLikeModal}+ onClose={() => {+ setShowPublicLikeModal(false);+ setPendingCommentLike(null);+ }}+ onLikeAnonymously={handleLikeAnonymously}+ onJoinAlbumToLike={handleJoinAlbumToLike}+ enableJoin={enableJoin}+ />+ <AddNameModal+ open={showAddNameModal}+ onClose={() => {+ setShowAddNameModal(false);+ setPendingCommentLike(null);+ }}+ onExited={() => {+ // Reset actionType after modal has fully closed to avoid+ // visual glitch of icon changing during exit animation+ setAddNameForCommentLike(false);+ }}+ onSubmit={handleNameSubmit}+ actionType={addNameForCommentLike ? "like" : "comment"}+ />+ </SidebarDrawer>+ );+};++// =============================================================================+// Styled Components+// =============================================================================++// Drawer & Layout+const SidebarDrawer = styled(Drawer)(({ theme }) => ({+ "& .MuiDrawer-paper": {+ width: "23vw",+ minWidth: "520px",+ maxWidth: "calc(100% - 32px)",+ height: "calc(100% - 32px)",+ margin: "16px",+ borderRadius: "36px",+ backgroundColor: "#fff",+ padding: "24px 24px 32px 24px",+ boxShadow: "none",+ border: "1px solid #E0E0E0",+ display: "flex",+ flexDirection: "column",+ overflow: "visible",+ "@media (max-width: 450px)": {+ width: "100%",+ minWidth: "unset",+ maxWidth: "100%",+ height: "100%",+ margin: 0,+ borderRadius: 0,+ },+ ...theme.applyStyles("dark", {+ backgroundColor: "#1b1b1b",+ border: "1px solid rgba(255, 255, 255, 0.18)",+ }),+ },+ "& .MuiBackdrop-root": { backgroundColor: "transparent" },+}));++const DrawerContentWrapper = styled(Box)(() => ({+ position: "relative",+ display: "flex",+ flexDirection: "column",+ flex: 1,+ minHeight: 0,+}));++const Header = styled(Stack)(() => ({+ flexDirection: "row",+ alignItems: "center",+ justifyContent: "space-between",+ marginBottom: 48,+}));++const CloseButton = styled(IconButton)(({ theme }) => ({+ backgroundColor: "#F5F5F7",+ color: "#000",+ padding: "8px",+ "&:hover": { backgroundColor: "#E5E5E7" },+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.12)",+ color: "#fff",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.16)" },+ }),+}));++// Collection Dropdown+const CollectionDropdownButton = styled(Box)(({ theme }) => ({+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ gap: 14,+ padding: "5px 6px 0px 6px",+ borderRadius: 12,+ backgroundColor: "#F0F0F0",+ cursor: "pointer",+ "&:hover": { backgroundColor: "#E8E8E8" },+ ...theme.applyStyles("dark", {+ backgroundColor: "#363636",+ "&:hover": { backgroundColor: "#404040" },+ }),+}));++const CollectionThumbnail = styled("img")(() => ({+ width: 24,+ height: 24,+ borderRadius: 5,+ objectFit: "cover",+ backgroundColor: "#08C225",+}));++const CollectionBadge = styled(Box)(({ theme }) => ({+ position: "absolute",+ bottom: 4,+ right: -4,+ display: "inline-flex",+ justifyContent: "center",+ alignItems: "center",+ borderRadius: "50%",+ backgroundColor: "#FFF",+ color: "#000",+ fontSize: 10,+ fontWeight: 600,+ lineHeight: 1,+ minWidth: 16,+ minHeight: 16,+ ...theme.applyStyles("dark", { backgroundColor: "#fff", color: "#000" }),+}));++const CollectionThumbnailPlaceholder = styled(Box)(() => ({+ width: 24,+ height: 24,+ borderRadius: 5,+ backgroundColor: "#08C225",+}));++const LoadingContainer = styled(Box)(() => ({+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ height: "100%",+ // Offset for header (marginBottom: 48) + padding diff (32-24=8) = 56, halved+ marginTop: -28,+}));++const EmptyMessage = styled(Typography)(({ theme }) => ({+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ height: "100%",+ // Offset for header (marginBottom: 48) + padding diff (32-24=8) = 56, halved+ marginTop: -28,+ color: "#666",+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.5)" }),+}));++const CollectionDropdownMenu = styled(Box)(({ theme }) => ({+ position: "absolute",+ top: "calc(100% + 8px)",+ left: 0,+ display: "flex",+ flexDirection: "column",+ justifyContent: "center",+ alignItems: "flex-start",+ width: 184,+ padding: 4,+ gap: 4,+ borderRadius: 12,+ border: "1px solid rgba(0, 0, 0, 0.08)",+ backgroundColor: "#F0F0F0",+ zIndex: 12,+ ...theme.applyStyles("dark", {+ border: "1px solid rgba(0, 0, 0, 0.08)",+ backgroundColor: "#363636",+ }),+}));++const CollectionDropdownItem = styled(Box)(({ theme }) => ({+ display: "flex",+ alignItems: "center",+ gap: 14,+ padding: "5px 6px 0px 6px",+ borderRadius: 8,+ cursor: "pointer",+ width: "100%",+ "&:hover": { backgroundColor: "#E8E8E8" },+ ...theme.applyStyles("dark", {+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.16)" },+ }),+}));++const CommentsContainer = styled(Box)(({ theme }) => ({+ flex: 1,+ overflow: "auto",+ marginBottom: 16,+ marginRight: -24,+ position: "relative",+ display: "flex",+ flexDirection: "column-reverse",+ "&::-webkit-scrollbar": { width: "6px" },+ "&::-webkit-scrollbar-track": { background: "transparent" },+ "&::-webkit-scrollbar-thumb": {+ background: "rgba(0, 0, 0, 0.2)",+ borderRadius: "3px",+ },+ scrollbarWidth: "thin",+ scrollbarColor: "rgba(0, 0, 0, 0.2) transparent",+ ...theme.applyStyles("dark", {+ "&::-webkit-scrollbar-thumb": {+ background: "rgba(255, 255, 255, 0.2)",+ },+ scrollbarColor: "rgba(255, 255, 255, 0.2) transparent",+ }),+}));++// Comment Header+const CommentHeaderContainer = styled(Box)(() => ({+ display: "flex",+ alignItems: "center",+ gap: 8,+ marginBottom: 12,+}));++const UserName = styled(Typography)(({ theme }) => ({+ fontWeight: 600,+ color: "#000",+ fontSize: 14,+ ...theme.applyStyles("dark", { color: "#fff" }),+}));++const Separator = styled(Typography)(({ theme }) => ({+ color: "#666",+ fontSize: 12,+ marginLeft: -4,+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.7)" }),+}));++const Timestamp = styled(Typography)(({ theme }) => ({+ color: "#666",+ fontSize: 12,+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.7)" }),+}));++const OwnTimestamp = styled(Typography)(({ theme }) => ({+ color: "#666",+ fontSize: 12,+ textAlign: "right",+ marginBottom: 4,+ paddingRight: 52,+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.7)" }),+}));++// Comment Bubbles+const CommentBubbleWrapper = styled(Box, {+ shouldForwardProp: (prop) =>+ !["isOwn", "isFirstOwn", "isLastOwn", "isHighlighted"].includes(+ prop as string,+ ),+})<{+ isOwn: boolean;+ isFirstOwn?: boolean;+ isLastOwn?: boolean;+ isHighlighted?: boolean;+}>(({ isOwn, isFirstOwn, isLastOwn, isHighlighted }) => ({+ display: "flex",+ justifyContent: isOwn ? "flex-end" : "flex-start",+ width: "100%",+ marginTop: isFirstOwn ? 64 : 0,+ marginBottom: isLastOwn ? 48 : 12,+ paddingRight: isOwn ? 52 : 0,+ paddingLeft: isOwn ? 0 : 28,+ position: "relative",+ zIndex: isHighlighted ? 11 : "auto",+}));++const CommentBubbleInner = styled(Box)(() => ({+ position: "relative",+ maxWidth: 320,+}));++const CommentBubble = styled(Box, {+ shouldForwardProp: (prop) => prop !== "isOwn",+})<{ isOwn: boolean }>(({ isOwn, theme }) => ({+ backgroundColor: isOwn ? "#0DAF35" : "#F0F0F0",+ borderRadius: isOwn ? "20px 6px 20px 20px" : "6px 20px 20px 20px",+ padding: "20px 40px 20px 20px",+ width: "fit-content",+ maxWidth: "100%",+ ...(!isOwn && theme.applyStyles("dark", { backgroundColor: "#363636" })),+}));++const CommentText = styled(Typography, {+ shouldForwardProp: (prop) => prop !== "isOwn",+})<{ isOwn: boolean }>(({ isOwn, theme }) => ({+ color: isOwn ? "#fff" : "#000",+ fontSize: 14,+ whiteSpace: "pre-wrap",+ overflowWrap: "break-word",+ ...(!isOwn && theme.applyStyles("dark", { color: "#fff" })),+}));++const QuotedReplyContainer = styled(Box, {+ shouldForwardProp: (prop) => prop !== "isOwn",+})<{ isOwn: boolean }>(({ isOwn, theme }) => ({+ borderLeft: `3px solid ${isOwn ? "rgba(255,255,255,0.5)" : "#ccc"}`,+ paddingLeft: 10,+ marginBottom: 16,+ ...(!isOwn &&+ theme.applyStyles("dark", {+ borderLeft: "3px solid rgba(255, 255, 255, 0.3)",+ })),+}));++// Input Area+const InputContainer = styled(Box)(({ theme }) => ({+ position: "relative",+ backgroundColor: "#F3F3F3",+ borderRadius: "20px",+ margin: "0 -8px -16px -8px",+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.12)",+ }),+}));++const ReplyingToBar = styled(Box)(() => ({ padding: "12px 12px 0 12px" }));++const ReplyingToContent = styled(Box)(({ theme }) => ({+ display: "flex",+ alignItems: "flex-start",+ gap: 8,+ backgroundColor: "rgba(0, 0, 0, 0.06)",+ borderRadius: 12,+ padding: "10px 10px 10px 12px",+ borderLeft: "4px solid #ccc",+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.08)",+ borderLeft: "4px solid rgba(255, 255, 255, 0.3)",+ }),+}));++const InputWrapper = styled(Box)(({ theme }) => ({+ padding: "8px 48px 8px 16px",+ maxHeight: "300px",+ overflow: "auto",+ "&::-webkit-scrollbar": { width: "8px" },+ "&::-webkit-scrollbar-track": { background: "transparent" },+ "&::-webkit-scrollbar-thumb": {+ background: "rgba(0, 0, 0, 0.3)",+ borderRadius: "4px",+ },+ "&::-webkit-scrollbar-thumb:hover": { background: "rgba(0, 0, 0, 0.5)" },+ scrollbarWidth: "thin",+ scrollbarColor: "rgba(0, 0, 0, 0.3) transparent",+ ...theme.applyStyles("dark", {+ "&::-webkit-scrollbar-thumb": {+ background: "rgba(255, 255, 255, 0.3)",+ },+ "&::-webkit-scrollbar-thumb:hover": {+ background: "rgba(255, 255, 255, 0.5)",+ },+ scrollbarColor: "rgba(255, 255, 255, 0.3) transparent",+ }),+}));++const StyledTextField = styled(TextField)(({ theme }) => ({+ "& .MuiInput-root": { "&::before, &::after": { display: "none" } },+ "& .MuiInputBase-input": {+ padding: 0,+ color: "#000",+ "&::placeholder": { color: "#999", opacity: 1 },+ },+ ...theme.applyStyles("dark", {+ "& .MuiInputBase-input": {+ color: "#fff",+ "&::placeholder": { color: "rgba(255, 255, 255, 0.5)" },+ },+ }),+}));++const SendButton = styled(IconButton)(({ theme }) => ({+ position: "absolute",+ right: 12,+ bottom: 8.5,+ color: "rgba(0, 0, 0, 0.8)",+ width: 42,+ height: 42,+ "&:hover": { backgroundColor: "rgba(0, 0, 0, 0.1)" },+ ...theme.applyStyles("dark", {+ color: "rgba(255, 255, 255, 0.8)",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.1)" },+ }),+}));++// Context Menu+const ContextMenuOverlay = styled(Box)(() => ({+ position: "absolute",+ top: -25,+ left: -25,+ right: -25,+ bottom: -33,+ backgroundColor: "rgba(0, 0, 0, 0.6)",+ zIndex: 10,+ borderRadius: "36px",+ "@media (max-width: 450px)": { borderRadius: 0 },+}));++const StyledMenu = styled(Menu)(({ theme }) => ({+ "& .MuiPaper-root": {+ backgroundColor: "#fff",+ borderRadius: "12px",+ boxShadow: "0 4px 16px rgba(0, 0, 0, 0.15)",+ minWidth: "140px",+ marginTop: "4px",+ },+ "& .MuiList-root": { padding: "6px" },+ ...theme.applyStyles("dark", {+ "& .MuiPaper-root": {+ backgroundColor: "#2b2b2b",+ boxShadow: "0 4px 16px rgba(0, 0, 0, 0.5)",+ },+ }),+}));++const StyledMenuItem = styled(MenuItem)(({ theme }) => ({+ display: "flex",+ alignItems: "center",+ gap: 10,+ padding: "8px 12px",+ borderRadius: 8,+ color: "#131313",+ fontSize: 14,+ "&:hover": { backgroundColor: "#F5F5F5" },+ ...theme.applyStyles("dark", {+ color: "#fff",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.12)" },+ }),+}));diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsxnew file mode 100644index 0000000000..8197acbf59--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsx@@ -0,0 +1,3098 @@+import { Navigation03Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import AddIcon from "@mui/icons-material/Add";+import ArchiveOutlinedIcon from "@mui/icons-material/ArchiveOutlined";+import ContentCopyIcon from "@mui/icons-material/ContentCopy";+import DeleteIcon from "@mui/icons-material/Delete";+import EditIcon from "@mui/icons-material/Edit";+import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";+import FullscreenExitOutlinedIcon from "@mui/icons-material/FullscreenExitOutlined";+import FullscreenOutlinedIcon from "@mui/icons-material/FullscreenOutlined";+import UnArchiveIcon from "@mui/icons-material/Unarchive";+import {+ Dialog,+ DialogContent,+ DialogTitle,+ Menu,+ MenuItem,+ Stack,+ styled,+ Typography,+ type ModalProps,+} from "@mui/material";+import type { LocalUser } from "ente-accounts/services/user";+import { isDesktop } from "ente-base/app";+import { SpacedRow } from "ente-base/components/containers";+import { InlineErrorIndicator } from "ente-base/components/ErrorIndicator";+import { TitledMiniDialog } from "ente-base/components/MiniDialog";+import { DialogCloseIconButton } from "ente-base/components/mui/DialogCloseIconButton";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { LoadingButton } from "ente-base/components/mui/LoadingButton";+import { useInterval, useIsSmallWidth } from "ente-base/components/utils/hooks";+import { type ModalVisibilityProps } from "ente-base/components/utils/modal";+import { useBaseContext } from "ente-base/context";+import { lowercaseExtension } from "ente-base/file-name";+import type { PublicAlbumsCredentials } from "ente-base/http";+import { formattedListJoin, ut } from "ente-base/i18n";+import log from "ente-base/log";+import { isOfficialAlbumsApp } from "ente-base/origins";+import {+ FileInfo,+ type FileInfoExif,+ type FileInfoProps,+} from "ente-gallery/components/FileInfo";+import type { Collection } from "ente-media/collection";+import { fileFileName, ItemVisibility } from "ente-media/file-metadata";+import { FileType } from "ente-media/file-type";+import type { EnteFile } from "ente-media/file.js";+import { isHEICExtension, needsJPEGConversion } from "ente-media/formats";+import {+ addPublicReaction,+ createAnonIdentity,+ deletePublicReaction,+ getPublicAnonProfiles,+ getPublicParticipantsMaskedEmails,+ getPublicSocialDiff,+ getStoredAnonIdentity,+} from "ente-new/albums/services/public-reaction";+import {+ ImageEditorOverlay,+ type ImageEditorOverlayProps,+} from "ente-new/photos/components/ImageEditorOverlay";+import { getCollectionByID } from "ente-new/photos/services/collection";+import type { CollectionSummaries } from "ente-new/photos/services/collection-summary";+import { type Comment } from "ente-new/photos/services/comment";+import { addReaction, deleteReaction } from "ente-new/photos/services/reaction";+import {+ getAnonProfiles,+ getUnifiedSocialDiff,+ type UnifiedReaction,+} from "ente-new/photos/services/social";+import { t } from "i18next";+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { AddNameModal } from "./AddNameModal";+import { CommentsSidebar } from "./CommentsSidebar";+import {+ fileInfoExifForFile,+ updateItemDataAlt,+ type ItemData,+} from "./data-source";+import { LikeAlbumSelectorModal } from "./LikeAlbumSelectorModal";+import { LikesSidebar } from "./LikesSidebar";+import {+ FileViewerPhotoSwipe,+ moreButtonID,+ moreMenuID,+ resetMoreMenuButtonOnMenuClose,+ type FileViewerPhotoSwipeDelegate,+} from "./photoswipe";+import { PublicLikeModal } from "./PublicLikeModal";++const fileViewerBackStateKey = "__enteFileViewerBackState";++const addFileViewerBackStateMarker = (state: unknown, marker: string) =>+ state && typeof state == "object"+ ? {+ ...(state as Record<string, unknown>),+ [fileViewerBackStateKey]: marker,+ }+ : { [fileViewerBackStateKey]: marker };++const hasFileViewerBackStateMarker = (state: unknown, marker: string) =>+ !!state &&+ typeof state == "object" &&+ (state as Record<string, unknown>)[fileViewerBackStateKey] == marker;++/**+ * Derived data for a file that is needed to display the file viewer controls+ * etc associated with the file.+ *+ * This is recomputed on-demand each time the slide changes.+ */+export interface FileViewerFileAnnotation {+ /**+ * The id of the file whose annotation this is.+ */+ fileID: number;+ /**+ * `true` if this file is owned by the logged in user (if any).+ */+ isOwnFile: boolean;+ /**+ * `true` if the toggle favorite action should be shown for this file.+ */+ showFavorite: boolean;+ /**+ * Set if the download action should be shown for this file.+ *+ * - When "bar", the action button is shown among the bar icons.+ *+ * - When "menu", the action is shown as a more menu entry.+ *+ * Note: "bar" should only be set if {@link haveUser} is also true.+ */+ showDownload: "bar" | "menu" | undefined;+ /**+ * `true` if the delete action should be shown for this file.+ */+ showDelete: boolean;+ /**+ * `true` if the toggle archive action should be shown for this file.+ */+ showArchive: boolean;+ /**+ * `true` if the copy image action should be shown for this file.+ */+ showCopyImage: boolean;+ /**+ * `true` if this is an image which can be edited, _and_ editing is+ * possible, and the edit action should therefore be shown for this file.+ */+ showEditImage: boolean;+}++/**+ * A file, its annotation, and its item data, in a nice cosy box.+ */+export interface FileViewerAnnotatedFile {+ file: EnteFile;+ annotation: FileViewerFileAnnotation;+ itemData: ItemData;+}++/** The type of sidebar to open initially in the file viewer. */+export type FileViewerInitialSidebar = "likes" | "comments";++export type FileViewerProps = ModalVisibilityProps & {+ /**+ * The currently logged in user, if any.+ *+ * - If we're running in the context of the photos app, then this should be+ * set to the currently logged in user.+ *+ * - If we're running in the context of the public albums app, then this+ * should not be set.+ *+ * See: [Note: Gallery children can assume user]+ */+ user?: LocalUser;+ /**+ * The list of files that are currently being displayed in the context in+ * which the file viewer was invoked.+ *+ * Although the file viewer is called on to display a particular file+ * (specified by the {@link initialIndex} prop), the viewer is always used+ * in the context of a an album, or search results, or some other arbitrary+ * list of files. The {@link files} prop sets this underlying list of files.+ *+ * After the initial file has been shown, the user can navigate through the+ * other files from within the viewer by using the arrow buttons.+ */+ files: EnteFile[];+ /**+ * The index of the file that should be initially shown.+ *+ * Subsequently the user may navigate between files by using the controls+ * provided within the file viewer itself.+ */+ initialIndex: number;+ /**+ * If set, the specified sidebar will be opened when the file viewer opens.+ */+ initialSidebar?: FileViewerInitialSidebar;+ /**+ * If set, the comments sidebar will scroll to and highlight this comment.+ * Only used when initialSidebar is "comments".+ */+ highlightCommentID?: string;+ /**+ * If true then the viewer does not show controls for downloading the file.+ */+ disableDownload?: boolean;+ /**+ * If true then the fullscreen button is shown as a primary action button+ * in the toolbar instead of being hidden in the more menu.+ */+ showFullscreenButton?: boolean;+ /**+ * `true` when we are viewing files in an album that the user does not own.+ */+ isInIncomingSharedCollection?: boolean;+ /**+ * `true` when we are viewing files in the Trash.+ */+ isInTrashSection?: boolean;+ /**+ * `true` when we are viewing files in the hidden section.+ */+ isInHiddenSection?: boolean;+ /**+ * File IDs of all the files that the user has marked as a favorite.+ *+ * See also {@link onToggleFavorite}.+ */+ favoriteFileIDs?: Set<number>;+ /**+ * File IDs of for which an update of its favorite status is pending (e.g.+ * due to a toggle favorite action in the file viewer).+ *+ * See also {@link favoriteFileIDs} and {@link onToggleFavorite}.+ */+ pendingFavoriteUpdates?: Set<number>;+ /**+ * File IDs of for which an update of its visibility is pending (e.g. due to+ * a toggle archived action in the file viewer).+ *+ * See also {@link onFileVisibilityUpdate}.+ */+ pendingVisibilityUpdates?: Set<number>;+ /**+ * A mapping from file IDs to the IDs of the normal (non-hidden) collections+ * that they are a part of.+ */+ fileNormalCollectionIDs?: FileInfoProps["fileCollectionIDs"];+ /**+ * Collection summaries indexed by their IDs.+ */+ collectionSummaries?: CollectionSummaries;+ /**+ * Called when there was some update performed within the file viewer that+ * necessitates us to pull the latest updates with remote.+ *+ * This is called when the file viewer is closing if any changes were made+ * in the file info panel of the file viewer for any of the files that the+ * user was viewing (e.g. if they changed the caption).+ *+ * Those changes have already been applied to both remote, and likely+ * already also to our local state via {@link onRemoteFilesPull}. This this+ * callback is to trigger a full pull so that any discrepancies in local+ * database also gets up to speed if needed.+ *+ * If we're in a context where edits are not possible, e.g. {@link user} is+ * not defined, then this prop is not used and need not be provided.+ */+ onTriggerRemotePull?: () => void;+ /**+ * Called when an action in the file viewer requires us to pull the local+ * files and collections with remote.+ *+ * Unlike {@link onTriggerRemotePull}, which is a trigger, this function+ * returns a promise that will settle once the pull has completed, and thus+ * can be used in interactive operations that indicate activity to the user.+ *+ * See also: [Note: Full remote pull vs files pull]+ */+ onRemoteFilesPull?: () => Promise<void>;+ /**+ * Called when the user performs an action which does not otherwise have any+ * immediate visual impact, to acknowledge it.+ *+ * See: [Note: Visual feedback to acknowledge user actions]+ */+ onVisualFeedback: () => void;+ /**+ * Called when the favorite status of given {@link file} should be toggled+ * from its current value.+ *+ * The favorite toggle button is shown only if all three of+ * {@link favoriteFileIDs}, {@link pendingFavoriteUpdates} and+ * {@link onToggleFavorite} are provided.+ */+ onToggleFavorite?: (file: EnteFile) => Promise<void>;+ /**+ * Called when {@link visibility} of the given {@link file} should be+ * updated (when the user activates toggle archived action).+ *+ * The toggle archived action is shown only if both+ * {@link pendingVisibilityUpdates} and {@link onFileVisibilityUpdate} are+ * provided.+ */+ onFileVisibilityUpdate?: (+ file: EnteFile,+ visibility: ItemVisibility,+ ) => Promise<void>;+ /**+ * Called when the given {@link file} should be downloaded.+ *+ * If this is not provided then the download action will not be shown.+ */+ onDownload?: (file: EnteFile) => void;+ /**+ * Called when the given {@link file} should be shared via quick link.+ *+ * If this is not provided then the send link action will not be shown.+ */+ onSendLink?: (file: EnteFile) => void;+ /**+ * Called when the given {@link file} should be deleted.+ *+ * If this is not provided then the delete action will not be shown.+ */+ onDelete?: (file: EnteFile) => Promise<void>;+ /**+ * Called when the user edits an image in the image editor and asks us to+ * save their edits as a copy.+ *+ * Editing is disabled if this is not provided.+ *+ * See {@link onSaveEditedCopy} in the {@link ImageEditorOverlay} props for+ * documentation about the parameters.+ */+ onSaveEditedImageCopy?: ImageEditorOverlayProps["onSaveEditedCopy"];++ onAddFileToCollection?: (+ file: EnteFile,+ sourceCollectionSummaryID?: number,+ ) => void;+ /**+ * The ID of the currently active collection, if any (e.g., when viewing an album).+ */+ activeCollectionID?: number;+ /**+ * Public album credentials for anonymous reactions/comments.+ * Required when viewing a public album (no logged in user).+ */+ publicAlbumsCredentials?: PublicAlbumsCredentials;+ /**+ * If set, overrides whether browser back should be consumed to close the+ * viewer.+ *+ * By default this is enabled in public album context, and disabled+ * otherwise.+ */+ shouldCloseOnBrowserBack?: boolean;+ /**+ * If `true`, disables closing the viewer with the Escape key.+ */+ disableEscapeClose?: boolean;+ /**+ * The decrypted collection key (base64 encoded) for encrypting reactions.+ * Required when viewing a public album (no logged in user).+ */+ collectionKey?: string;+ /**+ * Called when user clicks "Join album to like" in the public like modal.+ * Should trigger the join album flow (with mobile deep link fallback).+ */+ onJoinAlbum?: () => void;+ /**+ * `true` if comments are enabled on the public link.+ *+ * When `false`, the comment button and comments sidebar will be hidden.+ * Defaults to `true`.+ */+ enableComment?: boolean;+ /**+ * `true` if the comments and reactions feature is enabled for the user.+ *+ * When `false`, the like and comment buttons will be hidden for logged-in+ * users. Defaults to `true`.+ */+ isCommentsFeatureEnabled?: boolean;+ /**+ * `true` if the "Join album" option is enabled for this public link.+ *+ * When `false`, the "Join album and like/comment" button will be hidden+ * in the public like/comment modals.+ * Defaults to `true`.+ */+ enableJoin?: boolean;+} & Pick<+ FileInfoProps,+ "collectionNameByID" | "onSelectCollection" | "onSelectPerson"+ >;++/**+ * A PhotoSwipe based image, live photo and video viewer.+ */+export const FileViewer: React.FC<FileViewerProps> = ({+ open,+ onClose,+ user,+ files,+ initialIndex,+ initialSidebar,+ highlightCommentID,+ disableDownload,+ showFullscreenButton,+ isInIncomingSharedCollection,+ isInTrashSection,+ isInHiddenSection,+ favoriteFileIDs,+ pendingFavoriteUpdates,+ pendingVisibilityUpdates,+ fileNormalCollectionIDs,+ collectionSummaries,+ collectionNameByID,+ onTriggerRemotePull,+ onRemoteFilesPull,+ onVisualFeedback,+ onToggleFavorite,+ onFileVisibilityUpdate,+ onDownload,+ onSendLink,+ onDelete,+ onSelectCollection,+ onSelectPerson,+ onSaveEditedImageCopy,+ onAddFileToCollection,+ activeCollectionID,+ publicAlbumsCredentials,+ shouldCloseOnBrowserBack: shouldCloseOnBrowserBackOverride,+ disableEscapeClose = false,+ collectionKey,+ onJoinAlbum,+ enableComment = true,+ isCommentsFeatureEnabled = true,+ enableJoin = true,+}) => {+ const { onGenericError } = useBaseContext();+ const shouldCloseOnBrowserBack =+ shouldCloseOnBrowserBackOverride ?? !!publicAlbumsCredentials;++ // There are 3 things involved in this dance:+ //+ // 1. Us, "FileViewer". We're a React component.+ // 2. The custom PhotoSwipe wrapper, "FileViewerPhotoSwipe". It is a class.+ // 3. The delegate, "FileViewerPhotoSwipeDelegate".+ //+ // The delegate acts as a bridge between us and (our custom) photoswipe+ // class, to avoid recreating the class each time a "dynamic" prop changes.+ // The delegate has a stable identity, we just keep updating the callback+ // functions that it holds.+ //+ // The word "dynamic" here means a prop on whose change we should not+ // recreate the photoswipe dialog.+ const delegateRef = useRef<FileViewerPhotoSwipeDelegate | undefined>(+ undefined,+ );++ // We also need to maintain a ref to the currently displayed dialog since we+ // might need to ask it to refresh its contents.+ const psRef = useRef<FileViewerPhotoSwipe | undefined>(undefined);+ const handleCloseRef = useRef<() => void>(() => undefined);+ const browserBackStateRef = useRef<string | undefined>(undefined);++ // Whenever we get a callback from our custom PhotoSwipe instance, we also+ // get the active file on which that action was performed as an argument. We+ // save it as the `activeAnnotatedFile` state so that the rest of our React+ // tree can use it.+ //+ // This is not guaranteed, or even intended, to be in sync with the active+ // file shown within the file viewer. All that this guarantees is this will+ // refer to the file on which the last user initiated action was performed.+ const [activeAnnotatedFile, setActiveAnnotatedFile] = useState<+ FileViewerAnnotatedFile | undefined+ >(undefined);++ // With semantics similar to `activeAnnotatedFile`, this is the exif data+ // associated with the `activeAnnotatedFile`, if any.+ const [activeFileExif, setActiveFileExif] = useState<+ FileInfoExif | undefined+ >(undefined);++ const [openFileInfo, setOpenFileInfo] = useState(false);+ const [openComments, setOpenComments] = useState(false);+ const [openLikes, setOpenLikes] = useState(false);+ const [openLikeAlbumSelector, setOpenLikeAlbumSelector] = useState(false);+ const [openPublicLikeModal, setOpenPublicLikeModal] = useState(false);+ const [openAddNameModal, setOpenAddNameModal] = useState(false);+ const [moreMenuAnchorEl, setMoreMenuAnchorEl] =+ useState<HTMLElement | null>(null);+ const [openImageEditor, setOpenImageEditor] = useState(false);+ const [openConfirmDelete, setOpenConfirmDelete] = useState(false);+ const [openShortcuts, setOpenShortcuts] = useState(false);++ const [isFullscreen, setIsFullscreen] = useState(false);++ // Map of file ID to map of collection ID to array of comments.+ // For gallery view, we fetch comments from all collections.+ // For collection view, we only fetch comments from that collection.+ const [fileComments, setFileComments] = useState<+ Map<number, Map<number, Comment[]>>+ >(new Map());++ // Map of file ID to map of collection ID to array of all reactions.+ // Includes both file reactions and comment reactions.+ const [allReactions, setAllReactions] = useState<+ Map<number, Map<number, UnifiedReaction[]>>+ >(new Map());++ // Map of user ID to email for displaying reaction/comment authors.+ // Built from collection owner and sharees when fetching social data.+ const [userIDToEmail, setUserIDToEmail] = useState<Map<number, string>>(+ new Map(),+ );++ // Map of anon user ID to decrypted user name for anonymous users.+ const [anonUserNames, setAnonUserNames] = useState<Map<string, string>>(+ new Map(),+ );++ // Ref for fileComments to use in callbacks+ const fileCommentsRef = useRef(fileComments);+ useEffect(() => {+ fileCommentsRef.current = fileComments;+ }, [fileComments]);++ // Ref for allReactions to use in callbacks+ const allReactionsRef = useRef(allReactions);+ useEffect(() => {+ allReactionsRef.current = allReactions;+ }, [allReactions]);++ // Ref for collectionSummaries to use in callbacks without causing recreations+ const collectionSummariesRef = useRef(collectionSummaries);+ useEffect(() => {+ collectionSummariesRef.current = collectionSummaries;+ }, [collectionSummaries]);++ // Ref for fileNormalCollectionIDs to use in callbacks without causing recreations+ const fileNormalCollectionIDsRef = useRef(fileNormalCollectionIDs);+ useEffect(() => {+ fileNormalCollectionIDsRef.current = fileNormalCollectionIDs;+ }, [fileNormalCollectionIDs]);++ // Cache for collection keys to avoid refetching during polling+ const collectionCacheRef = useRef<+ Map<+ number,+ {+ key: string;+ ownerID: number;+ ownerEmail?: string;+ sharees: { id: number; email?: string }[];+ hasPublicURLs: boolean;+ }+ >+ >(new Map());++ // Track whether we've already opened the initial sidebar for this open+ const hasOpenedInitialSidebarRef = useRef(false);++ // Open the initial sidebar when the file viewer opens with initialSidebar set+ useEffect(() => {+ if (open && initialSidebar && !hasOpenedInitialSidebarRef.current) {+ hasOpenedInitialSidebarRef.current = true;+ if (initialSidebar === "comments") {+ setOpenComments(true);+ } else {+ setOpenLikes(true);+ }+ }+ // Reset the flag when the viewer closes+ if (!open) {+ hasOpenedInitialSidebarRef.current = false;+ }+ }, [open, initialSidebar]);++ // Helper to get current user's file reactions from allReactions+ const getUserFileReactions = useCallback(+ (fileId: number): { collectionId: number; reactionId: string }[] => {+ const fileReactionsMap = allReactionsRef.current.get(fileId);+ if (!fileReactionsMap) return [];++ const userReactions: {+ collectionId: number;+ reactionId: string;+ }[] = [];+ for (const [collectionId, reactions] of fileReactionsMap) {+ // Get stored anonymous identity for this specific collection+ const storedAnonIdentity = getStoredAnonIdentity(collectionId);++ const userFileReaction = reactions.find((r) => {+ if (+ r.commentID ||+ r.fileID !== fileId ||+ r.reactionType !== "green_heart"+ )+ return false;+ // Check for logged-in user+ if (user?.id && r.userID === user.id) return true;+ // Check for anonymous user+ if (+ storedAnonIdentity &&+ r.anonUserID === storedAnonIdentity.anonUserID+ )+ return true;+ return false;+ });+ if (userFileReaction) {+ userReactions.push({+ collectionId,+ reactionId: userFileReaction.id,+ });+ }+ }+ return userReactions;+ },+ [user?.id],+ );++ // If `true`, then we need to trigger a pull from remote when we close.+ const [, setNeedsRemotePull] = useState(false);++ const handleNeedsRemotePull = useCallback(+ () => setNeedsRemotePull(true),+ [],+ );++ const handleClose = useCallback(() => {+ if (document.fullscreenElement) void document.exitFullscreen();+ setNeedsRemotePull((needsPull) => {+ if (needsPull) onTriggerRemotePull?.();+ return false;+ });+ setOpenFileInfo(false);+ setOpenComments(false);+ setOpenLikes(false);+ setOpenLikeAlbumSelector(false);+ setOpenPublicLikeModal(false);+ // No need to `resetMoreMenuButtonOnMenuClose` since we're closing+ // anyway and it'll be removed from the DOM.+ setMoreMenuAnchorEl(null);+ setOpenImageEditor(false);+ setOpenConfirmDelete(false);+ setOpenShortcuts(false);+ setIsFullscreen(false);+ onClose();+ }, [onTriggerRemotePull, onClose]);++ // Keep the latest close callback available to non-react event handlers+ // without forcing effects that register handlers to re-run.+ handleCloseRef.current = handleClose;++ const handleViewInfo = useCallback(+ (annotatedFile: FileViewerAnnotatedFile) => {+ setActiveFileExif(+ fileInfoExifForFile(annotatedFile.file, (exif) =>+ setActiveFileExif(exif),+ ),+ );+ setOpenFileInfo(true);+ },+ [],+ );++ const handleFileInfoClose = useCallback(() => setOpenFileInfo(false), []);++ const handleViewComments = useCallback(() => setOpenComments(true), []);++ const handleCommentsClose = useCallback(() => setOpenComments(false), []);++ // Handle a new comment being added+ const handleCommentAdded = useCallback((comment: Comment) => {+ const fileID = comment.fileID;+ if (!fileID) return;++ setFileComments((prev) => {+ const next = new Map(prev);+ const fileCommentsMap = new Map<number, Comment[]>(+ prev.get(fileID) ?? new Map(),+ );+ const collectionComments =+ fileCommentsMap.get(comment.collectionID) ?? [];+ fileCommentsMap.set(comment.collectionID, [+ ...collectionComments,+ comment,+ ]);+ next.set(fileID, fileCommentsMap);+ return next;+ });+ }, []);++ // Handle a comment being deleted+ const handleCommentDeleted = useCallback(+ (collectionID: number, commentID: string) => {+ const fileID = activeAnnotatedFile?.file.id;+ if (!fileID) return;++ setFileComments((prev) => {+ const next = new Map(prev);+ const fileCommentsMap = prev.get(fileID);+ if (fileCommentsMap) {+ const updatedMap = new Map(fileCommentsMap);+ const collectionComments =+ updatedMap.get(collectionID) ?? [];+ updatedMap.set(+ collectionID,+ collectionComments.map((c) =>+ c.id === commentID ? { ...c, isDeleted: true } : c,+ ),+ );+ next.set(fileID, updatedMap);+ }+ return next;+ });+ },+ [activeAnnotatedFile],+ );++ // Handle a comment reaction being added+ const handleCommentReactionAdded = useCallback(+ (reaction: UnifiedReaction) => {+ const fileID = activeAnnotatedFile?.file.id;+ if (!fileID) return;++ setAllReactions((prev) => {+ const next = new Map(prev);+ const fileReactionsMap = new Map<number, UnifiedReaction[]>(+ prev.get(fileID) ?? new Map(),+ );+ const collectionReactions =+ fileReactionsMap.get(reaction.collectionID) ?? [];+ fileReactionsMap.set(reaction.collectionID, [+ ...collectionReactions,+ reaction,+ ]);+ next.set(fileID, fileReactionsMap);+ return next;+ });+ },+ [activeAnnotatedFile],+ );++ // Handle a comment reaction being deleted+ const handleCommentReactionDeleted = useCallback(+ (collectionID: number, reactionID: string) => {+ const fileID = activeAnnotatedFile?.file.id;+ if (!fileID) return;++ setAllReactions((prev) => {+ const next = new Map(prev);+ const fileReactionsMap = prev.get(fileID);+ if (fileReactionsMap) {+ const updatedMap = new Map(fileReactionsMap);+ const collectionReactions =+ updatedMap.get(collectionID) ?? [];+ updatedMap.set(+ collectionID,+ collectionReactions.filter((r) => r.id !== reactionID),+ );+ next.set(fileID, updatedMap);+ }+ return next;+ });+ },+ [activeAnnotatedFile],+ );++ const handleViewLikes = useCallback(() => setOpenLikes(true), []);++ const handleLikesClose = useCallback(() => setOpenLikes(false), []);++ // Refs to access current state without causing re-renders+ // when used in callbacks that are dependencies of the PhotoSwipe effect.+ const activeAnnotatedFileRef = useRef(activeAnnotatedFile);+ activeAnnotatedFileRef.current = activeAnnotatedFile;++ const isPublicAlbum = isOfficialAlbumsApp || !!publicAlbumsCredentials;++ // Called when the like button (heart) is clicked.+ // - If public album: toggle like (unlike if already liked, else show modal)+ // - If gallery view: show album selector (like) OR unlike selector/direct delete+ // - If collection view: toggle like in that collection+ const handleLikeClick = useCallback(() => {+ if (isPublicAlbum) {+ const file = activeAnnotatedFileRef.current?.file;+ if (!file || !publicAlbumsCredentials) {+ setOpenPublicLikeModal(true);+ return;+ }++ const fileId = file.id;+ const collectionId = file.collectionID;+ const storedAnonIdentity = getStoredAnonIdentity(collectionId);++ // Check if already liked by current anon user (file-level only, not comment likes)+ const fileReactionsMap = allReactionsRef.current.get(fileId);+ const collectionReactions =+ fileReactionsMap?.get(collectionId) ?? [];+ const existingReaction = collectionReactions.find(+ (r) =>+ r.reactionType === "green_heart" &&+ !r.commentID &&+ storedAnonIdentity &&+ r.anonUserID === storedAnonIdentity.anonUserID,+ );++ if (existingReaction) {+ // Already liked - unlike (delete reaction)+ void (async () => {+ try {+ await deletePublicReaction(+ publicAlbumsCredentials,+ collectionId,+ existingReaction.id,+ );++ // Update local state+ setAllReactions((prev) => {+ const next = new Map(prev);+ const fileReactionsMap = new Map<+ number,+ UnifiedReaction[]+ >(prev.get(fileId) ?? new Map());+ const updatedReactions = (+ fileReactionsMap.get(collectionId) ?? []+ ).filter((r) => r.id !== existingReaction.id);+ fileReactionsMap.set(+ collectionId,+ updatedReactions,+ );+ next.set(fileId, fileReactionsMap);+ return next;+ });+ } catch (e) {+ log.error("Failed to delete public reaction", e);+ }+ })();+ } else if (storedAnonIdentity) {+ // Has identity but not liked - add reaction directly+ void (async () => {+ try {+ if (!collectionKey) {+ log.error(+ "Missing collection key for public reaction",+ );+ return;+ }+ const reactionId = await addPublicReaction(+ publicAlbumsCredentials,+ collectionId,+ fileId,+ "green_heart",+ collectionKey,+ );++ // Update local state+ setAllReactions((prev) => {+ const next = new Map(prev);+ const fileReactionsMap = new Map<+ number,+ UnifiedReaction[]+ >(prev.get(fileId) ?? new Map());+ const collectionReactions =+ fileReactionsMap.get(collectionId) ?? [];+ fileReactionsMap.set(collectionId, [+ ...collectionReactions,+ {+ id: reactionId,+ collectionID: collectionId,+ fileID: fileId,+ reactionType: "green_heart",+ userID: 0,+ anonUserID: storedAnonIdentity.anonUserID,+ isDeleted: false,+ createdAt: Date.now() * 1000,+ updatedAt: Date.now() * 1000,+ },+ ]);+ next.set(fileId, fileReactionsMap);+ return next;+ });+ } catch (e) {+ log.error("Failed to add public reaction", e);+ }+ })();+ } else {+ // No identity - show modal to get name+ setOpenPublicLikeModal(true);+ }+ return;+ }++ const file = activeAnnotatedFileRef.current?.file;+ if (!file) return;++ const fileId = file.id;+ const reactions = getUserFileReactions(fileId);+ const isGalleryView = !activeCollectionID || activeCollectionID === 0;++ if (isGalleryView) {+ // Gallery view - only consider shared collections+ const allCollectionIDs =+ fileNormalCollectionIDsRef.current?.get(fileId) ?? [];+ const collectionIDs = allCollectionIDs.filter((id) =>+ collectionSummariesRef.current+ ?.get(id)+ ?.attributes.has("shared"),+ );++ if (reactions.length === 0) {+ // Not liked in any collection+ if (collectionIDs.length === 1) {+ // Single album - like directly without showing modal+ const collectionId = collectionIDs[0]!;+ void (async () => {+ try {+ const collection =+ await getCollectionByID(collectionId);+ const reactionId = await addReaction(+ collectionId,+ fileId,+ "green_heart",+ collection.key,+ );+ setAllReactions((prev) => {+ const next = new Map(prev);+ const fileReactionsMap = new Map<+ number,+ UnifiedReaction[]+ >(prev.get(fileId) ?? new Map());+ const collectionReactions =+ fileReactionsMap.get(collectionId) ?? [];+ fileReactionsMap.set(collectionId, [+ ...collectionReactions,+ {+ id: reactionId,+ collectionID: collectionId,+ fileID: fileId,+ reactionType: "green_heart",+ userID: user?.id ?? 0,+ isDeleted: false,+ createdAt: Date.now() * 1000,+ updatedAt: Date.now() * 1000,+ },+ ]);+ next.set(fileId, fileReactionsMap);+ return next;+ });+ } catch (e) {+ log.error("Failed to add reaction", e);+ }+ })();+ } else {+ // Multiple albums - show album selector+ setOpenLikeAlbumSelector(true);+ }+ } else {+ // Liked in one or more collections - unlike from all+ void (async () => {+ try {+ const deletedReactionIds = new Set<string>();+ for (const reaction of reactions) {+ await deleteReaction(reaction.reactionId);+ deletedReactionIds.add(reaction.reactionId);+ }+ setAllReactions((prev) => {+ const next = new Map(prev);+ const fileReactionsMap = prev.get(fileId);+ if (fileReactionsMap) {+ const updatedMap = new Map(fileReactionsMap);+ for (const [+ collectionId,+ collectionReactions,+ ] of updatedMap) {+ updatedMap.set(+ collectionId,+ collectionReactions.filter(+ (r) =>+ !deletedReactionIds.has(r.id),+ ),+ );+ }+ next.set(fileId, updatedMap);+ }+ return next;+ });+ } catch (e) {+ log.error("Failed to delete reactions", e);+ }+ })();+ }+ } else {+ // Collection view - toggle like in this specific collection+ const existingReaction = reactions.find(+ (r) => r.collectionId === activeCollectionID,+ );++ if (existingReaction) {+ // Already liked in this collection - delete+ void (async () => {+ try {+ await deleteReaction(existingReaction.reactionId);+ setAllReactions((prev) => {+ const next = new Map(prev);+ const fileReactionsMap = prev.get(fileId);+ if (fileReactionsMap) {+ const updatedMap = new Map(fileReactionsMap);+ const collectionReactions =+ updatedMap.get(activeCollectionID) ?? [];+ updatedMap.set(+ activeCollectionID,+ collectionReactions.filter(+ (r) =>+ r.id !==+ existingReaction.reactionId,+ ),+ );+ next.set(fileId, updatedMap);+ }+ return next;+ });+ } catch (e) {+ log.error("Failed to delete reaction", e);+ }+ })();+ } else {+ // Not liked in this collection - add+ void (async () => {+ try {+ const collection =+ await getCollectionByID(activeCollectionID);+ const reactionId = await addReaction(+ activeCollectionID,+ fileId,+ "green_heart",+ collection.key,+ );+ setAllReactions((prev) => {+ const next = new Map(prev);+ const fileReactionsMap = new Map<+ number,+ UnifiedReaction[]+ >(prev.get(fileId) ?? new Map());+ const collectionReactions =+ fileReactionsMap.get(activeCollectionID) ?? [];+ fileReactionsMap.set(activeCollectionID, [+ ...collectionReactions,+ {+ id: reactionId,+ collectionID: activeCollectionID,+ fileID: fileId,+ reactionType: "green_heart",+ userID: user?.id ?? 0,+ isDeleted: false,+ createdAt: Date.now() * 1000,+ updatedAt: Date.now() * 1000,+ },+ ]);+ next.set(fileId, fileReactionsMap);+ return next;+ });+ } catch (e) {+ log.error("Failed to add reaction", e);+ }+ })();+ }+ }+ }, [+ activeCollectionID,+ getUserFileReactions,+ user?.id,+ isPublicAlbum,+ publicAlbumsCredentials,+ collectionKey,+ ]);++ const handleLikeAlbumSelectorClose = useCallback(+ () => setOpenLikeAlbumSelector(false),+ [],+ );++ const handleToggleAlbumLike = useCallback(+ (albumId: number, isCurrentlyLiked: boolean) => {+ const file = activeAnnotatedFileRef.current?.file;+ if (!file) return;++ const fileId = file.id;++ if (isCurrentlyLiked) {+ // Unlike - delete the reaction+ const reactions = getUserFileReactions(fileId);+ const reactionToDelete = reactions.find(+ (r) => r.collectionId === albumId,+ );++ if (reactionToDelete) {+ void (async () => {+ try {+ await deleteReaction(reactionToDelete.reactionId);+ setAllReactions((prev) => {+ const next = new Map(prev);+ const fileReactionsMap = prev.get(fileId);+ if (fileReactionsMap) {+ const updatedMap = new Map(+ fileReactionsMap,+ );+ const collectionReactions =+ updatedMap.get(albumId) ?? [];+ updatedMap.set(+ albumId,+ collectionReactions.filter(+ (r) =>+ r.id !==+ reactionToDelete.reactionId,+ ),+ );+ next.set(fileId, updatedMap);+ }+ return next;+ });+ } catch (e) {+ log.error("Failed to delete reaction", e);+ }+ })();+ }+ } else {+ // Like - add a reaction+ void (async () => {+ try {+ const collection = await getCollectionByID(albumId);+ const reactionId = await addReaction(+ albumId,+ fileId,+ "green_heart",+ collection.key,+ );+ setAllReactions((prev) => {+ const next = new Map(prev);+ const fileReactionsMap = new Map<+ number,+ UnifiedReaction[]+ >(prev.get(fileId) ?? new Map());+ const collectionReactions =+ fileReactionsMap.get(albumId) ?? [];+ fileReactionsMap.set(albumId, [+ ...collectionReactions,+ {+ id: reactionId,+ collectionID: albumId,+ fileID: fileId,+ reactionType: "green_heart",+ userID: user?.id ?? 0,+ isDeleted: false,+ createdAt: Date.now() * 1000,+ updatedAt: Date.now() * 1000,+ },+ ]);+ next.set(fileId, fileReactionsMap);+ return next;+ });+ } catch (e) {+ log.error("Failed to add reaction", e);+ }+ })();+ }+ // Don't close - user might want to toggle more albums+ },+ [getUserFileReactions, user?.id],+ );++ const handleLikeAll = useCallback(() => {+ const file = activeAnnotatedFileRef.current?.file;+ if (!file) return;++ const fileId = file.id;+ const collectionIDs = fileNormalCollectionIDs?.get(fileId) ?? [];+ const existingReactions = getUserFileReactions(fileId);+ const likedCollectionIDs = new Set(+ existingReactions.map((r) => r.collectionId),+ );++ // Filter to only shared collections not already liked+ const collectionsToLike = collectionIDs.filter(+ (id) =>+ !likedCollectionIDs.has(id) &&+ collectionSummaries?.get(id)?.attributes.has("shared"),+ );++ void (async () => {+ try {+ const newReactions: {+ collectionId: number;+ reactionId: string;+ }[] = [];+ for (const collectionId of collectionsToLike) {+ const collection = await getCollectionByID(collectionId);+ const reactionId = await addReaction(+ collectionId,+ fileId,+ "green_heart",+ collection.key,+ );+ newReactions.push({ collectionId, reactionId });+ }+ setAllReactions((prev) => {+ const next = new Map(prev);+ const fileReactionsMap = new Map<number, UnifiedReaction[]>(+ prev.get(fileId) ?? new Map(),+ );+ for (const { collectionId, reactionId } of newReactions) {+ const collectionReactions =+ fileReactionsMap.get(collectionId) ?? [];+ fileReactionsMap.set(collectionId, [+ ...collectionReactions,+ {+ id: reactionId,+ collectionID: collectionId,+ fileID: fileId,+ reactionType: "green_heart",+ userID: user?.id ?? 0,+ isDeleted: false,+ createdAt: Date.now() * 1000,+ updatedAt: Date.now() * 1000,+ },+ ]);+ }+ next.set(fileId, fileReactionsMap);+ return next;+ });+ } catch (e) {+ log.error("Failed to add reactions", e);+ }+ })();+ setOpenLikeAlbumSelector(false);+ }, [+ fileNormalCollectionIDs,+ getUserFileReactions,+ user?.id,+ collectionSummaries,+ ]);++ const handlePublicLikeModalClose = useCallback(+ () => setOpenPublicLikeModal(false),+ [],+ );++ const handleLikeAnonymously = useCallback(() => {+ setOpenPublicLikeModal(false);+ setOpenAddNameModal(true);+ }, []);++ const handleJoinAlbumToLike = useCallback(() => {+ setOpenPublicLikeModal(false);+ onJoinAlbum?.();+ }, [onJoinAlbum]);++ const handleAddNameModalClose = useCallback(+ () => setOpenAddNameModal(false),+ [],+ );++ const handleAddNameSubmit = useCallback(+ (name: string) => {+ const file = activeAnnotatedFileRef.current?.file;+ if (!file || !publicAlbumsCredentials || !collectionKey) {+ log.error(+ "Missing file, credentials, or collection key for public reaction",+ );+ setOpenAddNameModal(false);+ return;+ }++ const fileId = file.id;+ // Use file.collectionID for public albums since activeCollectionID is a pseudo ID (0)+ const collectionId =+ activeCollectionID && activeCollectionID > 0+ ? activeCollectionID+ : file.collectionID;++ void (async () => {+ try {+ // Check if we already have an anon identity for this collection, otherwise create one+ let identity = getStoredAnonIdentity(collectionId);+ if (!identity) {+ identity = await createAnonIdentity(+ publicAlbumsCredentials,+ collectionId,+ name,+ collectionKey,+ );+ }++ // Add the public reaction+ const reactionId = await addPublicReaction(+ publicAlbumsCredentials,+ collectionId,+ fileId,+ "green_heart",+ collectionKey,+ identity,+ );++ // Update local state+ setAllReactions((prev) => {+ const next = new Map(prev);+ const fileReactionsMap = new Map<+ number,+ UnifiedReaction[]+ >(prev.get(fileId) ?? new Map());+ const collectionReactions =+ fileReactionsMap.get(collectionId) ?? [];+ fileReactionsMap.set(collectionId, [+ ...collectionReactions,+ {+ id: reactionId,+ collectionID: collectionId,+ fileID: fileId,+ reactionType: "green_heart",+ // Use a special userID for anonymous users (derived from anonUserID)+ userID: 0,+ anonUserID: identity.anonUserID,+ isDeleted: false,+ createdAt: Date.now() * 1000,+ updatedAt: Date.now() * 1000,+ },+ ]);+ next.set(fileId, fileReactionsMap);+ return next;+ });++ // Update anonUserNames so the name shows immediately in likers list+ setAnonUserNames((prev) => {+ const next = new Map(prev);+ next.set(identity.anonUserID, name);+ return next;+ });++ setOpenAddNameModal(false);+ setOpenLikes(true);+ } catch (e) {+ log.error("Failed to add public reaction", e);+ onGenericError(e);+ setOpenAddNameModal(false);+ }+ })();+ },+ [+ activeCollectionID,+ publicAlbumsCredentials,+ collectionKey,+ onGenericError,+ ],+ );++ // Callback invoked when the download action is triggered by activating the+ // download button in the PhotoSwipe bar.+ const handleDownloadBarAction = useCallback(+ (annotatedFile: FileViewerAnnotatedFile) => {+ onDownload!(annotatedFile.file);+ },+ [onDownload],+ );++ // Callback invoked when the download action is triggered by activating the+ // download menu item in the more menu.+ //+ // Not memoized since it uses the frequently changing `activeAnnotatedFile`.+ const handleDownloadMenuAction = () => {+ handleMoreMenuCloseIfNeeded();+ onDownload!(activeAnnotatedFile!.file);+ };++ // Callback invoked when the send link action is triggered by activating the+ // send link menu item in the more menu.+ //+ // Not memoized since it uses the frequently changing `activeAnnotatedFile`.+ const handleSendLinkMenuAction = () => {+ handleMoreMenuCloseIfNeeded();+ onSendLink!(activeAnnotatedFile!.file);+ };++ const handleMore = useCallback(+ (buttonElement: HTMLElement) => setMoreMenuAnchorEl(buttonElement),+ [],+ );++ const handleMoreMenuCloseIfNeeded = useCallback(() => {+ setMoreMenuAnchorEl((el) => {+ if (el) resetMoreMenuButtonOnMenuClose(el);+ return null;+ });+ }, []);++ const handleConfirmDelete = useMemo(() => {+ return onDelete+ ? () => {+ handleMoreMenuCloseIfNeeded();+ setOpenConfirmDelete(true);+ }+ : undefined;+ }, [onDelete, handleMoreMenuCloseIfNeeded]);++ const handleConfirmDeleteClose = useCallback(+ () => setOpenConfirmDelete(false),+ [],+ );++ // Not memoized since it uses the frequently changing `activeAnnotatedFile`.+ const handleDelete = async () => {+ const file = activeAnnotatedFile!.file;+ await onDelete!(file);+ handleNeedsRemotePull();+ };++ // Not memoized since it uses the frequently changing `activeAnnotatedFile`.+ const handleCopyImage = useCallback(() => {+ handleMoreMenuCloseIfNeeded();+ if (!activeAnnotatedFile) return;+ const { imageURL } = activeAnnotatedFile.itemData;+ if (!imageURL) return;+ // Safari does not copy if we do not call `navigator.clipboard.write`+ // synchronously within the click event handler, but it does supports+ // passing a promise in lieu of the blob.+ void window.navigator.clipboard+ .write([+ new ClipboardItem({+ "image/png": createImagePNGBlob(imageURL),+ }),+ ])+ .catch(onGenericError);+ }, [onGenericError, handleMoreMenuCloseIfNeeded, activeAnnotatedFile]);++ const handleAddFileToCollection = useMemo(() => {+ if (!onAddFileToCollection || !activeAnnotatedFile) return undefined;+ return () => {+ handleMoreMenuCloseIfNeeded();+ const sourceSummaryID = fileNormalCollectionIDs+ ?.get(activeAnnotatedFile.file.id)+ ?.find((id) => id === activeCollectionID);+ onAddFileToCollection(activeAnnotatedFile.file, sourceSummaryID);+ };+ }, [+ onAddFileToCollection,+ handleMoreMenuCloseIfNeeded,+ fileNormalCollectionIDs,+ activeAnnotatedFile,+ activeCollectionID,+ ]);++ const handleEditImage = useMemo(() => {+ return onSaveEditedImageCopy+ ? () => {+ handleMoreMenuCloseIfNeeded();+ setOpenImageEditor(true);+ }+ : undefined;+ }, [onSaveEditedImageCopy, handleMoreMenuCloseIfNeeded]);++ const handleImageEditorClose = useCallback(+ () => setOpenImageEditor(false),+ [],+ );++ const handleSaveEditedCopy = useMemo(() => {+ return onSaveEditedImageCopy+ ? (+ editedFile: File,+ collection: Collection,+ enteFile: EnteFile,+ ) => {+ onSaveEditedImageCopy(editedFile, collection, enteFile);+ handleClose();+ }+ : undefined;+ }, [onSaveEditedImageCopy, handleClose]);++ const handleAnnotate = useCallback(+ (file: EnteFile, itemData: ItemData): FileViewerAnnotatedFile => {+ const fileID = file.id;+ const isOwnFile = file.ownerID == user?.id;++ const canModify =+ isOwnFile && !isInTrashSection && !isInHiddenSection;++ const showFavorite = canModify;++ const showArchive = canModify;++ const showDelete =+ !!handleConfirmDelete &&+ isOwnFile &&+ !isInTrashSection &&+ !isInIncomingSharedCollection;++ const showEditImage =+ !!handleEditImage && canModify && fileIsEditableImage(file);++ const showDownload = (() => {+ if (disableDownload) return undefined;+ if (!onDownload) return undefined;+ if (user) {+ // Logged in users see the download option in the more menu.+ return "menu";+ } else {+ // In public albums, the download option is shown in the bar+ // buttons, in lieu of the favorite option.+ return "bar";+ }+ })();++ const showCopyImage = (() => {+ if (disableDownload) return false;+ switch (file.metadata.fileType) {+ case FileType.image:+ case FileType.livePhoto:+ return true;+ default:+ return false;+ }+ })();++ const annotation: FileViewerFileAnnotation = {+ fileID,+ isOwnFile,+ showFavorite,+ showDownload,+ showDelete,+ showArchive,+ showCopyImage,+ showEditImage,+ };++ const annotatedFile = { file, annotation, itemData };+ setActiveAnnotatedFile(annotatedFile);+ return annotatedFile;+ },+ [+ user,+ disableDownload,+ isInIncomingSharedCollection,+ isInTrashSection,+ isInHiddenSection,+ onDownload,+ handleEditImage,+ handleConfirmDelete,+ ],+ );++ const handleSelectCollection = useMemo(() => {+ return onSelectCollection+ ? (collectionID: number) => {+ onSelectCollection(collectionID);+ handleClose();+ }+ : undefined;+ }, [onSelectCollection, handleClose]);++ const handleSelectPerson = useMemo(() => {+ return onSelectPerson+ ? (personID: string) => {+ onSelectPerson(personID);+ handleClose();+ }+ : undefined;+ }, [onSelectPerson, handleClose]);++ const haveUser = !!user;++ // Determine if social buttons (like, comment) should be shown.+ // They're shown for public albums or when viewing a shared collection.+ const showSocialButtons = useMemo(() => {+ // Show for public albums (no logged-in user).+ if (!haveUser) return true;+ // For logged-in users, check if the comments feature is enabled.+ if (!isCommentsFeatureEnabled) return false;+ // In collection view: check if that specific collection is shared.+ if (+ activeCollectionID &&+ activeCollectionID !== 0 &&+ collectionSummaries+ ) {+ const collectionSummary =+ collectionSummaries.get(activeCollectionID);+ if (collectionSummary?.attributes.has("shared")) return true;+ }+ return false;+ }, [+ haveUser,+ isCommentsFeatureEnabled,+ activeCollectionID,+ collectionSummaries,+ ]);++ // Check if a file belongs to any shared collection (for gallery view).+ const isFileInSharedCollection = useCallback(+ (fileID: number): boolean => {+ if (!collectionSummaries || !fileNormalCollectionIDs) return false;+ const collectionIDs = fileNormalCollectionIDs.get(fileID) ?? [];+ return collectionIDs.some((collectionID) => {+ const summary = collectionSummaries.get(collectionID);+ return summary?.attributes.has("shared");+ });+ },+ [collectionSummaries, fileNormalCollectionIDs],+ );++ // Delegate callback to check if social buttons should be shown for a file.+ const shouldShowSocialButtons_ = useCallback(+ ({ file }: FileViewerAnnotatedFile): boolean => {+ // If showSocialButtons is already true (public album or in shared+ // collection view), this won't be called. This callback is only+ // for gallery view where we need to check per-file.+ //+ // For logged-in users, require the comments feature to be enabled.+ if (!isCommentsFeatureEnabled) return false;+ //+ // If we're in a specific collection context (not gallery view),+ // return false - the collection's shared status is what matters,+ // not whether the file happens to be in some other shared album.+ const isGalleryView =+ !activeCollectionID || activeCollectionID === 0;+ if (!isGalleryView) return false;++ return isFileInSharedCollection(file.id);+ },+ [+ isCommentsFeatureEnabled,+ isFileInSharedCollection,+ activeCollectionID,+ ],+ );++ // Compute shared albums the file belongs to and which are liked for the modal+ const { allAlbumsForFile, likedAlbumIDs } = useMemo(() => {+ const file = activeAnnotatedFile?.file;+ if (!file)+ return { allAlbumsForFile: [], likedAlbumIDs: new Set<number>() };++ // Get all collections the file belongs to, filtered to only shared ones+ const collectionIDs = fileNormalCollectionIDs?.get(file.id) ?? [];+ const allAlbumsForFile = collectionIDs+ .filter((id) =>+ collectionSummaries?.get(id)?.attributes.has("shared"),+ )+ .map((id) => ({+ id,+ name: collectionNameByID?.get(id) ?? `Album ${id}`,+ }));++ // Get the set of liked album IDs from allReactions+ const fileReactionsMap = allReactions.get(file.id);+ const likedAlbumIDs = new Set<number>();++ if (fileReactionsMap) {+ for (const [collectionId, reactions] of fileReactionsMap) {+ // Get stored anonymous identity for this specific collection+ const storedAnonIdentity = getStoredAnonIdentity(collectionId);++ const hasUserLike = reactions.some((r) => {+ if (r.commentID || r.reactionType !== "green_heart")+ return false;+ // Check for logged-in user+ if (user?.id && r.userID === user.id) return true;+ // Check for anonymous user+ if (+ storedAnonIdentity &&+ r.anonUserID === storedAnonIdentity.anonUserID+ )+ return true;+ return false;+ });+ if (hasUserLike) {+ likedAlbumIDs.add(collectionId);+ }+ }+ }++ return { allAlbumsForFile, likedAlbumIDs };+ }, [+ activeAnnotatedFile,+ collectionNameByID,+ collectionSummaries,+ fileNormalCollectionIDs,+ allReactions,+ user?.id,+ ]);++ const getFiles = useCallback(() => files, [files]);++ const isFavorite = useCallback(+ ({ file }: FileViewerAnnotatedFile) => {+ if (+ !haveUser ||+ !favoriteFileIDs ||+ !pendingFavoriteUpdates ||+ !onToggleFavorite+ ) {+ return undefined;+ }+ return favoriteFileIDs.has(file.id);+ },+ [haveUser, favoriteFileIDs, pendingFavoriteUpdates, onToggleFavorite],+ );++ const isFavoritePending = useCallback(+ ({ file }: FileViewerAnnotatedFile) =>+ !!pendingFavoriteUpdates?.has(file.id),+ [pendingFavoriteUpdates],+ );++ const toggleFavorite = useCallback(+ ({ file }: FileViewerAnnotatedFile) =>+ onToggleFavorite!(file)+ .catch(onGenericError)+ .finally(handleNeedsRemotePull),+ [onToggleFavorite, onGenericError, handleNeedsRemotePull],+ );++ const isLiked = useCallback(+ ({ file }: FileViewerAnnotatedFile) => {+ const fileReactionsMap = allReactions.get(file.id);+ if (!fileReactionsMap) return false;++ // Check if user has liked this file in any collection+ for (const [collectionId, reactions] of fileReactionsMap) {+ // Get stored anonymous identity for this specific collection+ const storedAnonIdentity = getStoredAnonIdentity(collectionId);++ const hasUserLike = reactions.some((r) => {+ if (r.commentID || r.reactionType !== "green_heart")+ return false;+ // Check for logged-in user+ if (user?.id && r.userID === user.id) return true;+ // Check for anonymous user+ if (+ storedAnonIdentity &&+ r.anonUserID === storedAnonIdentity.anonUserID+ )+ return true;+ return false;+ });+ if (hasUserLike) return true;+ }+ return false;+ },+ [allReactions, user?.id],+ );++ const getCommentCount = useCallback(+ ({ file }: FileViewerAnnotatedFile) => {+ const commentsMap = fileComments.get(file.id);+ if (!commentsMap) return 0;++ const isGalleryView =+ !activeCollectionID || activeCollectionID === 0;+ if (isGalleryView) {+ // Return the count from the collection with most comments+ let maxCount = 0;+ for (const comments of commentsMap.values()) {+ const count = comments.filter((c) => !c.isDeleted).length;+ if (count > maxCount) maxCount = count;+ }+ return maxCount;+ } else {+ // Return count from the active collection+ const comments = commentsMap.get(activeCollectionID);+ return comments?.filter((c) => !c.isDeleted).length ?? 0;+ }+ },+ [fileComments, activeCollectionID],+ );++ const updateFullscreenStatus = useCallback(() => {+ setIsFullscreen(!!document.fullscreenElement);+ }, []);++ const handleToggleFullscreen = useCallback(() => {+ handleMoreMenuCloseIfNeeded();+ void (+ document.fullscreenElement+ ? document.exitFullscreen()+ : document.body.requestFullscreen()+ ).then(() => setTimeout(updateFullscreenStatus, 200));+ }, [handleMoreMenuCloseIfNeeded, updateFullscreenStatus]);++ const handleShortcuts = useCallback(() => {+ handleMoreMenuCloseIfNeeded();+ setOpenShortcuts(true);+ }, [handleMoreMenuCloseIfNeeded]);++ const handleShortcutsClose = useCallback(() => setOpenShortcuts(false), []);++ const shouldIgnoreKeyboardEvent = useCallback(() => {+ // Don't handle keydowns if any of the viewer's own modals are open.+ if (+ openFileInfo ||+ openComments ||+ openLikes ||+ openLikeAlbumSelector ||+ openPublicLikeModal ||+ !!moreMenuAnchorEl ||+ openImageEditor ||+ openConfirmDelete ||+ openShortcuts+ ) {+ return true;+ }++ // Also ignore keydowns if keyboard focus is inside an editable field+ // (e.g., when the CollectionSelector dialog's search TextField is focused)+ const activeElement = document.activeElement as HTMLElement | null;+ if (activeElement) {+ const tagName = activeElement.tagName;+ const role = activeElement.getAttribute("role");+ if (+ tagName === "INPUT" ||+ tagName === "TEXTAREA" ||+ tagName === "SELECT" ||+ activeElement.isContentEditable ||+ role === "textbox" ||+ role === "combobox"+ ) {+ return true;+ }+ }++ return false;+ }, [+ openFileInfo,+ openComments,+ openLikes,+ openLikeAlbumSelector,+ openPublicLikeModal,+ moreMenuAnchorEl,+ openImageEditor,+ openConfirmDelete,+ openShortcuts,+ ]);++ const canCopyImage = useCallback(+ () =>+ activeAnnotatedFile?.annotation.showCopyImage &&+ !!activeAnnotatedFile.itemData.imageURL,+ [activeAnnotatedFile],+ );++ const { isArchived, isPendingToggleArchive, toggleArchived } =+ useMemo(() => {+ let isArchived: boolean | undefined;+ let isPendingToggleArchive: boolean | undefined;+ let toggleArchived: (() => void) | undefined;++ const file = activeAnnotatedFile?.file;++ if (+ pendingVisibilityUpdates &&+ onFileVisibilityUpdate &&+ file &&+ activeAnnotatedFile.annotation.showArchive+ ) {+ switch (file.magicMetadata?.data.visibility) {+ case undefined:+ case ItemVisibility.visible:+ isArchived = false;+ break;+ case ItemVisibility.archived:+ isArchived = true;+ break;+ }++ isPendingToggleArchive = pendingVisibilityUpdates.has(file.id);++ toggleArchived = () => {+ handleMoreMenuCloseIfNeeded();+ void onFileVisibilityUpdate(+ file,+ isArchived+ ? ItemVisibility.visible+ : ItemVisibility.archived,+ )+ .then(handleNeedsRemotePull)+ .catch(onGenericError);+ };+ }++ return { isArchived, isPendingToggleArchive, toggleArchived };+ }, [+ pendingVisibilityUpdates,+ onFileVisibilityUpdate,+ onGenericError,+ handleNeedsRemotePull,+ handleMoreMenuCloseIfNeeded,+ activeAnnotatedFile,+ ]);++ const performKeyAction = useCallback<+ FileViewerPhotoSwipeDelegate["performKeyAction"]+ >(+ (action) => {+ switch (action) {+ case "delete":+ if (activeAnnotatedFile?.annotation.showDelete)+ handleConfirmDelete?.();+ break;+ case "toggle-archive":+ if (!isPendingToggleArchive) {+ // Provide extra visual feedback when the toggle archive+ // action is invoked via a keyboard shortcut since there+ // is no corresponding screen control visible (the more+ // menu might not be visible).+ onVisualFeedback();+ toggleArchived?.();+ }+ break;+ case "copy":+ if (canCopyImage()) handleCopyImage();+ break;+ case "toggle-fullscreen":+ handleToggleFullscreen();+ break;+ case "help":+ handleShortcuts();+ break;+ }+ },+ [+ onVisualFeedback,+ handleConfirmDelete,+ handleCopyImage,+ handleToggleFullscreen,+ handleShortcuts,+ activeAnnotatedFile,+ isPendingToggleArchive,+ toggleArchived,+ canCopyImage,+ ],+ );++ // Initial value of delegate.+ if (!delegateRef.current) {+ delegateRef.current = {+ getFiles,+ isFavorite,+ isFavoritePending,+ toggleFavorite,+ isLiked,+ getCommentCount,+ shouldShowSocialButtons: shouldShowSocialButtons_,+ shouldIgnoreKeyboardEvent,+ performKeyAction,+ };+ }++ // Updates to delegate callbacks.+ useEffect(() => {+ const delegate = delegateRef.current!;+ delegate.getFiles = getFiles;+ delegate.isFavorite = isFavorite;+ delegate.isFavoritePending = isFavoritePending;+ delegate.toggleFavorite = toggleFavorite;+ delegate.isLiked = isLiked;+ delegate.getCommentCount = getCommentCount;+ delegate.shouldShowSocialButtons = shouldShowSocialButtons_;+ delegate.shouldIgnoreKeyboardEvent = shouldIgnoreKeyboardEvent;+ delegate.performKeyAction = performKeyAction;+ }, [+ getFiles,+ isFavorite,+ isFavoritePending,+ toggleFavorite,+ isLiked,+ getCommentCount,+ shouldShowSocialButtons_,+ shouldIgnoreKeyboardEvent,+ performKeyAction,+ ]);++ // Handle updates to files.+ //+ // See: [Note: Updates to the files prop for FileViewer]+ useEffect(() => {+ if (!files.length) {+ // If there are no more files left, close the viewer.+ handleClose();+ } else if (open && activeAnnotatedFile) {+ // Only refresh if the viewer is still open and we have an active file.+ // This prevents race conditions when navigating away (e.g., when clicking+ // the navigate button in AlbumAddedNotification while the viewer is open).+ psRef.current?.refreshSlideOnFilesUpdateIfNeeded();+ }+ }, [handleClose, files, open, activeAnnotatedFile]);++ useEffect(() => {+ // This effect might get triggered when the none of the files that were+ // being shown are eligible to be shown anymore. e.g. suppose we are the+ // archiveItems pseudo-collection, and the only archived file there is+ // marked as unarchived by the user within the file viewer.+ //+ // In such cases, don't attempt to refresh since that causes various+ // invariants (like the existence of a "currentFile") to get broken+ // inside the `FileViewerPhotoSwipe` implementation.+ if (open && files.length) {+ psRef.current?.refreshCurrentSlideFavoriteButtonIfNeeded();+ }+ }, [favoriteFileIDs, pendingFavoriteUpdates, files, open]);++ // Refresh like button when allReactions changes.+ useEffect(() => {+ if (open && files.length) {+ psRef.current?.refreshCurrentSlideLikeButtonIfNeeded();+ }+ }, [allReactions, files, open]);++ // Fetch comments and reactions for the current file (only for shared albums).+ const activeFileID = activeAnnotatedFile?.file.id;+ useEffect(() => {+ if (!open || !activeFileID) return;++ // Only fetch social data if social buttons should be shown.+ // In collection view, use showSocialButtons (based on that collection).+ // In gallery view, check if the file is in any shared collection.+ const isGalleryView = !activeCollectionID || activeCollectionID === 0;+ const shouldFetch =+ showSocialButtons ||+ (isCommentsFeatureEnabled &&+ isGalleryView &&+ isFileInSharedCollection(activeFileID));+ if (!shouldFetch) return;++ void (async () => {+ try {+ const commentsMap = new Map<number, Comment[]>();+ const reactionsMap = new Map<number, UnifiedReaction[]>();+ const newUserIDToEmail = new Map<number, string>();+ const newAnonUserNames = new Map<string, string>();++ const collectionIDs = isGalleryView+ ? (fileNormalCollectionIDs?.get(activeFileID) ?? [])+ : [activeCollectionID];++ for (const collectionId of collectionIDs) {+ try {+ const collection =+ await getCollectionByID(collectionId);++ // Cache collection data for polling refresh+ collectionCacheRef.current.set(collectionId, {+ key: collection.key,+ ownerID: collection.owner.id,+ ownerEmail: collection.owner.email,+ sharees: collection.sharees.map((s) => ({+ id: s.id,+ email: s.email,+ })),+ hasPublicURLs: collection.publicURLs.length > 0,+ });++ // Build user ID to email map from collection owner and sharees+ if (collection.owner.email) {+ newUserIDToEmail.set(+ collection.owner.id,+ collection.owner.email,+ );+ }+ for (const sharee of collection.sharees) {+ if (sharee.email) {+ newUserIDToEmail.set(sharee.id, sharee.email);+ }+ }++ const { comments, reactions } =+ await getUnifiedSocialDiff(+ collectionId,+ activeFileID,+ collection.key,+ );++ commentsMap.set(collectionId, comments);+ reactionsMap.set(collectionId, reactions);++ // Fetch anonymous user profiles only if collection has public links+ if (collection.publicURLs.length > 0) {+ try {+ const anonProfiles = await getAnonProfiles(+ collectionId,+ collection.key,+ );+ for (const [+ anonUserID,+ userName,+ ] of anonProfiles) {+ newAnonUserNames.set(anonUserID, userName);+ }+ } catch {+ // Ignore anon profiles fetch failures+ }+ }+ } catch {+ // Skip collections that fail to fetch+ }+ }++ setFileComments((prev) => {+ const next = new Map(prev);+ next.set(activeFileID, commentsMap);+ return next;+ });++ setAllReactions((prev) => {+ const next = new Map(prev);+ next.set(activeFileID, reactionsMap);+ return next;+ });++ setUserIDToEmail((prev) => {+ const next = new Map(prev);+ for (const [id, email] of newUserIDToEmail) {+ next.set(id, email);+ }+ return next;+ });++ setAnonUserNames((prev) => {+ const next = new Map(prev);+ for (const [id, name] of newAnonUserNames) {+ next.set(id, name);+ }+ return next;+ });+ } catch (e) {+ log.error("Failed to fetch social data", e);+ setFileComments((prev) => {+ const next = new Map(prev);+ next.delete(activeFileID);+ return next;+ });+ setAllReactions((prev) => {+ const next = new Map(prev);+ next.delete(activeFileID);+ return next;+ });+ }+ })();+ }, [+ open,+ activeFileID,+ activeCollectionID,+ fileNormalCollectionIDs,+ showSocialButtons,+ isFileInSharedCollection,+ isCommentsFeatureEnabled,+ ]);++ // Fetch social data (comments + reactions) for public albums (when viewing as anonymous user).+ useEffect(() => {+ if (+ !open ||+ !enableComment ||+ !activeFileID ||+ !publicAlbumsCredentials ||+ !collectionKey+ )+ return;++ const file = files.find((f) => f.id === activeFileID);+ if (!file) return;++ void (async () => {+ try {+ // Fetch both comments and reactions in a single API call+ const { comments, reactions } = await getPublicSocialDiff(+ publicAlbumsCredentials,+ activeFileID,+ collectionKey,+ );++ // Convert PublicComment to Comment format+ const commentsForFile: Comment[] = comments.map((c) => ({+ id: c.id,+ collectionID: c.collectionID,+ fileID: c.fileID,+ parentCommentID: c.parentCommentID,+ userID: c.userID,+ anonUserID: c.anonUserID,+ text: c.text,+ isDeleted: c.isDeleted,+ createdAt: c.createdAt,+ updatedAt: c.updatedAt,+ }));++ const commentsMap = new Map<number, Comment[]>();+ commentsMap.set(file.collectionID, commentsForFile);++ setFileComments((prev) => {+ const next = new Map(prev);+ next.set(activeFileID, commentsMap);+ return next;+ });++ // Convert PublicReaction to UnifiedReaction format+ const unifiedReactions: UnifiedReaction[] = reactions.map(+ (r) => ({+ id: r.id,+ collectionID: file.collectionID,+ fileID: r.fileID,+ commentID: r.commentID,+ reactionType: r.reactionType,+ userID: r.userID,+ anonUserID: r.anonUserID,+ isDeleted: r.isDeleted,+ createdAt: r.createdAt,+ updatedAt: r.updatedAt,+ }),+ );++ const reactionsMap = new Map<number, UnifiedReaction[]>();+ reactionsMap.set(file.collectionID, unifiedReactions);++ setAllReactions((prev) => {+ const next = new Map(prev);+ next.set(activeFileID, reactionsMap);+ return next;+ });++ // Fetch anonymous user profiles for public albums+ try {+ const anonProfiles = await getPublicAnonProfiles(+ publicAlbumsCredentials,+ collectionKey,+ );+ setAnonUserNames((prev) => {+ const next = new Map(prev);+ for (const [id, name] of anonProfiles) {+ next.set(id, name);+ }+ return next;+ });+ } catch {+ // Ignore anon profiles fetch failures+ }++ // Fetch registered participants' masked emails for public albums+ try {+ const participantEmails =+ await getPublicParticipantsMaskedEmails(+ publicAlbumsCredentials,+ );+ setUserIDToEmail((prev) => {+ const next = new Map(prev);+ for (const [id, email] of participantEmails) {+ next.set(id, email);+ }+ return next;+ });+ } catch {+ // Ignore participants fetch failures+ }+ } catch (e) {+ log.error("Failed to fetch public social data", e);+ }+ })();+ }, [+ open,+ enableComment,+ activeFileID,+ publicAlbumsCredentials,+ collectionKey,+ files,+ ]);++ // Refresh comment count when fileComments changes.+ useEffect(() => {+ if (open && files.length) {+ psRef.current?.refreshCurrentSlideCommentCountIfNeeded();+ }+ }, [fileComments, files, open]);++ // Polling interval for refreshing social data (5 seconds)+ const SOCIAL_REFRESH_INTERVAL_MS = 5_000;++ // Refresh social data for logged-in users (uses cached collection keys)+ const refreshSocialData = useCallback(async () => {+ if (!activeFileID) return;++ const isGalleryView = !activeCollectionID || activeCollectionID === 0;+ const shouldFetch =+ showSocialButtons ||+ (isCommentsFeatureEnabled &&+ isGalleryView &&+ isFileInSharedCollection(activeFileID));+ if (!shouldFetch) return;++ try {+ const commentsMap = new Map<number, Comment[]>();+ const reactionsMap = new Map<number, UnifiedReaction[]>();+ const newAnonUserNames = new Map<string, string>();++ const collectionIDs = isGalleryView+ ? (fileNormalCollectionIDs?.get(activeFileID) ?? [])+ : [activeCollectionID];++ for (const collectionId of collectionIDs) {+ // Use cached collection data (populated during initial fetch)+ const cached = collectionCacheRef.current.get(collectionId);+ if (!cached) continue; // Skip if not in cache++ try {+ const { comments, reactions } = await getUnifiedSocialDiff(+ collectionId,+ activeFileID,+ cached.key,+ );++ commentsMap.set(collectionId, comments);+ reactionsMap.set(collectionId, reactions);++ if (cached.hasPublicURLs) {+ try {+ const anonProfiles = await getAnonProfiles(+ collectionId,+ cached.key,+ );+ for (const [anonUserID, userName] of anonProfiles) {+ newAnonUserNames.set(anonUserID, userName);+ }+ } catch {+ // Ignore+ }+ }+ } catch {+ // Skip failed collections+ }+ }++ setFileComments((prev) => {+ const next = new Map(prev);+ next.set(activeFileID, commentsMap);+ return next;+ });++ setAllReactions((prev) => {+ const next = new Map(prev);+ next.set(activeFileID, reactionsMap);+ return next;+ });++ setAnonUserNames((prev) => {+ const next = new Map(prev);+ for (const [id, name] of newAnonUserNames) {+ next.set(id, name);+ }+ return next;+ });+ } catch (e) {+ log.error("Failed to refresh social data", e);+ }+ }, [+ activeFileID,+ activeCollectionID,+ fileNormalCollectionIDs,+ showSocialButtons,+ isFileInSharedCollection,+ isCommentsFeatureEnabled,+ ]);++ // Refresh social data for public albums+ const refreshPublicSocialData = useCallback(async () => {+ if (+ !activeFileID ||+ !publicAlbumsCredentials ||+ !collectionKey ||+ !enableComment+ )+ return;++ const file = files.find((f) => f.id === activeFileID);+ if (!file) return;++ try {+ const { comments, reactions } = await getPublicSocialDiff(+ publicAlbumsCredentials,+ activeFileID,+ collectionKey,+ );++ const commentsForFile: Comment[] = comments.map((c) => ({+ id: c.id,+ collectionID: c.collectionID,+ fileID: c.fileID,+ parentCommentID: c.parentCommentID,+ userID: c.userID,+ anonUserID: c.anonUserID,+ text: c.text,+ isDeleted: c.isDeleted,+ createdAt: c.createdAt,+ updatedAt: c.updatedAt,+ }));++ const commentsMap = new Map<number, Comment[]>();+ commentsMap.set(file.collectionID, commentsForFile);++ setFileComments((prev) => {+ const next = new Map(prev);+ next.set(activeFileID, commentsMap);+ return next;+ });++ const unifiedReactions: UnifiedReaction[] = reactions.map((r) => ({+ id: r.id,+ collectionID: file.collectionID,+ fileID: r.fileID,+ commentID: r.commentID,+ reactionType: r.reactionType,+ userID: r.userID,+ anonUserID: r.anonUserID,+ isDeleted: r.isDeleted,+ createdAt: r.createdAt,+ updatedAt: r.updatedAt,+ }));++ const reactionsMap = new Map<number, UnifiedReaction[]>();+ reactionsMap.set(file.collectionID, unifiedReactions);++ setAllReactions((prev) => {+ const next = new Map(prev);+ next.set(activeFileID, reactionsMap);+ return next;+ });++ // Fetch anon profiles (new anonymous users may have commented)+ try {+ const anonProfiles = await getPublicAnonProfiles(+ publicAlbumsCredentials,+ collectionKey,+ );+ setAnonUserNames((prev) => {+ const next = new Map(prev);+ for (const [id, name] of anonProfiles) {+ next.set(id, name);+ }+ return next;+ });+ } catch {+ // Ignore+ }+ // Note: Masked emails for registered participants are fetched only+ // on initial load since they rarely change during a session.+ } catch (e) {+ log.error("Failed to refresh public social data", e);+ }+ }, [+ activeFileID,+ publicAlbumsCredentials,+ collectionKey,+ enableComment,+ files,+ ]);++ // Poll for social data when comments or likes sidebar is open (logged-in users)+ useInterval(+ refreshSocialData,+ (openComments || openLikes) && !publicAlbumsCredentials+ ? SOCIAL_REFRESH_INTERVAL_MS+ : null,+ );++ // Poll for social data when comments or likes sidebar is open (public albums)+ useInterval(+ refreshPublicSocialData,+ (openComments || openLikes) && publicAlbumsCredentials+ ? SOCIAL_REFRESH_INTERVAL_MS+ : null,+ );++ useEffect(() => {+ if (open) {+ // We're open. Create psRef. This will show the file viewer dialog.+ log.debug(() => "Opening file viewer");++ const pswp = new FileViewerPhotoSwipe({+ initialIndex,+ haveUser,+ isPublicAlbum,+ showSocialButtons,+ enableComment,+ showFullscreenButton,+ disableEscapeClose,+ delegate: delegateRef.current!,+ onClose: () => {+ if (psRef.current) handleClose();+ },+ onAnnotate: handleAnnotate,+ onViewInfo: handleViewInfo,+ onViewComments: handleViewComments,+ onViewLikes: handleViewLikes,+ onLikeClick: handleLikeClick,+ onDownload: handleDownloadBarAction,+ onMore: handleMore,+ });++ psRef.current = pswp;++ return () => {+ // Close dialog in the effect callback.+ log.debug(() => "Closing file viewer");+ pswp.closeIfNeeded();+ };+ } else {+ return undefined;+ }+ // Be careful with adding new dependencies here, or changing the source+ // of existing ones. If any of these dependencies change unnecessarily,+ // then the file viewer will start getting reloaded even when it is+ // already open.+ //+ // Note: showSocialButtons and enableComment are intentionally NOT included+ // here even though they're passed to the constructor. The delegate's+ // shouldShowSocialButtons handles dynamic visibility, and these values only+ // change based on collectionSummaries which we don't want to trigger a full+ // recreation.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [+ open,+ onClose,+ user,+ initialIndex,+ disableDownload,+ showFullscreenButton,+ disableEscapeClose,+ haveUser,+ isPublicAlbum,+ handleClose,+ handleAnnotate,+ handleViewInfo,+ handleViewComments,+ handleViewLikes,+ handleLikeClick,+ handleDownloadBarAction,+ handleMore,+ ]);++ useEffect(() => {+ if (!open || !shouldCloseOnBrowserBack) return;++ // In public albums, consume one browser-back action to close the+ // viewer overlay instead of navigating away from the shared link.+ const stateMarker = `${Date.now()}-${Math.random().toString(36).slice(2)}`;+ browserBackStateRef.current = stateMarker;++ const currentState: unknown = window.history.state;+ const viewerState = addFileViewerBackStateMarker(+ currentState,+ stateMarker,+ );+ window.history.pushState(viewerState, "", window.location.href);++ const handlePopState = () => {+ if (browserBackStateRef.current != stateMarker) return;+ browserBackStateRef.current = undefined;+ handleCloseRef.current();+ };++ window.addEventListener("popstate", handlePopState);++ return () => {+ window.removeEventListener("popstate", handlePopState);+ if (browserBackStateRef.current != stateMarker) return;+ browserBackStateRef.current = undefined;++ const latestHistoryState: unknown = window.history.state;+ if (hasFileViewerBackStateMarker(latestHistoryState, stateMarker)) {+ window.history.back();+ }+ };+ }, [open, shouldCloseOnBrowserBack]);++ const handleFileMetadataUpdate = useMemo(() => {+ return onRemoteFilesPull+ ? async () => {+ // Wait for the files pull to complete.+ await onRemoteFilesPull();+ // Set the flag to trigger the full pull later.+ handleNeedsRemotePull();+ }+ : undefined;+ }, [onRemoteFilesPull, handleNeedsRemotePull]);++ const handleUpdateCaption = useCallback(+ (fileID: number, newCaption: string) => {+ updateItemDataAlt(fileID, newCaption);+ psRef.current!.refreshCurrentSlideContent();+ },+ [],+ );++ useEffect(updateFullscreenStatus, [updateFullscreenStatus]);++ if (!activeAnnotatedFile) {+ return <></>;+ }++ return (+ <>+ <FileInfo+ open={openFileInfo}+ onClose={handleFileInfoClose}+ file={activeAnnotatedFile.file}+ exif={activeFileExif}+ allowEdits={!!activeAnnotatedFile.annotation.isOwnFile}+ allowMap={haveUser}+ showCollections={haveUser && !isInHiddenSection}+ fileCollectionIDs={fileNormalCollectionIDs}+ onFileMetadataUpdate={handleFileMetadataUpdate}+ onUpdateCaption={handleUpdateCaption}+ onSelectCollection={handleSelectCollection}+ onSelectPerson={handleSelectPerson}+ {...{ collectionNameByID }}+ />+ <CommentsSidebar+ open={openComments}+ onClose={handleCommentsClose}+ file={activeAnnotatedFile.file}+ activeCollectionID={activeCollectionID}+ fileNormalCollectionIDs={fileNormalCollectionIDs}+ collectionSummaries={collectionSummaries}+ currentUserID={user?.id}+ prefetchedComments={fileComments.get(+ activeAnnotatedFile.file.id,+ )}+ prefetchedReactions={allReactions.get(+ activeAnnotatedFile.file.id,+ )}+ prefetchedUserIDToEmail={userIDToEmail}+ onCommentAdded={handleCommentAdded}+ onCommentDeleted={handleCommentDeleted}+ onCommentReactionAdded={handleCommentReactionAdded}+ onCommentReactionDeleted={handleCommentReactionDeleted}+ highlightCommentID={highlightCommentID}+ publicAlbumsCredentials={publicAlbumsCredentials}+ collectionKey={collectionKey}+ anonUserNames={anonUserNames}+ onJoinAlbum={onJoinAlbum}+ enableJoin={enableJoin}+ />+ <LikesSidebar+ open={openLikes}+ onClose={handleLikesClose}+ file={activeAnnotatedFile.file}+ activeCollectionID={activeCollectionID}+ fileNormalCollectionIDs={fileNormalCollectionIDs}+ collectionSummaries={collectionSummaries}+ currentUserID={user?.id}+ prefetchedReactions={allReactions.get(+ activeAnnotatedFile.file.id,+ )}+ prefetchedUserIDToEmail={userIDToEmail}+ anonUserNames={anonUserNames}+ />+ <LikeAlbumSelectorModal+ open={openLikeAlbumSelector}+ onClose={handleLikeAlbumSelectorClose}+ albums={allAlbumsForFile}+ likedAlbumIDs={likedAlbumIDs}+ onToggleAlbum={handleToggleAlbumLike}+ onLikeAll={handleLikeAll}+ />+ <PublicLikeModal+ open={openPublicLikeModal}+ onClose={handlePublicLikeModalClose}+ onLikeAnonymously={handleLikeAnonymously}+ onJoinAlbumToLike={handleJoinAlbumToLike}+ enableJoin={enableJoin}+ />+ <AddNameModal+ open={openAddNameModal}+ onClose={handleAddNameModalClose}+ onSubmit={handleAddNameSubmit}+ />+ <MoreMenu+ open={!!moreMenuAnchorEl}+ onClose={handleMoreMenuCloseIfNeeded}+ anchorEl={moreMenuAnchorEl}+ id={moreMenuID}+ disableAutoFocusItem+ slotProps={{ list: { "aria-labelledby": moreButtonID } }}+ >+ {activeAnnotatedFile.annotation.showDownload == "menu" && (+ <MoreMenuItem onClick={handleDownloadMenuAction}>+ <MoreMenuItemTitle>{t("download")}</MoreMenuItemTitle>+ <FileDownloadOutlinedIcon />+ </MoreMenuItem>+ )}+ {activeAnnotatedFile.annotation.isOwnFile &&+ !isInTrashSection &&+ onSendLink && (+ <MoreMenuItem onClick={handleSendLinkMenuAction}>+ <MoreMenuItemTitle>Send link</MoreMenuItemTitle>+ <HugeiconsIcon icon={Navigation03Icon} size={20} />+ </MoreMenuItem>+ )}+ {activeAnnotatedFile.annotation.showDelete && (+ <MoreMenuItem onClick={handleConfirmDelete}>+ <MoreMenuItemTitle>{t("delete")}</MoreMenuItemTitle>+ <DeleteIcon />+ </MoreMenuItem>+ )}+ {isArchived !== undefined && (+ <MoreMenuItem+ onClick={toggleArchived}+ disabled={isPendingToggleArchive}+ >+ <MoreMenuItemTitle>+ {isArchived ? t("unarchive") : t("archive")}+ </MoreMenuItemTitle>+ {isArchived ? (+ <UnArchiveIcon />+ ) : (+ <ArchiveOutlinedIcon />+ )}+ </MoreMenuItem>+ )}+ {handleAddFileToCollection &&+ activeAnnotatedFile.annotation.isOwnFile && (+ <MoreMenuItem onClick={handleAddFileToCollection}>+ <MoreMenuItemTitle>+ {t("add_to_album")}+ </MoreMenuItemTitle>+ <AddIcon />+ </MoreMenuItem>+ )}+ {canCopyImage() && (+ <MoreMenuItem onClick={handleCopyImage}>+ <MoreMenuItemTitle>+ {t("copy_as_png")}+ </MoreMenuItemTitle>+ {/* Tweak icon size to visually fit better with neighbours */}+ <ContentCopyIcon sx={{ "&&": { fontSize: "18px" } }} />+ </MoreMenuItem>+ )}++ {activeAnnotatedFile.annotation.showEditImage && (+ <MoreMenuItem onClick={handleEditImage}>+ <MoreMenuItemTitle>{t("edit_image")}</MoreMenuItemTitle>+ <EditIcon />+ </MoreMenuItem>+ )}+ <MoreMenuItem+ onClick={handleToggleFullscreen}+ divider+ sx={{+ borderColor: "fixed.dark.divider",+ /* 12px + 2px */+ pb: "14px",+ }}+ >+ <MoreMenuItemTitle>+ {isFullscreen+ ? t("exit_fullscreen")+ : t("go_fullscreen")}+ </MoreMenuItemTitle>+ {isFullscreen ? (+ <FullscreenExitOutlinedIcon />+ ) : (+ <FullscreenOutlinedIcon />+ )}+ </MoreMenuItem>+ <MoreMenuItem onClick={handleShortcuts} sx={{ mt: "2px" }}>+ <Typography sx={{ color: "fixed.dark.text.faint" }}>+ {t("shortcuts")}+ </Typography>+ </MoreMenuItem>+ </MoreMenu>+ <ConfirmDeleteFileDialog+ open={openConfirmDelete}+ onClose={handleConfirmDeleteClose}+ onConfirm={handleDelete}+ />+ {handleSaveEditedCopy && (+ <ImageEditorOverlay+ open={openImageEditor}+ onClose={handleImageEditorClose}+ file={activeAnnotatedFile.file}+ onSaveEditedCopy={handleSaveEditedCopy}+ />+ )}+ <Shortcuts+ open={openShortcuts}+ onClose={handleShortcutsClose}+ {...{ disableDownload, haveUser }}+ />+ </>+ );+};++const MoreMenu = styled(Menu)(+ ({ theme }) => `+ & .MuiPaper-root {+ background-color: ${theme.vars.palette.fixed.dark.background.paper};+ }+ & .MuiList-root {+ padding-block: 2px;+ }+`,+);++const MoreMenuItem = styled(MenuItem)(+ ({ theme }) => `+ min-width: 210px;++ /* MUI MenuItem default implementation has a minHeight of "48px" below the+ "sm" breakpoint, and auto after it. We always want the same height, so+ set minHeight auto and use an explicit padding always to come out to 44px+ (20px (icon or Typography height + 12 + 12) */+ padding-block: 12px;+ min-height: auto;++ gap: 1;+ justify-content: space-between;+ align-items: center;++ /* Same as other controls on the PhotoSwipe UI */+ color: rgba(255 255 255 / 0.85);+ &:hover {+ color: rgba(255 255 255 / 1);+ background-color: ${theme.vars.palette.fixed.dark.background.paper2}+ }++ .MuiSvgIcon-root {+ font-size: 20px;+ }+`,+);++const MoreMenuItemTitle: React.FC<React.PropsWithChildren> = ({ children }) => (+ <Typography sx={{ fontWeight: "medium" }}>{children}</Typography>+);++type ConfirmDeleteFileDialogProps = ModalVisibilityProps & {+ /**+ * Called when the user confirms the deletion.+ *+ * The delete button will show an activity indicator until this async+ * operation completes.+ */+ onConfirm: () => Promise<void>;+};++/**+ * A bespoke variant of AttributedMiniDialog for use by the delete file+ * confirmation prompt that we show in the file viewer.+ *+ * - It auto focuses the primary action.+ * - It uses a lighter backdrop in light mode.+ */+const ConfirmDeleteFileDialog: React.FC<ConfirmDeleteFileDialogProps> = ({+ open,+ onClose,+ onConfirm,+}) => {+ const [phase, setPhase] = useState<"loading" | "failed" | undefined>();++ const resetPhaseAndClose = () => {+ setPhase(undefined);+ onClose();+ };++ const handleClick = async () => {+ setPhase("loading");+ try {+ await onConfirm();+ resetPhaseAndClose();+ } catch (e) {+ log.error(e);+ setPhase("failed");+ }+ };++ const handleClose: ModalProps["onClose"] = (_, reason) => {+ // Ignore backdrop clicks when we're processing the user request.+ if (reason == "backdropClick" && phase == "loading") return;+ resetPhaseAndClose();+ };++ return (+ <TitledMiniDialog+ open={open}+ onClose={handleClose}+ title={t("trash_file_title")}+ sx={(theme) => ({+ // See: [Note: Lighter backdrop for overlays on photo viewer]+ ...theme.applyStyles("light", {+ ".MuiBackdrop-root": {+ backgroundColor: theme.vars.palette.backdrop.faint,+ },+ }),+ })}+ >+ <Typography sx={{ color: "text.muted" }}>+ {t("trash_file_message")}+ </Typography>+ <Stack sx={{ pt: 3, gap: 1 }}>+ {phase == "failed" && <InlineErrorIndicator />}+ <LoadingButton+ loading={phase == "loading"}+ fullWidth+ color="critical"+ autoFocus+ onClick={handleClick}+ >+ {t("move_to_trash")}+ </LoadingButton>+ <FocusVisibleButton+ fullWidth+ color="secondary"+ disabled={phase == "loading"}+ onClick={resetPhaseAndClose}+ >+ {t("cancel")}+ </FocusVisibleButton>+ </Stack>+ </TitledMiniDialog>+ );+};++type ShortcutsProps = ModalVisibilityProps &+ Pick<FileViewerProps, "disableDownload"> & {+ /**+ * `true` if we're running in a context where there is a logged in user.+ */+ haveUser: boolean;+ };++const Shortcuts: React.FC<ShortcutsProps> = ({+ open,+ onClose,+ disableDownload,+ haveUser,+}) => (+ <Dialog+ {...{ open, onClose }}+ fullWidth+ fullScreen={useIsSmallWidth()}+ slotProps={{ backdrop: { sx: { backdropFilter: "blur(30px)" } } }}+ >+ <SpacedRow sx={{ pt: 2, px: 2.5 }}>+ <DialogTitle>{t("shortcuts")}</DialogTitle>+ <DialogCloseIconButton {...{ onClose }} />+ </SpacedRow>+ <ShortcutsContent>+ <Shortcut action={t("close")} shortcut={ut("Esc")} />+ <Shortcut+ action={formattedListJoin([t("previous"), t("next")])}+ shortcut={`${formattedListJoin([ut("←"), ut("→")])} ${ut("(Option/Alt)")}`}+ />+ <Shortcut+ action={t("video_seek")}+ shortcut={formattedListJoin([ut("←"), ut("→")])}+ />+ <Shortcut+ action={t("zoom")}+ shortcut={formattedListJoin([t("mouse_scroll"), t("pinch")])}+ />+ <Shortcut+ action={t("zoom_preset")}+ shortcut={formattedListJoin([ut("Z"), t("tap_inside_image")])}+ />+ <Shortcut+ action={t("toggle_controls")}+ shortcut={formattedListJoin([ut("H"), t("tap_outside_image")])}+ />+ <Shortcut+ action={t("pan")}+ shortcut={formattedListJoin([ut("W A S D"), t("drag")])}+ />+ <Shortcut+ action={formattedListJoin([t("play"), t("pause")])}+ shortcut={ut("Space")}+ />+ <Shortcut action={t("toggle_live")} shortcut={ut("Space")} />+ <Shortcut action={t("toggle_audio")} shortcut={ut("M")} />+ {haveUser && (+ <Shortcut action={t("toggle_favorite")} shortcut={ut("L")} />+ )}+ <Shortcut action={t("view_info")} shortcut={ut("I")} />+ {!disableDownload && (+ <Shortcut action={t("download")} shortcut={ut("K")} />+ )}+ {haveUser && (+ <Shortcut+ action={t("delete")}+ shortcut={formattedListJoin([+ ut("Delete"),+ ut("Backspace"),+ ])}+ />+ )}+ {haveUser && (+ <Shortcut action={t("toggle_archive")} shortcut={ut("X")} />+ )}+ {!disableDownload && (+ <Shortcut action={t("copy_as_png")} shortcut={ut("^C / ⌘C")} />+ )}+ <Shortcut action={t("toggle_fullscreen")} shortcut={ut("F")} />+ <Shortcut action={t("show_shortcuts")} shortcut={ut("?")} />+ </ShortcutsContent>+ </Dialog>+);++const ShortcutsContent: React.FC<React.PropsWithChildren> = ({ children }) => (+ <DialogContent sx={{ "&&": { pt: 1, pb: 5, px: 5 } }}>+ <ShortcutsTable>+ <tbody>{children}</tbody>+ </ShortcutsTable>+ </DialogContent>+);++const ShortcutsTable = styled("table")`+ border-collapse: separate;+ border-spacing: 0 14px;+`;++interface ShortcutProps {+ action: string;+ shortcut: string;+}++const Shortcut: React.FC<ShortcutProps> = ({ action, shortcut }) => (+ <tr>+ <Typography+ component="td"+ sx={{ color: "text.muted", width: "min(20ch, 40svw)" }}+ >+ {action}+ </Typography>++ <Typography component="td" sx={{ fontWeight: "medium" }}>+ {shortcut}+ </Typography>+ </tr>+);++const fileIsEditableImage = (file: EnteFile) => {+ // Only images are editable.+ if (file.metadata.fileType !== FileType.image) return false;++ const extension = lowercaseExtension(fileFileName(file));+ // Assume it is editable;+ let isRenderable = true;+ if (extension && needsJPEGConversion(extension)) {+ // See if the file is on the whitelist of extensions that we know+ // will not be directly renderable.+ if (!isDesktop) {+ // On the web, we only support HEIC conversion.+ isRenderable = isHEICExtension(extension);+ }+ }+ return isRenderable;+};++/**+ * Return a promise that resolves with a "image/png" blob derived from the given+ * {@link imageURL} that can be written to the navigator's clipboard.+ */+const createImagePNGBlob = async (imageURL: string): Promise<Blob> =>+ new Promise((resolve, reject) => {+ const image = new Image();+ image.onload = () => {+ const canvas = document.createElement("canvas");+ canvas.width = image.width;+ canvas.height = image.height;+ canvas.getContext("2d")!.drawImage(image, 0, 0);+ canvas.toBlob(+ (blob) =>+ blob ? resolve(blob) : reject(new Error("toBlob failed")),+ "image/png",+ );+ };+ image.onerror = reject;+ image.src = imageURL;+ });diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/LikeAlbumSelectorModal.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/LikeAlbumSelectorModal.tsxnew file mode 100644index 0000000000..d76f41d9dc--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/LikeAlbumSelectorModal.tsx@@ -0,0 +1,429 @@+import CloseIcon from "@mui/icons-material/Close";+import { Box, Dialog, IconButton, styled, Typography } from "@mui/material";+import { type ModalVisibilityProps } from "ente-base/components/utils/modal";+import { t } from "i18next";+import React from "react";++// =============================================================================+// Icons+// =============================================================================++const HeartFilledIcon: React.FC<{ size?: number; color?: string }> = ({+ size = 18,+ color = "#08C225",+}) => (+ <svg+ width={size}+ height={(size * 15) / 18}+ viewBox="0 0 18 15"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ style={{ display: "block" }}+ >+ <path+ d="M7.40825 13.8538C5.15122 12.1661 0.679688 8.30753 0.679688 4.83524C0.679688 2.54019 2.3639 0.679688 4.67969 0.679688C5.87969 0.679688 7.07969 1.07969 8.67969 2.67969C10.2797 1.07969 11.4797 0.679688 12.6797 0.679688C14.9954 0.679688 16.6797 2.54019 16.6797 4.83524C16.6797 8.30753 12.2082 12.1661 9.95113 13.8538C9.19161 14.4218 8.16777 14.4218 7.40825 13.8538Z"+ fill={color}+ stroke={color}+ strokeWidth="1.36"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+);++const HeartOutlineIcon: React.FC<{ size?: number; color?: string }> = ({+ size = 18,+ color = "#08C225",+}) => (+ <svg+ width={size}+ height={(size * 15) / 18}+ viewBox="0 0 18 15"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ style={{ display: "block" }}+ >+ <path+ d="M7.40825 13.8538C5.15122 12.1661 0.679688 8.30753 0.679688 4.83524C0.679688 2.54019 2.3639 0.679688 4.67969 0.679688C5.87969 0.679688 7.07969 1.07969 8.67969 2.67969C10.2797 1.07969 11.4797 0.679688 12.6797 0.679688C14.9954 0.679688 16.6797 2.54019 16.6797 4.83524C16.6797 8.30753 12.2082 12.1661 9.95113 13.8538C9.19161 14.4218 8.16777 14.4218 7.40825 13.8538Z"+ stroke={color}+ strokeWidth="1.36"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+);++const LikePhotoIllustration: React.FC = () => (+ <svg+ width="126"+ height="121"+ viewBox="0 0 126 121"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M84.7129 23.0781C96.7222 23.0784 105.29 32.8476 105.29 44.499C105.29 53.3449 99.7258 62.2116 93.4453 69.4932C87.0622 76.8936 79.4391 83.2238 74.3574 87.0557C69.973 90.3616 64.031 90.3614 59.6465 87.0557C54.5648 83.2238 46.9408 76.8937 40.5576 69.4932C34.2771 62.2116 28.7129 53.3449 28.7129 44.499C28.713 32.8474 37.2813 23.0781 49.291 23.0781C54.9545 23.0782 60.4297 24.9062 67.001 30.9004C73.5726 24.9056 79.0491 23.0781 84.7129 23.0781Z"+ fill="#08C225"+ stroke="#232323"+ strokeWidth="5.73358"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ <mask+ id="mask0_643_19218"+ style={{ maskType: "alpha" }}+ maskUnits="userSpaceOnUse"+ x="31"+ y="25"+ width="72"+ height="62"+ >+ <path+ d="M61.3721 84.7662C51.3787 77.2306 31.5801 60.0026 31.5801 44.4993C31.5801 34.2522 39.0372 25.9453 49.2909 25.9453C54.6041 25.9453 59.9173 27.7313 67.0016 34.8751C74.086 27.7313 79.3992 25.9453 84.7124 25.9453C94.9659 25.9453 102.423 34.2522 102.423 44.4993C102.423 60.0026 82.6247 77.2306 72.6312 84.7662C69.2683 87.3019 64.735 87.3019 61.3721 84.7662Z"+ fill="#08C225"+ />+ </mask>+ <g mask="url(#mask0_643_19218)">+ <path+ d="M47.5975 41.0431C46.8515 39.3306 47.9859 37.1849 50.1312 36.2504C52.2765 35.316 54.6203 35.9467 55.3662 37.6591C56.1121 39.3716 54.9777 41.5173 52.8324 42.4518C50.6872 43.3862 48.3434 42.7555 47.5975 41.0431Z"+ fill="white"+ />+ <path+ d="M44.5677 45.0545C44.3136 44.4712 44.7025 43.7391 45.4364 43.4194C46.1704 43.0997 46.9713 43.3135 47.2254 43.8968C47.4795 44.4802 47.0906 45.2123 46.3567 45.532C45.6227 45.8517 44.8218 45.6379 44.5677 45.0545Z"+ fill="white"+ />+ <path+ d="M102.994 32.271C101.622 55.1395 78.9821 78.0073 50.9683 82.581C49.2531 88.2982 42.3926 93.7861 42.3926 95.1582C42.3926 96.5303 48.1097 107.926 50.9683 113.453L89.8447 101.447L115 66.5725C113.094 57.9969 106.196 31.3563 102.994 32.271Z"+ fill="#46A030"+ />+ <path+ d="M59.7039 28.2666C34.9591 23.1218 29.8137 47.7054 32.6723 55.1377L23.1143 51.7074C21.3992 47.3243 18.1976 37.9863 19.1123 35.6995C20.0271 33.4126 22.1615 16.833 23.1143 8.829L55.1302 3.68359L96.8651 13.9744C97.6274 18.1664 98.4659 26.8936 95.7217 28.2666C80.2855 22.5506 66.5644 33.9826 66.5644 33.4109C66.5644 32.9535 68.4701 30.5523 69.423 29.4089C66.3738 29.0281 60.1612 28.2666 59.7039 28.2666Z"+ fill="white"+ />+ </g>+ <path+ d="M20.9639 58.8477C14.9399 61.182 10.9104 66.0874 11.263 71.48C10.9104 66.0874 6.28324 61.7544 -9.80907e-05 60.2184C6.02383 57.884 10.0533 52.9787 9.70073 47.5861C10.0533 52.9787 14.6805 57.3117 20.9639 58.8477Z"+ fill="#08C225"+ />+ <path+ d="M119.579 91.9746C111.591 92.7003 105.114 97.1692 103.689 103.722C105.114 97.1692 101.077 90.4145 94.1117 86.438C102.099 85.7122 108.576 81.2434 110.001 74.6902C108.576 81.2434 112.613 87.9981 119.579 91.9746Z"+ fill="#08C225"+ />+ <path+ d="M112.728 9.21189C108.334 9.91374 104.912 12.6353 104.37 16.3181C104.912 12.6353 102.421 9.04853 98.4114 7.10627C102.806 6.40442 106.228 3.68284 106.77 7.55054e-05C106.228 3.68284 108.719 7.26962 112.728 9.21189Z"+ fill="#08C225"+ />+ </svg>+);++// =============================================================================+// Types+// =============================================================================++interface Album {+ id: number;+ name: string;+ coverURL?: string;+}++export interface LikeAlbumSelectorModalProps extends ModalVisibilityProps {+ /**+ * List of albums containing this file that user can like in.+ */+ albums: Album[];+ /**+ * Set of album IDs where the photo is currently liked.+ */+ likedAlbumIDs: Set<number>;+ /**+ * Called when user clicks on an album to toggle like status.+ * @param albumId The album ID+ * @param isCurrentlyLiked Whether the album is currently liked+ */+ onToggleAlbum: (albumId: number, isCurrentlyLiked: boolean) => void;+ /**+ * Called when user clicks "Like all" to like in all albums.+ */+ onLikeAll: () => void;+}++/**+ * Modal dialog for selecting which album to like a photo in.+ * Shown when the like button is clicked and the photo was opened from+ * gallery view (not from a specific collection).+ */+export const LikeAlbumSelectorModal: React.FC<LikeAlbumSelectorModalProps> = ({+ open,+ onClose,+ albums,+ likedAlbumIDs,+ onToggleAlbum,+ onLikeAll,+}) => {+ const likedCount = likedAlbumIDs.size;+ const allLiked = likedCount === albums.length && albums.length > 0;++ return (+ <StyledDialog open={open} onClose={onClose}>+ <DialogWrapper>+ <CloseButton onClick={onClose}>+ <CloseIcon sx={{ fontSize: 20 }} />+ </CloseButton>++ <ContentContainer>+ <IllustrationWrapper>+ <LikePhotoIllustration />+ </IllustrationWrapper>++ <TitleSection>+ <Title>{t("like_photo")}</Title>+ <Subtitle>{t("select_album_to_like")}</Subtitle>+ </TitleSection>++ <AlbumsSection>+ <AlbumsHeader>+ <AlbumsCount>+ {t("albums_count", { count: albums.length })}+ </AlbumsCount>+ <LikeAllButton+ onClick={!allLiked ? onLikeAll : undefined}+ sx={{+ opacity: !allLiked ? 1 : 0.5,+ cursor: !allLiked ? "pointer" : "default",+ pointerEvents: !allLiked ? "auto" : "none",+ }}+ >+ <Typography+ sx={(theme) => ({+ fontWeight: 500,+ fontSize: 14,+ color: "#000",+ ...theme.applyStyles("dark", {+ color: "#fff",+ }),+ })}+ >+ {t("like_all")}+ </Typography>+ {allLiked ? (+ <HeartFilledIcon+ size={16}+ color="var(--mui-palette-text-base)"+ />+ ) : (+ <HeartOutlineIcon+ size={16}+ color="var(--mui-palette-text-base)"+ />+ )}+ </LikeAllButton>+ </AlbumsHeader>++ <AlbumsList>+ {albums.map((album) => {+ const isLiked = likedAlbumIDs.has(album.id);+ return (+ <AlbumItem key={album.id}>+ <AlbumName>{album.name}</AlbumName>+ <HeartButton+ onClick={() =>+ onToggleAlbum(album.id, isLiked)+ }+ >+ {isLiked ? (+ <HeartFilledIcon />+ ) : (+ <HeartOutlineIcon />+ )}+ </HeartButton>+ </AlbumItem>+ );+ })}+ </AlbumsList>+ </AlbumsSection>+ </ContentContainer>+ </DialogWrapper>+ </StyledDialog>+ );+};++// =============================================================================+// Styled Components+// =============================================================================++const StyledDialog = styled(Dialog)(({ theme }) => ({+ "& .MuiDialog-paper": {+ width: 381,+ maxWidth: "calc(100% - 32px)",+ borderRadius: 28,+ backgroundColor: "#fff",+ padding: 0,+ margin: 16,+ overflow: "visible",+ boxShadow: "none",+ border: "1px solid #E0E0E0",+ ...theme.applyStyles("dark", {+ backgroundColor: "#1b1b1b",+ border: "1px solid rgba(255, 255, 255, 0.18)",+ }),+ },+ "& .MuiBackdrop-root": { backgroundColor: "rgba(0, 0, 0, 0.5)" },+}));++const DialogWrapper = styled(Box)(() => ({+ position: "relative",+ padding: "58px 24px 24px 24px",+}));++const CloseButton = styled(IconButton)(({ theme }) => ({+ position: "absolute",+ top: 11,+ right: 12,+ backgroundColor: "#FAFAFA",+ color: "#000",+ padding: 10,+ "&:hover": { backgroundColor: "#F0F0F0" },+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.12)",+ color: "#fff",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.16)" },+ }),+}));++const ContentContainer = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 16,+}));++const IllustrationWrapper = styled(Box)(() => ({+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ marginBottom: -12,+}));++const TitleSection = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 9,+ textAlign: "center",+ marginBottom: 14,+}));++const Title = styled(Typography)(({ theme }) => ({+ fontWeight: 600,+ fontSize: 24,+ lineHeight: "22px",+ letterSpacing: "-0.48px",+ color: "#000",+ ...theme.applyStyles("dark", { color: "#fff" }),+}));++const Subtitle = styled(Typography)(({ theme }) => ({+ fontWeight: 500,+ fontSize: 14,+ lineHeight: "17px",+ color: "#666666",+ maxWidth: 295,+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.7)" }),+}));++const AlbumsSection = styled(Box)(({ theme }) => ({+ width: "100%",+ backgroundColor: "rgba(162, 162, 162, 0.12)",+ borderRadius: 27,+ padding: "16px 0 0 0",+ maxHeight: 313,+ display: "flex",+ flexDirection: "column",+ overflow: "hidden",+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(162, 162, 162, 0.12)",+ }),+}));++const AlbumsHeader = styled(Box)(() => ({+ display: "flex",+ justifyContent: "space-between",+ alignItems: "center",+ padding: "0 16px 0 25px",+ marginBottom: 16,+}));++const AlbumsCount = styled(Typography)(({ theme }) => ({+ fontWeight: 500,+ fontSize: 14,+ lineHeight: "17px",+ color: "#000",+ ...theme.applyStyles("dark", { color: "#fff" }),+}));++const LikeAllButton = styled(Box)(({ theme }) => ({+ display: "flex",+ alignItems: "center",+ gap: 10,+ padding: 10,+ backgroundColor: "#fff",+ borderRadius: 14,+ cursor: "pointer",+ "&:hover": { backgroundColor: "#EBEBEB" },+ ...theme.applyStyles("dark", {+ backgroundColor: "#1b1b1b",+ "&:hover": { backgroundColor: "#252525" },+ }),+}));++const AlbumsList = styled(Box)(({ theme }) => ({+ display: "flex",+ flexDirection: "column",+ gap: 6,+ padding: "0 12px 12px 12px",+ overflowY: "auto",+ maxHeight: 241,+ "&::-webkit-scrollbar": { width: 6 },+ "&::-webkit-scrollbar-track": { background: "transparent" },+ "&::-webkit-scrollbar-thumb": {+ background: "rgba(0, 0, 0, 0.2)",+ borderRadius: 3,+ },+ ...theme.applyStyles("dark", {+ "&::-webkit-scrollbar-thumb": {+ background: "rgba(255, 255, 255, 0.2)",+ },+ }),+}));++const AlbumItem = styled(Box)(({ theme }) => ({+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ gap: 12,+ padding: "10px 10px 10px 16px",+ backgroundColor: "#fff",+ borderRadius: 16,+ ...theme.applyStyles("dark", { backgroundColor: "#212121" }),+}));++const AlbumName = styled(Typography)(({ theme }) => ({+ fontWeight: 500,+ fontSize: 14,+ lineHeight: "17px",+ color: "#000",+ flex: 1,+ ...theme.applyStyles("dark", { color: "#fff" }),+}));++const HeartButton = styled(Box)(() => ({+ width: 32,+ height: 32,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ backgroundColor: "rgba(8, 194, 37, 0.06)",+ borderRadius: 9.6,+ cursor: "pointer",+ "&:hover": { backgroundColor: "rgba(8, 194, 37, 0.12)" },+}));diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/LikesSidebar.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/LikesSidebar.tsxnew file mode 100644index 0000000000..05fb404a65--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/LikesSidebar.tsx@@ -0,0 +1,831 @@+import CloseIcon from "@mui/icons-material/Close";+import {+ Avatar,+ Box,+ CircularProgress,+ Drawer,+ IconButton,+ Stack,+ styled,+ Typography,+} from "@mui/material";+import { type ModalVisibilityProps } from "ente-base/components/utils/modal";+import log from "ente-base/log";+import { downloadManager } from "ente-gallery/services/download";+import { getAvatarColor } from "ente-gallery/utils/avatar-colors";+import type { EnteFile } from "ente-media/file";+import { getStoredAnonIdentity } from "ente-new/albums/services/public-reaction";+import type { CollectionSummaries } from "ente-new/photos/services/collection-summary";+import { type UnifiedReaction } from "ente-new/photos/services/social";+import { t } from "i18next";+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";++// =============================================================================+// Icons+// =============================================================================++const ChevronDownIcon: React.FC = () => (+ <svg+ width="22"+ height="22"+ viewBox="0 0 20 20"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ style={{ marginLeft: -6, transform: "translateY(-2px)" }}+ >+ <path+ d="M10.0007 12.5004L6.46484 8.96544L7.64401 7.78711L10.0007 10.1438L12.3573 7.78711L13.5365 8.96544L10.0007 12.5004Z"+ fill="currentColor"+ />+ </svg>+);++const HeartFilledIcon: React.FC = () => (+ <svg+ width="18"+ height="16"+ viewBox="0 0 30 26"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M12.4926 23.4794C8.64537 20.6025 1.02344 14.0254 1.02344 8.10676C1.02344 4.19475 3.89425 1.02344 7.84162 1.02344C9.88707 1.02344 11.9325 1.70526 14.6598 4.43253C17.3871 1.70526 19.4325 1.02344 21.478 1.02344C25.4253 1.02344 28.2962 4.19475 28.2962 8.10676C28.2962 14.0254 20.6743 20.6025 16.827 23.4794C15.5324 24.4474 13.7872 24.4474 12.4926 23.4794Z"+ fill="#08C225"+ stroke="#08C225"+ strokeWidth="2.04545"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+);++const PersonIcon: React.FC = () => (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M12 12C14.21 12 16 10.21 16 8C16 5.79 14.21 4 12 4C9.79 4 8 5.79 8 8C8 10.21 9.79 12 12 12ZM12 14C9.33 14 4 15.34 4 18V20H20V18C20 15.34 14.67 14 12 14Z"+ fill="currentColor"+ />+ </svg>+);++// =============================================================================+// Types+// =============================================================================++/** A liker with display info. */+interface Liker {+ id: string;+ userID: number;+ anonUserID?: string;+ userName: string;+ /** The actual email for avatar color, even when userName is "You". */+ email: string;+ /** The first letter of the actual name (not "You") for the avatar. */+ avatarInitial: string;+ /** True if this is a registered user with masked email (show person icon). */+ isMaskedEmail: boolean;+}++/** Collection info for the dropdown. */+interface CollectionInfo {+ id: number;+ name: string;+ likeCount: number;+ coverFile?: EnteFile;+}++// =============================================================================+// Main Component+// =============================================================================++export interface LikesSidebarProps extends ModalVisibilityProps {+ /**+ * The file whose likes are being displayed.+ */+ file?: EnteFile;+ /**+ * The currently active collection ID (when viewing from within a collection).+ */+ activeCollectionID?: number;+ /**+ * A mapping from file IDs to the IDs of collections they belong to.+ */+ fileNormalCollectionIDs?: Map<number, number[]>;+ /**+ * Collection summaries indexed by their IDs.+ */+ collectionSummaries?: CollectionSummaries;+ /**+ * The current user's ID.+ */+ currentUserID?: number;+ /**+ * Pre-fetched reactions by collection ID (includes both file and comment reactions).+ */+ prefetchedReactions?: Map<number, UnifiedReaction[]>;+ /**+ * Pre-fetched user ID to email mapping.+ */+ prefetchedUserIDToEmail?: Map<number, string>;+ /**+ * Map of anonymous user ID to decrypted user name.+ */+ anonUserNames?: Map<string, string>;+}++/**+ * A sidebar panel for displaying users who liked a file.+ */+export const LikesSidebar: React.FC<LikesSidebarProps> = ({+ open,+ onClose,+ file,+ activeCollectionID,+ fileNormalCollectionIDs,+ collectionSummaries,+ currentUserID,+ prefetchedReactions,+ prefetchedUserIDToEmail,+ anonUserNames,+}) => {+ const [loading, setLoading] = useState(false);+ const [collectionDropdownOpen, setCollectionDropdownOpen] = useState(false);++ // Reactions grouped by collection: collectionID -> reactions+ const [reactionsByCollection, setReactionsByCollection] = useState<+ Map<number, UnifiedReaction[]>+ >(new Map());++ // Selected collection for viewing likes (when in gallery view)+ const [selectedCollectionID, setSelectedCollectionID] = useState<+ number | undefined+ >(undefined);++ // Thumbnail URLs for each collection's cover file: collectionID -> URL+ const [thumbnailURLs, setThumbnailURLs] = useState<Map<number, string>>(+ new Map(),+ );++ // Check if opened from a collection context+ const hasCollectionContext =+ activeCollectionID !== undefined && activeCollectionID !== 0;++ // Get shared collections the file belongs to+ const fileCollectionIDs = useMemo(() => {+ if (!file) return [];+ const allCollectionIDs = fileNormalCollectionIDs?.get(file.id) ?? [];++ // If no collection IDs from fileNormalCollectionIDs (e.g., public album),+ // use the file's collection ID directly+ if (allCollectionIDs.length === 0) {+ return [file.collectionID];+ }++ // Filter to only include shared collections+ return allCollectionIDs.filter((id) =>+ collectionSummaries?.get(id)?.attributes.has("shared"),+ );+ }, [file, fileNormalCollectionIDs, collectionSummaries]);++ // Build collection info list with like counts and cover files+ const collectionsInfo = useMemo((): CollectionInfo[] => {+ return fileCollectionIDs.map((collectionID) => {+ const summary = collectionSummaries?.get(collectionID);+ return {+ id: collectionID,+ name: summary?.name ?? `Album ${collectionID}`,+ likeCount:+ reactionsByCollection+ .get(collectionID)+ ?.filter((r) => r.reactionType === "green_heart")+ .length ?? 0,+ coverFile: summary?.coverFile,+ };+ });+ }, [fileCollectionIDs, collectionSummaries, reactionsByCollection]);++ // Collections sorted by like count (descending) for dropdown+ const sortedCollectionsInfo = useMemo(() => {+ return [...collectionsInfo].sort((a, b) => b.likeCount - a.likeCount);+ }, [collectionsInfo]);++ // Currently selected collection info+ const selectedCollectionInfo = useMemo(() => {+ const targetID = hasCollectionContext+ ? activeCollectionID+ : selectedCollectionID;+ return (+ collectionsInfo.find((c) => c.id === targetID) ??+ sortedCollectionsInfo[0]+ );+ }, [+ hasCollectionContext,+ activeCollectionID,+ selectedCollectionID,+ collectionsInfo,+ sortedCollectionsInfo,+ ]);++ // Get likers for the selected collection+ const likers = useMemo((): Liker[] => {+ if (!selectedCollectionInfo) return [];+ const reactions =+ reactionsByCollection.get(selectedCollectionInfo.id) ?? [];++ // Get stored anonymous identity for this collection to check if current anon user+ const storedAnonIdentity = getStoredAnonIdentity(+ selectedCollectionInfo.id,+ );++ return reactions+ .filter((r) => r.reactionType === "green_heart")+ .sort((a, b) => b.createdAt - a.createdAt) // Most recent first+ .map((r) => {+ // Check if this is an anonymous user+ const isAnonymous =+ r.anonUserID || r.userID === 0 || r.userID === -1;++ // Check if this is the current user (logged-in or anonymous)+ const isCurrentUser = r.userID === currentUserID;+ const isCurrentAnonUser =+ storedAnonIdentity &&+ r.anonUserID === storedAnonIdentity.anonUserID;++ let email: string;+ let userName: string;+ let actualName: string;++ if (isAnonymous) {+ // Use decrypted name from anonUserNames if available+ const decryptedName = r.anonUserID+ ? anonUserNames?.get(r.anonUserID)+ : undefined;+ actualName =+ decryptedName ??+ `${t("anonymous")} ${r.anonUserID?.slice(-4) ?? ""}`;+ // Use actualName for avatar color (varying length like mobile emails)+ email = actualName;+ userName = isCurrentAnonUser ? t("you") : actualName;+ } else {+ const emailFromMap = prefetchedUserIDToEmail?.get(r.userID);+ // Use userID as string for unique avatar color+ email = emailFromMap ?? String(r.userID);+ // In public albums (no currentUserID), non-anonymous+ // users are album owner or collaborators+ actualName = emailFromMap ?? t("anonymous");+ userName = isCurrentUser ? t("you") : actualName;+ }++ // Check if email is masked (starts with *)+ const isMaskedEmail =+ !isAnonymous && actualName.startsWith("*");++ return {+ id: r.id,+ userID: r.userID,+ anonUserID: r.anonUserID,+ userName,+ email,+ avatarInitial: actualName[0]?.toUpperCase() ?? "?",+ isMaskedEmail,+ };+ });+ }, [+ selectedCollectionInfo,+ reactionsByCollection,+ currentUserID,+ prefetchedUserIDToEmail,+ anonUserNames,+ ]);++ // Load reactions from prefetched data+ const loadReactions = useCallback(() => {+ if (!file || !open || !prefetchedReactions) return;++ setLoading(true);++ try {+ // Use prefetched reactions (filter to only file reactions, not comment reactions)+ const filteredReactions = new Map<number, UnifiedReaction[]>();+ for (const [collectionID, reactions] of prefetchedReactions) {+ const fileReactions = reactions.filter(+ (r) => !r.commentID && r.fileID === file.id,+ );+ filteredReactions.set(collectionID, fileReactions);+ }++ setReactionsByCollection(filteredReactions);+ } catch (e) {+ log.error("Failed to load reactions", e);+ } finally {+ setLoading(false);+ }+ }, [file, open, prefetchedReactions]);++ // Track previous open state to detect when sidebar opens+ const prevOpenRef = useRef(false);++ // Load reactions and set initial selection when the sidebar opens+ useEffect(() => {+ if (open && !prevOpenRef.current) {+ // Sidebar just opened - load reactions and set initial selection+ loadReactions();++ // Set initial selection to album with most likes (gallery view only)+ if (+ !hasCollectionContext &&+ prefetchedReactions &&+ prefetchedReactions.size > 0+ ) {+ let maxCount = -1;+ let bestCollectionID: number | undefined;+ for (const [collectionID, reactions] of prefetchedReactions) {+ const count = reactions.filter(+ (r) =>+ !r.commentID &&+ r.fileID === file?.id &&+ r.reactionType === "green_heart",+ ).length;+ if (count > maxCount) {+ maxCount = count;+ bestCollectionID = collectionID;+ }+ }+ if (bestCollectionID !== undefined) {+ setSelectedCollectionID(bestCollectionID);+ }+ }+ }+ prevOpenRef.current = open;+ }, [+ open,+ loadReactions,+ hasCollectionContext,+ prefetchedReactions,+ file?.id,+ ]);++ // Update local state when prefetchedReactions changes (e.g., like/unlike from heart button)+ useEffect(() => {+ if (!open || !file || !prefetchedReactions) return;++ // Filter to only file reactions (not comment reactions)+ const filteredReactions = new Map<number, UnifiedReaction[]>();+ for (const [collectionID, reactions] of prefetchedReactions) {+ const fileReactions = reactions.filter(+ (r) => !r.commentID && r.fileID === file.id,+ );+ filteredReactions.set(collectionID, fileReactions);+ }++ setReactionsByCollection(filteredReactions);+ }, [open, file, prefetchedReactions]);++ // Fetch thumbnails for each collection's cover file+ useEffect(() => {+ // Only fetch when open, don't clear when closing (avoids flash during animation)+ if (!open || collectionsInfo.length === 0) {+ return;+ }++ let didCancel = false;++ const fetchThumbnails = async () => {+ const urls = new Map<number, string>();+ for (const collection of collectionsInfo) {+ if (collection.coverFile) {+ try {+ const url =+ await downloadManager.renderableThumbnailURL(+ collection.coverFile,+ );+ if (!didCancel && url) {+ urls.set(collection.id, url);+ }+ } catch (e) {+ log.warn(+ `Failed to fetch thumbnail for collection ${collection.id}`,+ e,+ );+ }+ }+ }+ if (!didCancel) {+ setThumbnailURLs(urls);+ }+ };++ void fetchThumbnails();++ return () => {+ didCancel = true;+ };+ }, [open, collectionsInfo]);++ const handleCollectionSelect = (collectionID: number) => {+ setSelectedCollectionID(collectionID);+ setCollectionDropdownOpen(false);+ };++ const showOverlay = collectionDropdownOpen;++ return (+ <SidebarDrawer open={open} onClose={onClose} anchor="right">+ <DrawerContentWrapper>+ {showOverlay && (+ <ContextMenuOverlay+ onClick={() => {+ setCollectionDropdownOpen(false);+ }}+ />+ )}+ <Header>+ {hasCollectionContext ? (+ <Typography+ sx={(theme) => ({+ color: "#000",+ fontWeight: 600,+ ...theme.applyStyles("dark", { color: "#fff" }),+ })}+ >+ {loading+ ? t("loading")+ : t("like_count", { count: likers.length })}+ </Typography>+ ) : collectionsInfo.length > 1 ? (+ <Box+ sx={{+ position: "relative",+ zIndex: collectionDropdownOpen ? 12 : "auto",+ }}+ >+ <CollectionDropdownButton+ onClick={() =>+ setCollectionDropdownOpen(+ !collectionDropdownOpen,+ )+ }+ >+ <Box sx={{ position: "relative" }}>+ {selectedCollectionInfo &&+ thumbnailURLs.get(+ selectedCollectionInfo.id,+ ) ? (+ <CollectionThumbnail+ src={thumbnailURLs.get(+ selectedCollectionInfo.id,+ )}+ alt=""+ />+ ) : (+ <CollectionThumbnailPlaceholder />+ )}+ <CollectionBadge>+ {selectedCollectionInfo?.likeCount ?? 0}+ </CollectionBadge>+ </Box>+ <Typography+ sx={(theme) => ({+ color: "#000",+ fontWeight: 600,+ fontSize: 14,+ lineHeight: "20px",+ marginBottom: "4px",+ ...theme.applyStyles("dark", {+ color: "#fff",+ }),+ })}+ >+ {selectedCollectionInfo?.name ?? "Album"}+ </Typography>+ <ChevronDownIcon />+ </CollectionDropdownButton>+ {collectionDropdownOpen && (+ <CollectionDropdownMenu>+ {sortedCollectionsInfo.map((collection) => (+ <CollectionDropdownItem+ key={collection.id}+ onClick={() =>+ handleCollectionSelect(+ collection.id,+ )+ }+ >+ <Box sx={{ position: "relative" }}>+ {thumbnailURLs.get(+ collection.id,+ ) ? (+ <CollectionThumbnail+ src={thumbnailURLs.get(+ collection.id,+ )}+ alt=""+ />+ ) : (+ <CollectionThumbnailPlaceholder />+ )}+ <CollectionBadge>+ {collection.likeCount}+ </CollectionBadge>+ </Box>+ <Typography+ sx={(theme) => ({+ color: "#000",+ fontWeight: 600,+ fontSize: 14,+ lineHeight: "20px",+ marginBottom: "4px",+ ...theme.applyStyles(+ "dark",+ { color: "#fff" },+ ),+ })}+ >+ {collection.name}+ </Typography>+ </CollectionDropdownItem>+ ))}+ </CollectionDropdownMenu>+ )}+ </Box>+ ) : (+ <Typography+ sx={(theme) => ({+ color: "#000",+ fontWeight: 600,+ ...theme.applyStyles("dark", { color: "#fff" }),+ })}+ >+ {loading+ ? t("loading")+ : t("like_count", { count: likers.length })}+ </Typography>+ )}+ <CloseButton onClick={onClose}>+ <CloseIcon sx={{ fontSize: 22 }} />+ </CloseButton>+ </Header>++ <LikersContainer>+ {loading ? (+ <LoadingContainer>+ <CircularProgress size={32} />+ </LoadingContainer>+ ) : likers.length === 0 ? (+ <EmptyMessage>{t("no_likes_yet")}</EmptyMessage>+ ) : (+ likers.map((liker) => (+ <LikerRow key={liker.id}>+ <Avatar+ sx={{+ width: 32,+ height: 32,+ fontSize: 14,+ bgcolor: getAvatarColor(liker.email),+ color: "#fff",+ }}+ >+ {liker.isMaskedEmail ? (+ <PersonIcon />+ ) : (+ liker.avatarInitial+ )}+ </Avatar>+ <LikerName>{liker.userName}</LikerName>+ <HeartFilledIcon />+ </LikerRow>+ ))+ )}+ </LikersContainer>+ </DrawerContentWrapper>+ </SidebarDrawer>+ );+};++// =============================================================================+// Styled Components+// =============================================================================++// Drawer & Layout+const SidebarDrawer = styled(Drawer)(({ theme }) => ({+ "& .MuiDrawer-paper": {+ width: "23vw",+ minWidth: "520px",+ maxWidth: "calc(100% - 32px)",+ height: "calc(100% - 32px)",+ margin: "16px",+ borderRadius: "36px",+ backgroundColor: "#fff",+ padding: "24px 24px 32px 24px",+ boxShadow: "none",+ border: "1px solid #E0E0E0",+ display: "flex",+ flexDirection: "column",+ overflow: "visible",+ "@media (max-width: 450px)": {+ width: "100%",+ minWidth: "unset",+ maxWidth: "100%",+ height: "100%",+ margin: 0,+ borderRadius: 0,+ },+ ...theme.applyStyles("dark", {+ backgroundColor: "#1b1b1b",+ border: "1px solid rgba(255, 255, 255, 0.18)",+ }),+ },+ "& .MuiBackdrop-root": { backgroundColor: "transparent" },+}));++const DrawerContentWrapper = styled(Box)(() => ({+ position: "relative",+ display: "flex",+ flexDirection: "column",+ flex: 1,+ minHeight: 0,+}));++const Header = styled(Stack)(() => ({+ flexDirection: "row",+ alignItems: "center",+ justifyContent: "space-between",+ marginBottom: 48,+}));++const CloseButton = styled(IconButton)(({ theme }) => ({+ backgroundColor: "#F5F5F7",+ color: "#000",+ padding: "8px",+ "&:hover": { backgroundColor: "#E5E5E7" },+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.12)",+ color: "#fff",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.16)" },+ }),+}));++// Collection Dropdown+const CollectionDropdownButton = styled(Box)(({ theme }) => ({+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ gap: 14,+ padding: "5px 6px 0px 6px",+ borderRadius: 12,+ backgroundColor: "#F0F0F0",+ cursor: "pointer",+ "&:hover": { backgroundColor: "#E8E8E8" },+ ...theme.applyStyles("dark", {+ backgroundColor: "#363636",+ "&:hover": { backgroundColor: "#404040" },+ }),+}));++const CollectionThumbnail = styled("img")(() => ({+ width: 24,+ height: 24,+ borderRadius: 5,+ objectFit: "cover",+}));++const CollectionThumbnailPlaceholder = styled(Box)(() => ({+ width: 24,+ height: 24,+ borderRadius: 5,+ backgroundColor: "#08C225",+}));++const CollectionBadge = styled(Box)(({ theme }) => ({+ position: "absolute",+ bottom: 4,+ right: -4,+ display: "inline-flex",+ justifyContent: "center",+ alignItems: "center",+ borderRadius: "50%",+ backgroundColor: "#FFF",+ color: "#000",+ fontSize: 10,+ fontWeight: 600,+ lineHeight: 1,+ minWidth: 16,+ minHeight: 16,+ ...theme.applyStyles("dark", { backgroundColor: "#fff", color: "#000" }),+}));++const CollectionDropdownMenu = styled(Box)(({ theme }) => ({+ position: "absolute",+ top: "calc(100% + 8px)",+ left: 0,+ display: "flex",+ flexDirection: "column",+ justifyContent: "center",+ alignItems: "flex-start",+ width: 184,+ padding: 4,+ gap: 4,+ borderRadius: 12,+ border: "1px solid rgba(0, 0, 0, 0.08)",+ backgroundColor: "#F0F0F0",+ zIndex: 12,+ ...theme.applyStyles("dark", {+ border: "1px solid rgba(0, 0, 0, 0.08)",+ backgroundColor: "#363636",+ }),+}));++const CollectionDropdownItem = styled(Box)(({ theme }) => ({+ display: "flex",+ alignItems: "center",+ gap: 14,+ padding: "5px 6px 0px 6px",+ borderRadius: 8,+ cursor: "pointer",+ width: "100%",+ "&:hover": { backgroundColor: "#E8E8E8" },+ ...theme.applyStyles("dark", {+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.16)" },+ }),+}));++const LikersContainer = styled(Box)(({ theme }) => ({+ flex: 1,+ overflow: "auto",+ marginRight: -24,+ paddingRight: 24,+ "&::-webkit-scrollbar": { width: "6px" },+ "&::-webkit-scrollbar-track": { background: "transparent" },+ "&::-webkit-scrollbar-thumb": {+ background: "rgba(0, 0, 0, 0.2)",+ borderRadius: "3px",+ },+ scrollbarWidth: "thin",+ scrollbarColor: "rgba(0, 0, 0, 0.2) transparent",+ ...theme.applyStyles("dark", {+ "&::-webkit-scrollbar-thumb": {+ background: "rgba(255, 255, 255, 0.2)",+ },+ scrollbarColor: "rgba(255, 255, 255, 0.2) transparent",+ }),+}));++const LikerRow = styled(Box)(() => ({+ display: "flex",+ alignItems: "center",+ gap: 12,+ padding: "10px 10px 10px 0",+}));++const LikerName = styled(Typography)(({ theme }) => ({+ flex: 1,+ fontWeight: 500,+ color: "#000",+ fontSize: 14,+ ...theme.applyStyles("dark", { color: "#fff" }),+}));++const LoadingContainer = styled(Box)(() => ({+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ height: "100%",+ // Offset for header (marginBottom: 48) + padding diff (32-24=8) = 56, halved+ marginTop: -28,+}));++const EmptyMessage = styled(Typography)(({ theme }) => ({+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ height: "100%",+ // Offset for header (marginBottom: 48) + padding diff (32-24=8) = 56, halved+ marginTop: -28,+ color: "#666",+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.5)" }),+}));++// Context Menu Overlay+const ContextMenuOverlay = styled(Box)(() => ({+ position: "absolute",+ top: -25,+ left: -25,+ right: -25,+ bottom: -33,+ backgroundColor: "rgba(0, 0, 0, 0.6)",+ zIndex: 10,+ borderRadius: "36px",+ "@media (max-width: 450px)": { borderRadius: 0 },+}));diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/PublicCommentModal.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/PublicCommentModal.tsxnew file mode 100644index 0000000000..b3590af12b--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/PublicCommentModal.tsx@@ -0,0 +1,304 @@+import CloseIcon from "@mui/icons-material/Close";+import {+ Box,+ Button,+ Dialog,+ IconButton,+ styled,+ Typography,+} from "@mui/material";+import { type ModalVisibilityProps } from "ente-base/components/utils/modal";+import { t } from "i18next";+import React from "react";++// =============================================================================+// Icons+// =============================================================================++const CommentIllustration: React.FC = () => (+ <svg+ width="146"+ height="104"+ viewBox="0 0 146 104"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M62.4161 23.9825C69.5416 21.6377 77.2027 21.4587 84.4301 23.4677C91.6577 25.4768 98.1278 29.5846 103.021 35.2705C107.914 40.9564 111.011 47.9656 111.921 55.4117C112.83 62.8579 111.511 70.4066 108.131 77.1033C104.75 83.8 99.4603 89.3444 92.929 93.0344C86.3977 96.7244 78.9186 98.3952 71.438 97.8347C65.5124 97.3907 59.9955 95.6061 55.1766 92.7912L36.6137 95.1736C35.7803 95.2805 34.9485 94.962 34.4004 94.3252C33.8523 93.6882 33.6604 92.8183 33.8903 92.0101L39.0115 74.0065C36.9468 68.823 36.0051 63.1057 36.4493 57.1772C37.0098 49.6966 39.7764 42.5499 44.3984 36.6414C49.0204 30.733 55.2905 26.3274 62.4161 23.9825Z"+ fill="#08C225"+ stroke="#232323"+ strokeWidth="5"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ <mask+ id="mask0_737_21326"+ style={{ maskType: "alpha" }}+ maskUnits="userSpaceOnUse"+ x="36"+ y="24"+ width="74"+ height="72"+ >+ <path+ d="M71.6249 95.341C78.6125 95.8645 85.5985 94.3043 91.6993 90.8575C97.8002 87.4107 102.742 82.2321 105.899 75.9768C109.057 69.7214 110.289 62.6702 109.439 55.7147C108.59 48.7592 105.696 42.2119 101.126 36.9007C96.5551 31.5895 90.512 27.753 83.7608 25.8763C77.0096 23.9996 69.8535 24.167 63.1974 26.3573C56.5414 28.5477 50.6843 32.6626 46.3669 38.1817C42.0494 43.7008 39.4656 50.3762 38.942 57.3639C38.5044 63.2051 39.5049 68.8185 41.6537 73.8587L36.2949 92.6938L55.7183 90.2015C60.382 93.0774 65.7876 94.9037 71.6249 95.341Z"+ fill="#08C225"+ />+ </mask>+ <g mask="url(#mask0_737_21326)">+ <path+ d="M90.785 29.2779C55.9844 19.5648 41.0889 44.5028 37.9912 58.186L34.2834 72.1186C32.1784 72.553 27.1513 72.4724 23.883 68.6747C19.7976 63.9275 7.9607 55.936 8.75491 45.336C9.54911 34.736 9.85699 18.7723 10.8726 17.072C11.6851 15.7117 48.8217 4.51972 67.2885 -0.90625L123.817 3.32912C127.307 16.0258 125.586 38.991 90.785 29.2779Z"+ fill="white"+ />+ <path+ d="M68.1126 36.8926C67.7871 34.8769 69.5702 32.9123 72.0953 32.5044C74.6204 32.0966 76.9313 33.4 77.2568 35.4157C77.5824 37.4313 75.7993 39.3959 73.2742 39.8038C70.7491 40.2116 68.4382 38.9082 68.1126 36.8926Z"+ fill="white"+ />+ <path+ d="M63.6068 40.3106C63.4959 39.624 64.1063 38.9542 64.9702 38.8147C65.834 38.6752 66.6242 39.1187 66.7351 39.8054C66.846 40.492 66.2356 41.1618 65.3718 41.3013C64.5079 41.4408 63.7177 40.9973 63.6068 40.3106Z"+ fill="white"+ />+ <path+ d="M35.0516 84.4974C50.0736 86.3458 84.2825 85.3953 100.941 66.8061C117.601 48.217 131.472 23.1618 129.517 33.958C128.008 42.824 108.57 103.778 97.3574 108.665C83.3409 114.774 55.5151 127.853 46.4893 128.205C37.4635 128.557 25.3268 115.992 24.0509 114.477C22.775 112.962 24.2879 103.196 26.2494 99.9921C27.959 97.1997 26.5317 91.4899 26.2742 90.6394C26.2622 90.6323 26.2542 90.6209 26.2503 90.6048C26.2237 90.4942 26.2362 90.514 26.2742 90.6394C26.7756 90.9343 34.2208 83.5106 35.0516 84.4974Z"+ fill="#24B41F"+ />+ <path+ d="M63.1172 64.2407C65.5626 64.2849 67.581 62.3384 67.6253 59.8929C67.6695 57.4475 65.723 55.4291 63.2775 55.3849C60.8321 55.3406 58.8137 57.2871 58.7694 59.7326C58.7252 62.1781 60.6717 64.1964 63.1172 64.2407Z"+ fill="#232323"+ />+ <path+ d="M75.293 64.4555C77.7384 64.4998 79.7568 62.5532 79.801 60.1078C79.8453 57.6623 77.8988 55.644 75.4533 55.5997C73.0078 55.5554 70.9895 57.502 70.9452 59.9474C70.901 62.3929 72.8475 64.4112 75.293 64.4555Z"+ fill="#232323"+ />+ <path+ d="M87.4707 64.6821C89.9162 64.7263 91.9345 62.7798 91.9788 60.3343C92.023 57.8889 90.0765 55.8705 87.631 55.8263C85.1856 55.782 83.1672 57.7285 83.123 60.174C83.0787 62.6195 85.0252 64.6378 87.4707 64.6821Z"+ fill="#232323"+ />+ </g>+ <path+ d="M20.1099 75.4512C14.3314 77.6905 10.4661 82.396 10.8043 87.5689C10.4661 82.396 6.02735 78.2395 0 76.7661C5.77852 74.5268 9.64385 69.8213 9.30562 64.6484C9.64385 69.8213 14.0826 73.9778 20.1099 75.4512Z"+ fill="#08C225"+ />+ <path+ d="M145.699 62.5334C138.037 63.2295 131.824 67.5164 130.457 73.8026C131.824 67.5164 127.951 61.0368 121.27 57.2223C128.932 56.5261 135.145 52.2393 136.512 45.9531C135.145 52.2393 139.017 58.7188 145.699 62.5334Z"+ fill="#08C225"+ />+ <path+ d="M51.1361 8.83653C46.9208 9.50979 43.6377 12.1205 43.1181 15.6532C43.6377 12.1205 41.2488 8.67983 37.4023 6.81669C41.6176 6.14343 44.9007 3.53273 45.4202 0C44.9007 3.53273 47.2896 6.97339 51.1361 8.83653Z"+ fill="#08C225"+ />+ </svg>+);++// =============================================================================+// Types+// =============================================================================++export interface PublicCommentModalProps extends ModalVisibilityProps {+ /**+ * Called when user clicks "Comment anonymously".+ */+ onCommentAnonymously: () => void;+ /**+ * Called when user clicks "Join album and comment".+ */+ onJoinAlbumToComment: () => void;+ /**+ * Whether the "Join album" option is enabled for this public link.+ * When false, the "Join album and comment" button will be hidden.+ */+ enableJoin?: boolean;+}++/**+ * Modal dialog for commenting on a photo in a public album.+ * Shows options to comment anonymously or sign in to comment.+ */+export const PublicCommentModal: React.FC<PublicCommentModalProps> = ({+ open,+ onClose,+ onCommentAnonymously,+ onJoinAlbumToComment,+ enableJoin = true,+}) => {+ return (+ <StyledDialog open={open} onClose={onClose}>+ <DialogWrapper>+ <CloseButton onClick={onClose}>+ <CloseIcon sx={{ fontSize: 20 }} />+ </CloseButton>++ <ContentContainer>+ <IllustrationWrapper>+ <CommentIllustration />+ </IllustrationWrapper>++ <TitleSection>+ <Title>{t("say_something_nice")}</Title>+ {enableJoin && (+ <Subtitle>{t("public_comment_subtitle")}</Subtitle>+ )}+ </TitleSection>++ <ButtonsSection sx={!enableJoin ? { mt: 4 } : undefined}>+ {enableJoin ? (+ <AnonymousButton+ variant="outlined"+ fullWidth+ onClick={onCommentAnonymously}+ >+ {t("comment_anonymously")}+ </AnonymousButton>+ ) : (+ <SignInButton+ variant="contained"+ fullWidth+ onClick={onCommentAnonymously}+ >+ {t("comment_anonymously")}+ </SignInButton>+ )}+ {enableJoin && (+ <SignInButton+ variant="contained"+ fullWidth+ onClick={onJoinAlbumToComment}+ >+ {t("join_album_and_comment")}+ </SignInButton>+ )}+ </ButtonsSection>+ </ContentContainer>+ </DialogWrapper>+ </StyledDialog>+ );+};++// =============================================================================+// Styled Components+// =============================================================================++const StyledDialog = styled(Dialog)(({ theme }) => ({+ "& .MuiDialog-paper": {+ width: 381,+ maxWidth: "calc(100% - 32px)",+ borderRadius: 28,+ backgroundColor: "#fff",+ padding: 0,+ margin: 16,+ overflow: "visible",+ boxShadow: "none",+ border: "1px solid #E0E0E0",+ ...theme.applyStyles("dark", {+ backgroundColor: "#1b1b1b",+ border: "1px solid rgba(255, 255, 255, 0.18)",+ }),+ },+ "& .MuiBackdrop-root": { backgroundColor: "rgba(0, 0, 0, 0.5)" },+}));++const DialogWrapper = styled(Box)(() => ({+ position: "relative",+ padding: "48px 16px 16px 16px",+}));++const CloseButton = styled(IconButton)(({ theme }) => ({+ position: "absolute",+ top: 11,+ right: 12,+ backgroundColor: "#FAFAFA",+ color: "#000",+ padding: 10,+ "&:hover": { backgroundColor: "#F0F0F0" },+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.12)",+ color: "#fff",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.16)" },+ }),+}));++const ContentContainer = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 16,+}));++const IllustrationWrapper = styled(Box)(() => ({+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ marginBottom: 8,+}));++const TitleSection = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 9,+ textAlign: "center",+ marginBottom: 16,+}));++const Title = styled(Typography)(({ theme }) => ({+ fontWeight: 600,+ fontSize: 24,+ lineHeight: "28px",+ letterSpacing: "-0.48px",+ color: "#000",+ ...theme.applyStyles("dark", { color: "#fff" }),+}));++const Subtitle = styled(Typography)(({ theme }) => ({+ fontWeight: 500,+ fontSize: 14,+ lineHeight: "20px",+ color: "#666666",+ maxWidth: 240,+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.7)" }),+}));++const ButtonsSection = styled(Box)(() => ({+ width: "100%",+ display: "flex",+ flexDirection: "column",+ gap: 12,+}));++const AnonymousButton = styled(Button)(({ theme }) => ({+ display: "flex",+ padding: "20px 16px",+ justifyContent: "center",+ alignItems: "center",+ gap: 8,+ flex: "1 0 0",+ borderRadius: 20,+ backgroundColor: "rgba(0, 0, 0, 0.04)",+ border: "none",+ fontSize: 16,+ fontWeight: 500,+ textTransform: "none",+ color: "#000",+ "&:hover": { backgroundColor: "rgba(0, 0, 0, 0.08)", border: "none" },+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.08)",+ color: "#fff",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.12)" },+ }),+}));++const SignInButton = styled(Button)(() => ({+ display: "flex",+ padding: "20px 16px",+ justifyContent: "center",+ alignItems: "center",+ gap: 8,+ flex: "1 0 0",+ borderRadius: 20,+ backgroundColor: "#08C225",+ fontSize: 16,+ fontWeight: 500,+ textTransform: "none",+ color: "#fff",+ "&:hover": { backgroundColor: "#07A820" },+}));diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/PublicFeedSidebar.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/PublicFeedSidebar.tsxnew file mode 100644index 0000000000..08eea1b292--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/PublicFeedSidebar.tsx@@ -0,0 +1,1029 @@+import CloseIcon from "@mui/icons-material/Close";+import {+ Avatar,+ Box,+ CircularProgress,+ Drawer,+ IconButton,+ Stack,+ styled,+ Typography,+} from "@mui/material";+import { useColorScheme } from "@mui/material/styles";+import { useInterval } from "ente-base/components/utils/hooks";+import { type ModalVisibilityProps } from "ente-base/components/utils/modal";+import type { PublicAlbumsCredentials } from "ente-base/http";+import log from "ente-base/log";+import { downloadManager } from "ente-gallery/services/download";+import { getAvatarColor } from "ente-gallery/utils/avatar-colors";+import type { EnteFile } from "ente-media/file";+import { FileType } from "ente-media/file-type";+import {+ getPublicAlbumFeed,+ getPublicAnonProfiles,+ getPublicParticipantsMaskedEmails,+ type PublicFeedComment,+ type PublicFeedReaction,+} from "ente-new/albums/services/public-reaction";+import { t } from "i18next";+import React, { useCallback, useEffect, useMemo, useState } from "react";++// =============================================================================+// Icons+// =============================================================================++const LikedPhotoIcon: React.FC = () => (+ <svg+ width="17"+ height="15"+ viewBox="0 0 17 15"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M6.99906 13.1537C4.84391 11.5421 0.574219 7.85775 0.574219 4.54219C0.574219 2.35074 2.1824 0.574219 4.39366 0.574219C5.5395 0.574219 6.68533 0.956163 8.21311 2.48394C9.74089 0.956163 10.8867 0.574219 12.0326 0.574219C14.2438 0.574219 15.852 2.35074 15.852 4.54219C15.852 7.85775 11.5823 11.5421 9.42716 13.1537C8.70192 13.696 7.7243 13.696 6.99906 13.1537Z"+ fill="#08C225"+ stroke="#08C225"+ strokeWidth="1.14583"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+);++const CommentedPhotoIcon: React.FC = () => (+ <svg+ width="15"+ height="15"+ viewBox="0 0 15 15"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M7.5 14.25C8.83502 14.25 10.1401 13.8541 11.2501 13.1124C12.3601 12.3707 13.2253 11.3165 13.7362 10.0831C14.2471 8.84971 14.3808 7.49252 14.1203 6.18314C13.8598 4.87377 13.217 3.67104 12.273 2.72703C11.329 1.78303 10.1262 1.14015 8.81686 0.879702C7.50749 0.619252 6.15029 0.752925 4.91689 1.26382C3.68349 1.77471 2.62928 2.63987 1.88758 3.7499C1.14588 4.85994 0.75 6.16498 0.75 7.5C0.75 8.616 1.02 9.66825 1.5 10.5953L0.75 14.25L4.40475 13.5C5.33175 13.98 6.38475 14.25 7.5 14.25Z"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+);++const RepliedCommentIcon: React.FC = () => (+ <svg+ width="12"+ height="9"+ viewBox="0 0 12 9"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M4.2334 0.0849609C4.39661 0.0849817 4.55308 0.151147 4.66797 0.268555C4.78252 0.386006 4.84664 0.544829 4.84668 0.709961C4.84668 0.875074 4.78246 1.03389 4.66797 1.15137L2.1748 3.70215H7.76855C8.41316 3.70215 9.34837 3.88326 10.1738 4.42969L10.3379 4.54297L10.5029 4.67188C11.3155 5.34145 11.918 6.39843 11.918 7.94531C11.9179 8.11049 11.8539 8.26927 11.7393 8.38672C11.6244 8.50422 11.4679 8.57119 11.3047 8.57129C11.1413 8.57129 10.985 8.5043 10.8701 8.38672C10.7553 8.26923 10.6905 8.11066 10.6904 7.94531C10.6904 6.70123 10.1974 5.98489 9.61914 5.55859C9.00926 5.10915 8.25891 4.95312 7.76855 4.95312H2.17578L4.66504 7.50098C4.72518 7.55831 4.77424 7.62756 4.80762 7.7041C4.84094 7.78063 4.85886 7.86362 4.86035 7.94727C4.8618 8.03105 4.84614 8.11459 4.81543 8.19238C4.78472 8.27017 4.73883 8.34087 4.68066 8.40039C4.62251 8.45986 4.55306 8.50745 4.47656 8.53906C4.40013 8.57058 4.31786 8.58645 4.23535 8.58496C4.1528 8.58343 4.07139 8.5646 3.99609 8.53027C3.9207 8.4959 3.85295 8.44634 3.79688 8.38477V8.38379L0.263672 4.76953C0.148973 4.65203 0.0849609 4.49242 0.0849609 4.32715C0.085085 4.16205 0.149084 4.00313 0.263672 3.88574L3.79883 0.268555C3.91373 0.151128 4.07015 0.0849609 4.2334 0.0849609Z"+ fill="currentColor"+ stroke="currentColor"+ strokeWidth="0.166667"+ />+ </svg>+);++const LikedCommentIcon: React.FC<{ heartStroke?: string }> = ({+ heartStroke = "white",+}) => (+ <svg+ width="22"+ height="21"+ viewBox="0 0 22 21"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M9.16797 16.043C10.5277 16.043 11.8569 15.6398 12.9875 14.8843C14.1181 14.1289 14.9993 13.0552 15.5196 11.7989C16.04 10.5427 16.1761 9.16035 15.9109 7.82673C15.6456 6.49311 14.9908 5.2681 14.0293 4.30661C13.0678 3.34513 11.8428 2.69035 10.5092 2.42507C9.17559 2.1598 7.79326 2.29595 6.53702 2.8163C5.28078 3.33665 4.20705 4.21784 3.45162 5.34843C2.69618 6.47901 2.29297 7.80823 2.29297 9.16797C2.29297 10.3046 2.56797 11.3764 3.05686 12.3205L2.29297 16.043L6.0154 15.2791C6.95957 15.768 8.03207 16.043 9.16797 16.043Z"+ stroke="currentColor"+ strokeWidth="1.52778"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ <path+ d="M17.3555 10.0986C18.9264 10.0987 20.0537 11.3666 20.0537 12.8887C20.0536 14.0427 19.3203 15.2043 18.4863 16.1631C17.6399 17.1362 16.6287 17.9692 15.9541 18.4736C15.3852 18.899 14.6148 18.899 14.0459 18.4736C13.3713 17.9692 12.3601 17.1362 11.5137 16.1631C10.6797 15.2043 9.94638 14.0427 9.94629 12.8887C9.94629 11.3666 11.0736 10.0986 12.6445 10.0986C13.3933 10.0986 14.1193 10.34 15 11.1455C15.8807 10.34 16.6067 10.0986 17.3555 10.0986Z"+ stroke={heartStroke}+ strokeWidth="0.685221"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ <path+ d="M14.2513 18.1992C12.9222 17.2053 10.2891 14.9332 10.2891 12.8885C10.2891 11.537 11.2808 10.4414 12.6445 10.4414C13.3511 10.4414 14.0578 10.677 15 11.6191C15.9421 10.677 16.6488 10.4414 17.3554 10.4414C18.7191 10.4414 19.7109 11.537 19.7109 12.8885C19.7109 14.9332 17.0777 17.2053 15.7487 18.1992C15.3014 18.5336 14.6985 18.5336 14.2513 18.1992Z"+ fill="#08C225"+ stroke="#08C225"+ strokeWidth="0.685221"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+);++const PersonIcon: React.FC = () => (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M12 12C14.21 12 16 10.21 16 8C16 5.79 14.21 4 12 4C9.79 4 8 5.79 8 8C8 10.21 9.79 12 12 12ZM12 14C9.33 14 4 15.34 4 18V20H20V18C20 15.34 14.67 14 12 14Z"+ fill="currentColor"+ />+ </svg>+);++// =============================================================================+// Types+// =============================================================================++/**+ * Information about a feed item click for navigation purposes.+ */+export interface PublicFeedItemClickInfo {+ /** The type of feed item. */+ type: PublicFeedItem["type"];+ /** The file ID to navigate to. */+ fileID: number;+ /**+ * The comment ID to highlight (for comment-related items).+ * For `replied_comment`, this is the reply's comment ID.+ * For `liked_comment`, this is the target comment ID.+ */+ commentID?: string;+}++export interface PublicFeedSidebarProps extends ModalVisibilityProps {+ /**+ * The files in the album, used to display thumbnails and determine file type.+ */+ files?: EnteFile[];+ /**+ * Public album credentials for API access.+ */+ credentials: PublicAlbumsCredentials;+ /**+ * The decrypted collection key (base64 encoded).+ */+ collectionKey: string;+ /**+ * Called when a feed item is clicked for navigation.+ */+ onItemClick?: (info: PublicFeedItemClickInfo) => void;+}++/** A user who performed an action in the feed. */+interface FeedUser {+ userID: number;+ anonUserID?: string;+ userName: string;+ /** Email/identifier used for avatar color. */+ email: string;+ /** True if this is a registered user with masked email (show person icon). */+ isMaskedEmail: boolean;+}++/** Base interface for all feed items. */+interface BaseFeedItem {+ /** Unique identifier for this feed item (for React keys). */+ id: string;+ /** Timestamp of the most recent action in this item. */+ timestamp: number;+}++/** Someone liked a photo/video (grouped by file). */+interface LikedFileFeedItem extends BaseFeedItem {+ type: "liked_photo" | "liked_video";+ fileID: number;+ thumbnailURL?: string;+ users: FeedUser[];+}++/** Someone commented on a photo/video. */+interface CommentedFileFeedItem extends BaseFeedItem {+ type: "commented_photo" | "commented_video";+ fileID: number;+ /** The ID of the comment for navigation. */+ commentID: string;+ thumbnailURL?: string;+ user: FeedUser;+}++/** Someone replied to a comment. */+interface RepliedCommentFeedItem extends BaseFeedItem {+ type: "replied_comment";+ /** The parent comment ID. */+ parentCommentID: string;+ /** The ID of the reply for navigation. */+ replyID: string;+ fileID?: number;+ thumbnailURL?: string;+ user: FeedUser;+}++/** Someone liked a comment (grouped by comment, includes reply likes). */+interface LikedCommentFeedItem extends BaseFeedItem {+ type: "liked_comment";+ commentID: string;+ fileID?: number;+ thumbnailURL?: string;+ users: FeedUser[];+}++type PublicFeedItem =+ | LikedFileFeedItem+ | CommentedFileFeedItem+ | RepliedCommentFeedItem+ | LikedCommentFeedItem;++/** Thumbnail URL cache for files. */+type ThumbnailCache = Map<number, string>;++/** File type cache for determining photo vs video. */+type FileTypeCache = Map<number, number>;++// =============================================================================+// Utility Functions+// =============================================================================++/**+ * Get the display name for a user.+ * For anonymous users, uses their entered name from userName.+ * Falls back to "Anonymous" only if userName is empty.+ */+const getUserDisplayName = (+ userID: number,+ userName: string,+ anonUserID?: string,+): string => {+ if (userID === -1 || userID === 0 || anonUserID) {+ return userName || t("anonymous");+ }+ return userName;+};++/**+ * Process feed items from public album data.+ *+ * For public albums, we show ALL actions from everyone:+ * - X liked a photo/video+ * - A liked a comment (includes reply likes)+ * - M commented on a photo/video+ * - C replied to a comment+ */+const processFeedItems = (+ comments: PublicFeedComment[],+ reactions: PublicFeedReaction[],+ thumbnailCache: ThumbnailCache,+ fileTypeCache: FileTypeCache,+ maskedEmails: Map<number, string>,+ anonUserNames: Map<string, string>,+): PublicFeedItem[] => {+ const feedItems: PublicFeedItem[] = [];++ // Build a map from commentID to fileID for looking up comment likes+ const commentFileIDMap = new Map<string, number>();+ for (const c of comments) {+ if (c.fileID) {+ commentFileIDMap.set(c.id, c.fileID);+ }+ }++ // Helper to get display name for a user+ const getUserName = (userID: number, anonUserID?: string): string => {+ if (anonUserID) {+ return (+ anonUserNames.get(anonUserID) ??+ `${t("anonymous")} ${anonUserID.slice(-4)}`+ );+ }+ return maskedEmails.get(userID) ?? t("unknown_user");+ };++ // Helper to get avatar color key+ const getAvatarColorKey = (userID: number, anonUserID?: string): string => {+ if (anonUserID) {+ return anonUserNames.get(anonUserID) ?? anonUserID;+ }+ return maskedEmails.get(userID) ?? String(userID);+ };++ // On public albums, all registered users have masked emails+ const isRegisteredUser = (anonUserID?: string): boolean => !anonUserID;++ // Helper to get thumbnail URL from cache+ const getThumbnailURL = (fileID: number | undefined): string | undefined =>+ fileID ? thumbnailCache.get(fileID) : undefined;++ // Helper to determine if file is video+ const isVideo = (fileID: number | undefined): boolean => {+ if (!fileID) return false;+ const fileType = fileTypeCache.get(fileID);+ return fileType === FileType.video;+ };++ // 1. Process comments - categorize as "commented_photo/video" or "replied_comment"+ for (const c of comments) {+ if (c.isDeleted) continue;++ const displayName = getUserName(c.userID, c.anonUserID);+ const avatarColorKey = getAvatarColorKey(c.userID, c.anonUserID);+ const isMaskedEmail = isRegisteredUser(c.anonUserID);++ if (c.isReply && c.parentCommentID) {+ // This is a reply to a comment+ feedItems.push({+ id: `replied_comment_${c.id}`,+ type: "replied_comment",+ parentCommentID: c.parentCommentID,+ replyID: c.id,+ fileID: c.fileID,+ thumbnailURL: getThumbnailURL(c.fileID),+ timestamp: c.createdAt,+ user: {+ userID: c.userID,+ anonUserID: c.anonUserID,+ userName: displayName,+ email: avatarColorKey,+ isMaskedEmail,+ },+ });+ } else if (c.fileID) {+ // This is a comment on a photo/video+ const fileIsVideo = isVideo(c.fileID);+ feedItems.push({+ id: `commented_file_${c.id}`,+ type: fileIsVideo ? "commented_video" : "commented_photo",+ fileID: c.fileID,+ commentID: c.id,+ thumbnailURL: getThumbnailURL(c.fileID),+ timestamp: c.createdAt,+ user: {+ userID: c.userID,+ anonUserID: c.anonUserID,+ userName: displayName,+ email: avatarColorKey,+ isMaskedEmail,+ },+ });+ }+ }++ // 2. Process reactions - group by file or comment+ // Group file likes by fileID+ const fileLikes = new Map<+ number,+ { users: FeedUser[]; latestTimestamp: number; isVideo: boolean }+ >();+ // Group comment likes by commentID (includes reply likes)+ const commentLikes = new Map<+ string,+ { users: FeedUser[]; latestTimestamp: number; fileID?: number }+ >();++ for (const r of reactions) {+ if (r.isDeleted) continue;++ const userName = getUserName(r.userID, r.anonUserID);+ const email = getAvatarColorKey(r.userID, r.anonUserID);+ const isMaskedEmail = isRegisteredUser(r.anonUserID);+ const user: FeedUser = {+ userID: r.userID,+ anonUserID: r.anonUserID,+ userName,+ email,+ isMaskedEmail,+ };++ if (r.fileID && !r.commentID) {+ // Reaction on a file (photo/video)+ const fileID = r.fileID;+ const existing = fileLikes.get(fileID);+ if (existing) {+ existing.users.push(user);+ if (r.createdAt > existing.latestTimestamp) {+ existing.latestTimestamp = r.createdAt;+ // Move most recent user to front+ existing.users.pop();+ existing.users.unshift(user);+ }+ } else {+ fileLikes.set(fileID, {+ users: [user],+ latestTimestamp: r.createdAt,+ isVideo: isVideo(fileID),+ });+ }+ } else if (r.commentID) {+ // Reaction on a comment (treat reply likes as comment likes)+ const commentID = r.commentID;+ // Look up fileID from comment if not present in reaction+ const fileID = r.fileID || commentFileIDMap.get(commentID);+ const existing = commentLikes.get(commentID);+ if (existing) {+ existing.users.push(user);+ if (r.createdAt > existing.latestTimestamp) {+ existing.latestTimestamp = r.createdAt;+ existing.users.pop();+ existing.users.unshift(user);+ }+ } else {+ commentLikes.set(commentID, {+ users: [user],+ latestTimestamp: r.createdAt,+ fileID,+ });+ }+ }+ }++ // Add grouped file likes to feed+ for (const [fileID, data] of fileLikes) {+ feedItems.push({+ id: `liked_file_${fileID}`,+ type: data.isVideo ? "liked_video" : "liked_photo",+ fileID,+ thumbnailURL: getThumbnailURL(fileID),+ timestamp: data.latestTimestamp,+ users: data.users,+ });+ }++ // Add grouped comment likes to feed (includes reply likes)+ for (const [commentID, data] of commentLikes) {+ feedItems.push({+ id: `liked_comment_${commentID}`,+ type: "liked_comment",+ commentID,+ fileID: data.fileID,+ thumbnailURL: getThumbnailURL(data.fileID),+ timestamp: data.latestTimestamp,+ users: data.users,+ });+ }++ // Sort by timestamp (newest first)+ return feedItems.sort((a, b) => b.timestamp - a.timestamp);+};++/**+ * Get the action text for a feed item.+ */+const getActionText = (item: PublicFeedItem): string => {+ switch (item.type) {+ case "liked_photo":+ return t("liked_a_photo");+ case "liked_video":+ return t("liked_a_video");+ case "commented_photo":+ return t("commented_on_a_photo");+ case "commented_video":+ return t("commented_on_a_video");+ case "replied_comment":+ return t("replied_to_a_comment");+ case "liked_comment":+ return t("liked_a_comment");+ }+};++/**+ * Get the users string for display (e.g., "John and 2 others").+ */+const getUsersDisplayText = (users: FeedUser[]): string => {+ if (users.length === 0) return "";+ const firstName = getUserDisplayName(+ users[0]!.userID,+ users[0]!.userName,+ users[0]!.anonUserID,+ );+ if (users.length === 1) {+ return firstName;+ }+ const othersCount = users.length - 1;+ return `${firstName} and ${othersCount} ${othersCount === 1 ? "other" : "others"}`;+};++/**+ * Get the icon component for a feed item type.+ */+const getFeedIcon = (+ type: PublicFeedItem["type"],+ heartStroke: string,+): React.ReactNode => {+ switch (type) {+ case "liked_photo":+ case "liked_video":+ return <LikedPhotoIcon />;+ case "commented_photo":+ case "commented_video":+ return <CommentedPhotoIcon />;+ case "replied_comment":+ return <RepliedCommentIcon />;+ case "liked_comment":+ return <LikedCommentIcon heartStroke={heartStroke} />;+ }+};++// =============================================================================+// Feed Item Row Component+// =============================================================================++interface FeedItemRowProps {+ item: PublicFeedItem;+ onClick?: () => void;+}++/**+ * Get the users array from a feed item.+ */+const getFeedItemUsers = (item: PublicFeedItem): FeedUser[] => {+ switch (item.type) {+ case "commented_photo":+ case "commented_video":+ case "replied_comment":+ return [item.user];+ case "liked_photo":+ case "liked_video":+ case "liked_comment":+ return item.users;+ }+};++/**+ * A single row in the feed showing an action.+ */+const FeedItemRow: React.FC<FeedItemRowProps> = ({ item, onClick }) => {+ const { mode, systemMode } = useColorScheme();+ const users = getFeedItemUsers(item);++ const displayText = getUsersDisplayText(users);+ const actionText = getActionText(item);+ const resolvedMode = mode === "system" ? systemMode : mode;+ const heartStroke = resolvedMode === "dark" ? "#1b1b1b" : "white";++ return (+ <FeedItemContainer onClick={onClick}>+ <IconContainer>{getFeedIcon(item.type, heartStroke)}</IconContainer>+ <FeedItemContent>+ <AvatarStack>+ {users.slice(0, 3).map((user, index) => {+ const displayName = getUserDisplayName(+ user.userID,+ user.userName,+ user.anonUserID,+ );+ return (+ <StyledAvatar+ key={`${user.userID}-${user.anonUserID ?? index}`}+ sx={{+ zIndex: users.length - index,+ bgcolor: getAvatarColor(user.email),+ color: "#fff",+ }}+ >+ {user.isMaskedEmail ? (+ <PersonIcon />+ ) : (+ (displayName[0]?.toUpperCase() ?? "A")+ )}+ </StyledAvatar>+ );+ })}+ </AvatarStack>+ <UserNameText>{displayText}</UserNameText>+ <ActionText>{actionText}</ActionText>+ </FeedItemContent>+ {item.thumbnailURL && (+ <ThumbnailImage src={item.thumbnailURL} alt="" />+ )}+ </FeedItemContainer>+ );+};++// =============================================================================+// Main Component+// =============================================================================++/**+ * Extracts navigation info from a feed item for click handling.+ */+const getFeedItemClickInfo = (+ item: PublicFeedItem,+): PublicFeedItemClickInfo => {+ switch (item.type) {+ case "liked_photo":+ case "liked_video":+ return { type: item.type, fileID: item.fileID };+ case "commented_photo":+ case "commented_video":+ return {+ type: item.type,+ fileID: item.fileID,+ commentID: item.commentID,+ };+ case "replied_comment":+ return {+ type: item.type,+ fileID: item.fileID!,+ commentID: item.replyID,+ };+ case "liked_comment":+ return {+ type: item.type,+ fileID: item.fileID!,+ commentID: item.commentID,+ };+ }+};++/**+ * A sidebar panel for displaying the activity feed for a public album.+ */+export const PublicFeedSidebar: React.FC<PublicFeedSidebarProps> = ({+ open,+ onClose,+ files = [],+ credentials,+ collectionKey,+ onItemClick,+}) => {+ const [thumbnailCache, setThumbnailCache] = useState<ThumbnailCache>(+ new Map(),+ );+ const [fileTypeCache, setFileTypeCache] = useState<FileTypeCache>(+ new Map(),+ );+ const [comments, setComments] = useState<PublicFeedComment[]>([]);+ const [reactions, setReactions] = useState<PublicFeedReaction[]>([]);+ const [maskedEmails, setMaskedEmails] = useState<Map<number, string>>(+ new Map(),+ );+ const [anonUserNames, setAnonUserNames] = useState<Map<string, string>>(+ new Map(),+ );+ const [isLoading, setIsLoading] = useState(false);++ // Build file type cache from files+ useEffect(() => {+ const cache = new Map<number, number>();+ for (const file of files) {+ cache.set(file.id, file.metadata.fileType);+ }+ setFileTypeCache(cache);+ }, [files]);++ // Load thumbnails for files that have reactions/comments+ useEffect(() => {+ const loadThumbnails = async () => {+ // Get unique file IDs from comments and reactions+ const fileIDsWithActivity = new Set<number>();+ for (const c of comments) {+ if (c.fileID) fileIDsWithActivity.add(c.fileID);+ }+ for (const r of reactions) {+ if (r.fileID) fileIDsWithActivity.add(r.fileID);+ }++ // Find matching files+ const filesToLoad = files.filter((f) =>+ fileIDsWithActivity.has(f.id),+ );++ const newCache = new Map<number, string>();+ for (const file of filesToLoad) {+ try {+ const url =+ await downloadManager.renderableThumbnailURL(file);+ if (url) {+ newCache.set(file.id, url);+ }+ } catch {+ // Ignore thumbnail loading errors+ }+ }+ setThumbnailCache(newCache);+ };++ if (open && (comments.length > 0 || reactions.length > 0)) {+ void loadThumbnails();+ }+ }, [open, comments, reactions, files]);++ // Polling interval for refreshing feed data (5 seconds)+ const FEED_REFRESH_INTERVAL_MS = 5_000;++ // Refresh social data (used for periodic refresh - excludes masked emails)+ const refreshSocialData = useCallback(async () => {+ try {+ const [feedData, anonProfiles] = await Promise.all([+ getPublicAlbumFeed(credentials, collectionKey),+ getPublicAnonProfiles(credentials, collectionKey),+ ]);+ setComments(feedData.comments);+ setReactions(feedData.reactions);+ setAnonUserNames(anonProfiles);+ // Note: Masked emails for registered participants are fetched only+ // on initial load since they rarely change during a session.+ } catch (e) {+ log.error("Failed to refresh public album feed", e);+ }+ }, [credentials, collectionKey]);++ // Initial fetch when sidebar opens (includes masked emails)+ useEffect(() => {+ if (!open) return;++ const fetchInitialData = async () => {+ try {+ const [feedData, anonProfiles, participantEmails] =+ await Promise.all([+ getPublicAlbumFeed(credentials, collectionKey),+ getPublicAnonProfiles(credentials, collectionKey),+ getPublicParticipantsMaskedEmails(credentials),+ ]);+ setComments(feedData.comments);+ setReactions(feedData.reactions);+ setAnonUserNames(anonProfiles);+ setMaskedEmails(participantEmails);+ } catch (e) {+ log.error("Failed to fetch public album feed", e);+ }+ };++ setIsLoading(true);+ void fetchInitialData().finally(() => setIsLoading(false));+ }, [open, credentials, collectionKey]);++ // Periodic refresh while sidebar is open+ useInterval(+ refreshSocialData,+ open && !isLoading ? FEED_REFRESH_INTERVAL_MS : null,+ );++ const feedItems = useMemo(+ () =>+ processFeedItems(+ comments,+ reactions,+ thumbnailCache,+ fileTypeCache,+ maskedEmails,+ anonUserNames,+ ),+ [+ comments,+ reactions,+ thumbnailCache,+ fileTypeCache,+ maskedEmails,+ anonUserNames,+ ],+ );++ return (+ <SidebarDrawer open={open} onClose={onClose} anchor="right">+ <DrawerContentWrapper>+ <Header>+ <Typography+ sx={(theme) => ({+ color: "#000",+ fontWeight: 600,+ ...theme.applyStyles("dark", { color: "#fff" }),+ })}+ >+ {t("feed")}+ </Typography>+ <CloseButton onClick={onClose}>+ <CloseIcon sx={{ fontSize: 22 }} />+ </CloseButton>+ </Header>++ <ContentContainer>+ {isLoading ? (+ <LoadingContainer>+ <CircularProgress size={24} />+ </LoadingContainer>+ ) : feedItems.length === 0 ? (+ <EmptyStateText>{t("no_activity_yet")}</EmptyStateText>+ ) : (+ feedItems.map((item) => (+ <FeedItemRow+ key={item.id}+ item={item}+ onClick={+ onItemClick+ ? () => {+ onItemClick(+ getFeedItemClickInfo(item),+ );+ }+ : undefined+ }+ />+ ))+ )}+ </ContentContainer>+ </DrawerContentWrapper>+ </SidebarDrawer>+ );+};++// =============================================================================+// Styled Components+// =============================================================================++// Drawer & Layout+const SidebarDrawer = styled(Drawer)(({ theme }) => ({+ zIndex: 2100, // Above TripLayout nav buttons (z-index: 2000)+ "& .MuiDrawer-paper": {+ width: "23vw",+ minWidth: "520px",+ maxWidth: "calc(100% - 32px)",+ height: "calc(100% - 32px)",+ margin: "16px",+ borderRadius: "36px",+ backgroundColor: "#FAFAFA",+ padding: "24px 24px 32px 24px",+ boxShadow: "none",+ border: "1px solid #E0E0E0",+ display: "flex",+ flexDirection: "column",+ overflow: "visible",+ "@media (max-width: 450px)": {+ width: "100%",+ minWidth: "unset",+ maxWidth: "100%",+ height: "100%",+ margin: 0,+ borderRadius: 0,+ },+ ...theme.applyStyles("dark", {+ backgroundColor: "#1b1b1b",+ border: "1px solid rgba(255, 255, 255, 0.18)",+ }),+ },+ "& .MuiBackdrop-root": { backgroundColor: "rgba(0, 0, 0, 0.65)" },+}));++const DrawerContentWrapper = styled(Box)(() => ({+ position: "relative",+ display: "flex",+ flexDirection: "column",+ flex: 1,+ minHeight: 0,+}));++const Header = styled(Stack)(() => ({+ flexDirection: "row",+ alignItems: "center",+ justifyContent: "space-between",+ marginBottom: 48,+}));++const CloseButton = styled(IconButton)(({ theme }) => ({+ backgroundColor: "#F5F5F7",+ color: "#000",+ padding: "8px",+ "&:hover": { backgroundColor: "#E5E5E7" },+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.12)",+ color: "#fff",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.16)" },+ }),+}));++const ContentContainer = styled(Box)(({ theme }) => ({+ flex: 1,+ overflow: "auto",+ marginRight: -24,+ paddingRight: 24,+ "&::-webkit-scrollbar": { width: "6px" },+ "&::-webkit-scrollbar-track": { background: "transparent" },+ "&::-webkit-scrollbar-thumb": {+ background: "rgba(0, 0, 0, 0.2)",+ borderRadius: "3px",+ },+ scrollbarWidth: "thin",+ scrollbarColor: "rgba(0, 0, 0, 0.2) transparent",+ ...theme.applyStyles("dark", {+ "&::-webkit-scrollbar-thumb": {+ background: "rgba(255, 255, 255, 0.2)",+ },+ scrollbarColor: "rgba(255, 255, 255, 0.2) transparent",+ }),+}));++// Feed Item Components+const FeedItemContainer = styled(Box)(({ theme }) => ({+ display: "flex",+ alignItems: "flex-start",+ gap: 12,+ marginBottom: 40,+ cursor: "pointer",+ position: "relative",+ "&:not(:last-child)::before": {+ content: '""',+ position: "absolute",+ left: 16,+ top: 33,+ bottom: -40,+ width: 2,+ backgroundImage:+ "repeating-linear-gradient(to bottom, #E6E6E6 0px, #E6E6E6 8px, transparent 8px, transparent 16px)",+ borderRadius: 1,+ ...theme.applyStyles("dark", {+ backgroundImage:+ "repeating-linear-gradient(to bottom, rgba(255, 255, 255, 0.18) 0px, rgba(255, 255, 255, 0.18) 8px, transparent 8px, transparent 16px)",+ }),+ },+ "&:last-child": { marginBottom: 0 },+}));++const IconContainer = styled(Box)(({ theme }) => ({+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ width: 33,+ height: 33,+ flexShrink: 0,+ backgroundColor: "#fff",+ borderRadius: "50%",+ position: "relative",+ zIndex: 1,+ ...theme.applyStyles("dark", { backgroundColor: "#2a2a2a" }),+}));++const FeedItemContent = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ gap: 4,+ flex: 1,+ minWidth: 0,+}));++const AvatarStack = styled(Box)(() => ({+ display: "flex",+ flexDirection: "row",+ alignItems: "center",+}));++const StyledAvatar = styled(Avatar)(({ theme }) => ({+ width: 32,+ height: 32,+ fontSize: 14,+ fontWeight: 600,+ border: "2px solid #FAFAFA",+ marginLeft: -8,+ "&:first-of-type": { marginLeft: 0 },+ ...theme.applyStyles("dark", { border: "2px solid #1b1b1b" }),+}));++const UserNameText = styled(Typography)(({ theme }) => ({+ fontWeight: 600,+ fontSize: 14,+ color: "#000",+ whiteSpace: "nowrap",+ overflow: "hidden",+ textOverflow: "ellipsis",+ ...theme.applyStyles("dark", { color: "#fff" }),+}));++const ActionText = styled(Typography)(({ theme }) => ({+ fontSize: 13,+ color: "#666",+ whiteSpace: "nowrap",+ overflow: "hidden",+ textOverflow: "ellipsis",+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.7)" }),+}));++const ThumbnailImage = styled("img")(() => ({+ width: 76,+ height: 76,+ borderRadius: 8,+ objectFit: "cover",+ flexShrink: 0,+}));++const LoadingContainer = styled(Box)(() => ({+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ height: "100%",+ // Offset for header (marginBottom: 48) + padding diff (32-24=8) = 56, halved+ marginTop: -28,+}));++const EmptyStateText = styled(Typography)(({ theme }) => ({+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ height: "100%",+ // Offset for header (marginBottom: 48) + padding diff (32-24=8) = 56, halved+ marginTop: -28,+ color: "#666",+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.6)" }),+}));diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/PublicLikeModal.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/PublicLikeModal.tsxnew file mode 100644index 0000000000..9ac5430118--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/PublicLikeModal.tsx@@ -0,0 +1,292 @@+import CloseIcon from "@mui/icons-material/Close";+import {+ Box,+ Button,+ Dialog,+ IconButton,+ styled,+ Typography,+} from "@mui/material";+import { type ModalVisibilityProps } from "ente-base/components/utils/modal";+import { t } from "i18next";+import React from "react";++// =============================================================================+// Icons+// =============================================================================++const LikeIllustration: React.FC = () => (+ <svg+ width="126"+ height="121"+ viewBox="0 0 126 121"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M84.7129 23.0781C96.7222 23.0784 105.29 32.8476 105.29 44.499C105.29 53.3449 99.7258 62.2116 93.4453 69.4932C87.0622 76.8936 79.4391 83.2238 74.3574 87.0557C69.973 90.3616 64.031 90.3614 59.6465 87.0557C54.5648 83.2238 46.9408 76.8937 40.5576 69.4932C34.2771 62.2116 28.7129 53.3449 28.7129 44.499C28.713 32.8474 37.2813 23.0781 49.291 23.0781C54.9545 23.0782 60.4297 24.9062 67.001 30.9004C73.5726 24.9056 79.0491 23.0781 84.7129 23.0781Z"+ fill="#08C225"+ stroke="#232323"+ strokeWidth="5.73358"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ <mask+ id="mask0_public_like"+ style={{ maskType: "alpha" }}+ maskUnits="userSpaceOnUse"+ x="31"+ y="25"+ width="72"+ height="62"+ >+ <path+ d="M61.3721 84.7662C51.3787 77.2306 31.5801 60.0026 31.5801 44.4993C31.5801 34.2522 39.0372 25.9453 49.2909 25.9453C54.6041 25.9453 59.9173 27.7313 67.0016 34.8751C74.086 27.7313 79.3992 25.9453 84.7124 25.9453C94.9659 25.9453 102.423 34.2522 102.423 44.4993C102.423 60.0026 82.6247 77.2306 72.6312 84.7662C69.2683 87.3019 64.735 87.3019 61.3721 84.7662Z"+ fill="#08C225"+ />+ </mask>+ <g mask="url(#mask0_public_like)">+ <path+ d="M47.5975 41.0431C46.8515 39.3306 47.9859 37.1849 50.1312 36.2504C52.2765 35.316 54.6203 35.9467 55.3662 37.6591C56.1121 39.3716 54.9777 41.5173 52.8324 42.4518C50.6872 43.3862 48.3434 42.7555 47.5975 41.0431Z"+ fill="white"+ />+ <path+ d="M44.5677 45.0545C44.3136 44.4712 44.7025 43.7391 45.4364 43.4194C46.1704 43.0997 46.9713 43.3135 47.2254 43.8968C47.4795 44.4802 47.0906 45.2123 46.3567 45.532C45.6227 45.8517 44.8218 45.6379 44.5677 45.0545Z"+ fill="white"+ />+ <path+ d="M102.994 32.271C101.622 55.1395 78.9821 78.0073 50.9683 82.581C49.2531 88.2982 42.3926 93.7861 42.3926 95.1582C42.3926 96.5303 48.1097 107.926 50.9683 113.453L89.8447 101.447L115 66.5725C113.094 57.9969 106.196 31.3563 102.994 32.271Z"+ fill="#46A030"+ />+ <path+ d="M59.7039 28.2666C34.9591 23.1218 29.8137 47.7054 32.6723 55.1377L23.1143 51.7074C21.3992 47.3243 18.1976 37.9863 19.1123 35.6995C20.0271 33.4126 22.1615 16.833 23.1143 8.829L55.1302 3.68359L96.8651 13.9744C97.6274 18.1664 98.4659 26.8936 95.7217 28.2666C80.2855 22.5506 66.5644 33.9826 66.5644 33.4109C66.5644 32.9535 68.4701 30.5523 69.423 29.4089C66.3738 29.0281 60.1612 28.2666 59.7039 28.2666Z"+ fill="white"+ />+ </g>+ <path+ d="M20.9639 58.8477C14.9399 61.182 10.9104 66.0874 11.263 71.48C10.9104 66.0874 6.28324 61.7544 -9.80907e-05 60.2184C6.02383 57.884 10.0533 52.9787 9.70073 47.5861C10.0533 52.9787 14.6805 57.3117 20.9639 58.8477Z"+ fill="#08C225"+ />+ <path+ d="M119.579 91.9746C111.591 92.7003 105.114 97.1692 103.689 103.722C105.114 97.1692 101.077 90.4145 94.1117 86.438C102.099 85.7122 108.576 81.2434 110.001 74.6902C108.576 81.2434 112.613 87.9981 119.579 91.9746Z"+ fill="#08C225"+ />+ <path+ d="M112.728 9.21189C108.334 9.91374 104.912 12.6353 104.37 16.3181C104.912 12.6353 102.421 9.04853 98.4114 7.10627C102.806 6.40442 106.228 3.68284 106.77 7.55054e-05C106.228 3.68284 108.719 7.26962 112.728 9.21189Z"+ fill="#08C225"+ />+ </svg>+);++// =============================================================================+// Types+// =============================================================================++export interface PublicLikeModalProps extends ModalVisibilityProps {+ /**+ * Called when user clicks "Like anonymously".+ */+ onLikeAnonymously: () => void;+ /**+ * Called when user clicks "Join album to like".+ */+ onJoinAlbumToLike: () => void;+ /**+ * Whether the "Join album" option is enabled for this public link.+ * When false, the "Join album and like" button will be hidden.+ */+ enableJoin?: boolean;+}++/**+ * Modal dialog for liking a photo in a public album.+ * Shows options to like anonymously or sign in to like.+ */+export const PublicLikeModal: React.FC<PublicLikeModalProps> = ({+ open,+ onClose,+ onLikeAnonymously,+ onJoinAlbumToLike,+ enableJoin = true,+}) => {+ return (+ <StyledDialog open={open} onClose={onClose}>+ <DialogWrapper>+ <CloseButton onClick={onClose}>+ <CloseIcon sx={{ fontSize: 20 }} />+ </CloseButton>++ <ContentContainer>+ <IllustrationWrapper>+ <LikeIllustration />+ </IllustrationWrapper>++ <TitleSection>+ <Title>{t("give_it_a_like")}</Title>+ {enableJoin && (+ <Subtitle>{t("public_like_subtitle")}</Subtitle>+ )}+ </TitleSection>++ <ButtonsSection sx={!enableJoin ? { mt: 4 } : undefined}>+ {enableJoin ? (+ <AnonymousButton+ variant="outlined"+ fullWidth+ onClick={onLikeAnonymously}+ >+ {t("like_anonymously")}+ </AnonymousButton>+ ) : (+ <SignInButton+ variant="contained"+ fullWidth+ onClick={onLikeAnonymously}+ >+ {t("like_anonymously")}+ </SignInButton>+ )}+ {enableJoin && (+ <SignInButton+ variant="contained"+ fullWidth+ onClick={onJoinAlbumToLike}+ >+ {t("join_album_and_like")}+ </SignInButton>+ )}+ </ButtonsSection>+ </ContentContainer>+ </DialogWrapper>+ </StyledDialog>+ );+};++// =============================================================================+// Styled Components+// =============================================================================++const StyledDialog = styled(Dialog)(({ theme }) => ({+ "& .MuiDialog-paper": {+ width: 381,+ maxWidth: "calc(100% - 32px)",+ borderRadius: 28,+ backgroundColor: "#fff",+ padding: 0,+ margin: 16,+ overflow: "visible",+ boxShadow: "none",+ border: "1px solid #E0E0E0",+ ...theme.applyStyles("dark", {+ backgroundColor: "#1b1b1b",+ border: "1px solid rgba(255, 255, 255, 0.18)",+ }),+ },+ "& .MuiBackdrop-root": { backgroundColor: "rgba(0, 0, 0, 0.5)" },+}));++const DialogWrapper = styled(Box)(() => ({+ position: "relative",+ padding: "48px 16px 16px 16px",+}));++const CloseButton = styled(IconButton)(({ theme }) => ({+ position: "absolute",+ top: 11,+ right: 12,+ backgroundColor: "#FAFAFA",+ color: "#000",+ padding: 10,+ "&:hover": { backgroundColor: "#F0F0F0" },+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.12)",+ color: "#fff",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.16)" },+ }),+}));++const ContentContainer = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 16,+}));++const IllustrationWrapper = styled(Box)(() => ({+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ marginBottom: 8,+}));++const TitleSection = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 9,+ textAlign: "center",+ marginBottom: 16,+}));++const Title = styled(Typography)(({ theme }) => ({+ fontWeight: 600,+ fontSize: 24,+ lineHeight: "28px",+ letterSpacing: "-0.48px",+ color: "#000",+ ...theme.applyStyles("dark", { color: "#fff" }),+}));++const Subtitle = styled(Typography)(({ theme }) => ({+ fontWeight: 500,+ fontSize: 14,+ lineHeight: "20px",+ color: "#666666",+ maxWidth: 240,+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.7)" }),+}));++const ButtonsSection = styled(Box)(() => ({+ width: "100%",+ display: "flex",+ flexDirection: "column",+ gap: 12,+}));++const AnonymousButton = styled(Button)(({ theme }) => ({+ display: "flex",+ padding: "20px 16px",+ justifyContent: "center",+ alignItems: "center",+ gap: 8,+ flex: "1 0 0",+ borderRadius: 20,+ backgroundColor: "rgba(0, 0, 0, 0.04)",+ border: "none",+ fontSize: 16,+ fontWeight: 500,+ textTransform: "none",+ color: "#000",+ "&:hover": { backgroundColor: "rgba(0, 0, 0, 0.08)", border: "none" },+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.08)",+ color: "#fff",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.12)" },+ }),+}));++const SignInButton = styled(Button)(() => ({+ display: "flex",+ padding: "20px 16px",+ justifyContent: "center",+ alignItems: "center",+ gap: 8,+ flex: "1 0 0",+ borderRadius: 20,+ backgroundColor: "#08C225",+ fontSize: 16,+ fontWeight: 500,+ textTransform: "none",+ color: "#fff",+ "&:hover": { backgroundColor: "#07A820" },+}));diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/data-source.ts b/web/apps/albums/vendor/ente-gallery/components/viewer/data-source.tsnew file mode 100644index 0000000000..2325584b27--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/data-source.ts@@ -0,0 +1,772 @@+import log from "ente-base/log";+import type { FileInfoExif } from "ente-gallery/components/FileInfo";+import { downloadManager } from "ente-gallery/services/download";+import { extractRawExif, parseExif } from "ente-gallery/services/exif";+import {+ hlsPlaylistDataForFile,+ type HLSPlaylistDataForFile,+} from "ente-gallery/services/video";+import type { EnteFile } from "ente-media/file";+import { FileType } from "ente-media/file-type";+import { ensureString } from "ente-utils/ensure";++/**+ * This is a subset of the fields expected by PhotoSwipe itself (see the+ * {@link SlideData} type exported by PhotoSwipe).+ */+interface PhotoSwipeSlideData {+ /**+ * The image URL expected by PhotoSwipe.+ *+ * This is set to the URL of the image that should be shown in the image+ * viewer component provided by PhotoSwipe.+ *+ * It will be a renderable (i.e., possibly converted) object URL obtained+ * from the current "best" image we have.+ *+ * For example, if all we have is the thumbnail, then this'll be an+ * renderable object URL obtained from the thumbnail data. Then later when+ * we fetch the original image, this'll be the renderable object URL derived+ * from the original. But if it is a video, this will just be cleared.+ */+ src?: string | undefined;+ /**+ * The width (in pixels) of the {@link src} image.+ */+ width?: number | undefined;+ /**+ * The height (in pixels) of the {@link src} image.+ */+ height?: number | undefined;+ /**+ * The alt text associated with the file.+ *+ * This will be set to the file's caption. PhotoSwipe will use it as the alt+ * text when constructing img elements (if any) for this item. We will also+ * use this for displaying the visible "caption" element atop the file (both+ * images and video).+ */+ alt?: string;+ /**+ * The HTML (string) contents of the slide, if we don't wish for it to show+ * an image.+ */+ html?: string | undefined;+}++/**+ * The data returned by the flagship {@link itemDataForFile} function provided+ * by the file viewer data source module.+ *+ * This is the minimal data expected by PhotoSwipe, plus some fields we use+ * ourselves in the custom scaffolding we have around PhotoSwipe.+ */+export type ItemData = PhotoSwipeSlideData & {+ /**+ * The ID of the {@link EnteFile} whose data we are.+ */+ fileID: number;+ /**+ * The {@link EnteFile} type of the file whose data we are.+ *+ * Expected to be one of {@link FileType}.+ */+ fileType: number;+ /**+ * The renderable object URL of the image associated with the file.+ *+ * - For images, this will be the object URL of a renderable image.+ * - For videos, this will not be defined.+ * - For live photos, this will be a renderable object URL of the image+ * portion of the live photo.+ */+ imageURL?: string;+ /**+ * The original image associated with the file, as a Blob.+ *+ * - For images, this will be the original image itself.+ * - For live photos, this will be the image component of the live photo.+ * - For videos, this will be not be present.+ */+ originalImageBlob?: Blob;+ /**+ * The renderable object URL of the video associated with the file.+ *+ * - For images, this will not be defined.+ * - For videos, this will be the object URL of a renderable video (but only+ * if {@link videoPlaylistURL} is not set).+ * - For live photos, this will be a renderable object URL of the video+ * portion of the live photo.+ */+ videoURL?: string;+ /**+ * The object URL to an HLS playlist that can be used to play the video+ * associated with the file in a streaming manner.+ *+ * This will only be defined for videos for which a corresponding streamable+ * version has been created.+ *+ * Only one of {@link videoURL} or {@link videoPlaylistURL} will be set at a+ * time.+ */+ videoPlaylistURL?: string;+ /**+ * The DOM element ID of the `media-controller` element that is showing the+ * video for the current item.+ *+ * If present, this value will be used to display controls for controlling+ * the video wrapped by the media-controller.+ *+ * This is only set for videos that are streamed using HLS (i.e. videos for+ * which {@link videoPlaylistURL} has also been set).+ */+ mediaControllerID?: string;+ /**+ * `true` if we should indicate to the user that we're still fetching data+ * for this file.+ *+ * Note that this doesn't imply that the data is final. e.g. for a live+ * photo, this will be not be set after we get the original image component,+ * but the fetch for the video component might still be ongoing.+ */+ isContentLoading?: boolean;+ /**+ * This will be explicitly set to `false` when we want to disable+ * PhotoSwipe's built in image zoom.+ *+ * It is set while the thumbnail is loaded.+ */+ isContentZoomable?: boolean;+ /**+ * This will be `true` if the fetch for the file's data has failed.+ *+ * It is possible for this to be set in tandem with the content URLs also+ * being set (e.g. if we were able to use the cached thumbnail, but the+ * original file could not be fetched because of an network error).+ */+ fetchFailed?: boolean;+ /**+ * This will be `true` if the item data for this particular file is+ * considered transient, and should not be cached.+ */+ isTransient?: boolean;+};++/**+ * This module stores and serves data required by our custom PhotoSwipe+ * instance, effectively acting as an in-memory cache.+ *+ * By keeping this independent of the lifetime of the PhotoSwipe instance, we+ * can reuse the same cache for multiple displays of our file viewer.+ *+ * This will be cleared on logout.+ */+class FileViewerDataSourceState {+ /**+ * Non-zero if a file viewer is currently open.+ *+ * This is a counter, but the file viewer data source has other many+ * assumptions about only a single instance of PhotoSwipe being active at a+ * time, so this could've been a boolean as well.+ */+ viewerCount = 0;+ /**+ * True if our state needs to be cleared the next time the file viewer is+ * closed.+ */+ needsReset = false;+ /**+ * The best data we have for a particular file (ID).+ */+ itemDataByFileID = new Map<number, ItemData>();+ /**+ * The validity (if applicable) for the corresponding entry in+ * {@link itemDataByFileID}.+ */+ itemDataValidTillByFileID = new Map<number, Date>();+ /**+ * The latest callback registered for notifications of better data being+ * available for a particular file (ID).+ */+ needsRefreshByFileID = new Map<number, () => void>();+ /**+ * The exif data we have for a particular file (ID).+ */+ fileInfoExifByFileID = new Map<number, FileInfoExif>();+ /**+ * The latest callback registered for notifications of exif data being+ * available for a particular file (ID).+ */+ exifObserverByFileID = new Map<number, (exif: FileInfoExif) => void>();+}++/**+ * State shared by functions in this module.+ *+ * See {@link FileViewerDataSourceState}.+ */+let _state = new FileViewerDataSourceState();++const resetState = () => {+ _state = new FileViewerDataSourceState();+};++/**+ * Clear any internal state maintained by the file viewer data source.+ */+export const logoutFileViewerDataSource = resetState;++/**+ * Clear any internal state if possible. This is invoked when files have been+ * updated on remote, and those changes synced locally.+ *+ * Because we also retain callbacks, clearing existing item data when the file+ * viewer is open can lead to problematic edge cases. Thus, this function+ * behaves in two different ways:+ *+ * - If the file viewer is already open, then we enqueue a reset for when it is+ * closed the next time.+ *+ * - Otherwise we immediately reset our state.+ *+ * See: [Note: Changes to underlying files when file viewer is open]+ */+export const resetFileViewerDataSourceOnClose = () => {+ if (_state.viewerCount) {+ _state.needsReset = true;+ } else {+ resetState();+ }+};++/**+ * Called by the file viewer whenever it is opened.+ */+export const fileViewerWillOpen = () => {+ _state.viewerCount++;+};++/**+ * Called by the file viewer whenever it has been closed.+ */+export const fileViewerDidClose = () => {+ _state.viewerCount--;+ if (_state.needsReset && _state.viewerCount == 0) {+ // Reset everything.+ resetState();+ } else {+ // Selectively clear.+ forgetFailedOrTransientItems();+ forgetExif();+ }+};++/**+ * Options to modify the default behaviour of {@link itemDataForFile}.+ */+export interface ItemDataOpts {+ videoQuality?: "auto" | "original";+}++/**+ * Return the best available {@link ItemData} for rendering the given+ * {@link file}.+ *+ * If an entry does not exist for a particular file, then it is lazily added on+ * demand, and updated as we keep getting better data (thumbnail, original) for+ * the file.+ *+ * At each step, we call the provided callback so that file viewer can call us+ * again to get the updated data.+ *+ * @param opts Options to modify the default behaviours.+ *+ * ---+ *+ * Detailed flow:+ *+ * If we already have the final data about the file, then this function will+ * return it and do nothing subsequently.+ *+ * Otherwise, it will:+ *+ * 1. Return empty slide data; PhotoSwipe will not show anything in the image+ * area but will otherwise render UI controls properly (in most cases a+ * cached renderable thumbnail URL will be available shortly).+ *+ * 2. Insert this empty data in its cache so that we don't enqueue multiple+ * updates.+ *+ * Then it we start fetching data for the file.+ *+ * First it'll fetch the thumbnail. Once that is done, it'll update the data it+ * has cached, and notify the caller (using the provided callback) so it can+ * refresh the slide.+ *+ * Then it'll continue fetching the original.+ *+ * - For images this will be the single original.+ *+ * - For videos this will be either the HLS playlist to a streamable variant of+ * the video (if the video has one available), or the original video itself.+ *+ * - For live photos, this will also be a two step process, first fetching the+ * video component, then fetching the image component.+ *+ * At this point, the data for this file will be considered final, and+ * subsequent calls for the same file will return this same value unless it is+ * invalidated.+ *+ * If at any point an error occurs, we reset our cache for this file so that the+ * next time the data is requested we repeat the process instead of continuing+ * to serve the incomplete result.+ */+export const itemDataForFile = (+ file: EnteFile,+ opts: ItemDataOpts | undefined,+ needsRefresh: () => void,+) => {+ const fileID = file.id;+ const fileType = file.metadata.fileType;++ const validTill = _state.itemDataValidTillByFileID.get(fileID);+ if (validTill && validTill < new Date()) {+ // Don't use the cached entry if it has become stale.+ forgetItemDataForFileID(fileID);+ }++ let itemData = _state.itemDataByFileID.get(fileID);++ // We assume that there is only one file viewer that is using us at a given+ // point of time. This assumption is currently valid.+ _state.needsRefreshByFileID.set(file.id, needsRefresh);++ if (!itemData) {+ itemData = { fileID, fileType, isContentLoading: true };+ _state.itemDataByFileID.set(file.id, itemData);+ void enqueueUpdates(file, opts);+ }++ return itemData;+};++/**+ * Forget item data for the given {@link file}.+ *+ * This is called when we change the options passed to {@link itemDataForFile},+ * and so would like to clear any previously cached data.+ */+export const forgetItemDataForFileID = (fileID: number) => {+ _state.itemDataByFileID.delete(fileID);+ _state.itemDataValidTillByFileID.delete(fileID);+};++/**+ * Forget item data for the given {@link file} if its fetch had failed, or if it+ * is caching something that is transient in nature.+ *+ * It is called when the user moves away from a slide. In particular, this way+ * we can reset failures, if any, for a slide so that the fetch is tried again+ * when we come back to it.+ *+ * [Note: File viewer preloading and contentDeactivate]+ *+ * Note that because of preloading, this will only have a user visible effect if+ * the user moves out of the preload range. Let's take an example:+ *+ * - User opens slide at index `i`. Then the adjacent slides, `i - 1` and `i ++ * 1`, also get preloaded.+ *+ * - User moves away from `i` (in either direction, but let us take the example+ * if they move `i - 1`).+ *+ * - This function will get called for `i` and will clear any failed or+ * transient state.+ *+ * - But since PhotoSwipe already has the slides ready for `i`, if the user then+ * moves back to `i` then PhotoSwipe will not attempt to recreate the slide+ * and so will not even try to get "itemData". So this will only have an+ * effect if they move out of preload range (e.g. `i - 1`, `i - 2`), and then+ * back (`i - 1`, `i`).+ *+ * See: [Note: File viewer error handling]+ *+ * See: [Note: Caching HLS playlist data]+ */+export const forgetItemDataForFileIDIfNeeded = (fileID: number) => {+ const itemData = _state.itemDataByFileID.get(fileID);+ if (itemData?.fetchFailed || itemData?.isTransient)+ forgetItemDataForFileID(fileID);+};++/**+ * Update the alt attribute of the {@link ItemData}, if any, associated with the+ * given {@link EnteFile}.+ *+ * @param fileID The ID of the file whose {@link alt} attribute we want to+ * update.+ *+ * @param newAlt The new value of the {@link alt} attribute.+ */+export const updateItemDataAlt = (fileID: number, newAlt: string) => {+ const itemData = _state.itemDataByFileID.get(fileID);+ if (itemData) {+ itemData.alt = newAlt;+ }+};++/**+ * Forget item data for the all files whose fetch had failed, or if the+ * corresponding item data is transient and shouldn't be cached.+ *+ * This is called when the user closes the file viewer; in particular, this way+ * we attempt a full retry for previously failed files when the user reopens the+ * viewer the next time.+ */+const forgetFailedOrTransientItems = () =>+ [..._state.itemDataByFileID.keys()].forEach(+ forgetItemDataForFileIDIfNeeded,+ );++const enqueueUpdates = async (+ file: EnteFile,+ opts: ItemDataOpts | undefined,+) => {+ const fileID = file.id;+ const fileType = file.metadata.fileType;++ const update = (itemData: Partial<ItemData>, validTill?: Date) => {+ // Use the file's caption as its alt text (in addition to using it as+ // the visible caption).+ const alt = file.pubMagicMetadata?.data.caption;++ _state.itemDataByFileID.set(file.id, {+ ...itemData,+ fileType,+ fileID,+ alt,+ });+ if (validTill) {+ _state.itemDataValidTillByFileID.set(file.id, validTill);+ } else {+ _state.itemDataValidTillByFileID.delete(file.id);+ }+ _state.needsRefreshByFileID.get(file.id)?.();+ };++ const updateVideo = (+ videoURL: string | undefined,+ hlsPlaylistData: HLSPlaylistDataForFile,+ ) => {+ const videoURLD = videoURL ? { videoURL } : {};+ // See: [Note: Caching HLS playlist data]+ //+ // In brief, there are three cases:+ if (typeof hlsPlaylistData == "object") {+ // 1. If we have a playlist, we can cache it+ const {+ playlistURL: videoPlaylistURL,+ width,+ height,+ } = hlsPlaylistData;+ update(+ { ...videoURLD, videoPlaylistURL, width, height },+ createHLSPlaylistItemDataValidity(),+ );+ } else {+ // 2. if the file is not eligible ("skip"), we can cache it.+ // 3. Otherwise it's transient and shouldn't be cached indefinitely.+ update({ ...videoURLD, isTransient: hlsPlaylistData != "skip" });+ }+ };++ // Use the last best available data, but stop showing the loading indicator+ // and instead show the error indicator.+ const markFailed = () => {+ const lastData: Partial<ItemData> =+ _state.itemDataByFileID.get(file.id) ?? {};+ delete lastData.isContentLoading;+ update({ ...lastData, fetchFailed: true });+ };++ try {+ const thumbnailURL = await downloadManager.renderableThumbnailURL(file);+ // While the types don't reflect it, it is safe to use the ! (null+ // assertion) here since renderableThumbnailURL can throw but will not+ // return undefined by default.+ const thumbnailData = await withDimensionsIfPossible(+ ensureString(thumbnailURL),+ );++ // If the aspect ratio of the original file matches the aspect ratio of+ // the thumbnail, then render the thumbnail using the original's+ // dimensions for a better visual experience.+ const { width, height } = thumbnailDimensions(thumbnailData, file);++ update({+ ...thumbnailData,+ width,+ height,+ isContentLoading: true,+ isContentZoomable: false,+ });+ } catch (e) {+ // If we can't even get the thumbnail, then a network error is likely+ // (download manager already has retries); in particular, it cannot be a+ // format error since thumbnails are already standard JPEGs.+ //+ // Notify the user of the error. The entire process will be retried when+ // they reopen the slide later.+ //+ // See: [Note: File viewer error handling]+ log.error("Failed to fetch thumbnail", e);+ markFailed();+ return;+ }++ try {+ let hlsPlaylistData: HLSPlaylistDataForFile;+ if (file.metadata.fileType == FileType.video) {+ hlsPlaylistData = await hlsPlaylistDataForFile(+ file,+ downloadManager.publicAlbumsCredentials,+ );+ // We have a HLS playlist, and the user didn't request the original.+ // Early return so that we don't initiate a fetch for the original.+ if (+ typeof hlsPlaylistData == "object" &&+ opts?.videoQuality != "original"+ ) {+ updateVideo(undefined, hlsPlaylistData);+ return;+ }+ }++ const sourceURLs = await downloadManager.renderableSourceURLs(file);++ switch (sourceURLs.type) {+ case "image": {+ const { imageURL, originalImageBlob } = sourceURLs;+ const itemData = await withDimensionsIfPossible(imageURL);+ update({ ...itemData, imageURL, originalImageBlob });+ break;+ }++ case "video": {+ const { videoURL } = sourceURLs;+ updateVideo(videoURL, hlsPlaylistData);+ break;+ }++ case "livePhoto": {+ // The image component of a live photo usually is an HEIC file,+ // which cannot be displayed natively by many browsers and needs+ // a conversion, which is slow on web (faster on desktop). We+ // already have both components available since they're part of+ // the same zip. And in the UI, the first (default) interaction+ // is to loop the live video.+ //+ // For these reasons, we resolve with the video first, then+ // resolve with the image.+ const videoURL = await sourceURLs.videoURL();+ update({+ videoURL,+ isContentLoading: true,+ isContentZoomable: false,+ });+ const imageURL = await sourceURLs.imageURL();+ const originalImageBlob = sourceURLs.originalImageBlob;+ update({+ ...(await withDimensionsIfPossible(imageURL)),+ imageURL,+ originalImageBlob,+ videoURL,+ });+ break;+ }+ }+ } catch (e) {+ // [Note: File viewer error handling]+ //+ // Generally, file downloads will fail because of two reasons: Network+ // errors, or format errors.+ //+ // In the first case (network error), the `renderableSourceURLs` method+ // above will throw. We will show an error indicator icon in the UI, but+ // will keep showing the thumbnail.+ //+ // In the second case (format error), we'll get back a URL, but if a+ // file conversion was needed but not possible (say, it is an+ // unsupported format), we might have at our hands the original file's+ // untouched URL, that the browser might not know how to render.+ //+ // In this case we won't get into an error state here, but PhotoSwipe+ // will encounter an error when trying to render it, and it will show+ // our customized error message ("This file could not be previewed"),+ // but the user will still be able to download it.+ log.error("Failed to fetch file", e);+ markFailed();+ }+};++/**+ * Take a image URL, determine its dimensions using browser APIs if possible,+ * and return the URL and its dimensions in a form that can directly be passed+ * to PhotoSwipe as {@link ItemData}.+ *+ * If the dimensions cannot be extracted (i.e., the browser was not able to load+ * the image), then PhotoSwipe itself will also not likely be able to render it,+ * but we still return the {@link imageURL} back so that PhotoSwipe can show the+ * appropriate error when trying to render it.+ */+const withDimensionsIfPossible = (+ imageURL: string,+): Promise<Partial<ItemData>> =>+ new Promise((resolve) => {+ const image = new Image();+ image.onload = () =>+ resolve({+ src: imageURL,+ width: image.naturalWidth,+ height: image.naturalHeight,+ });+ image.onerror = () => resolve({ src: imageURL });+ image.src = imageURL;+ });++/**+ * Return the dimensions to use for the thumbnail associated with {@link file}.+ *+ * If the aspect ratio of the thumbnail is (approximately) equal to that of the+ * dimensions we have on record for the original image (obtained from the file+ * metadata), then use the dimensions of the original image in lieu of the+ * thumbnail dimensions for a more graceful transition during image loads.+ */+const thumbnailDimensions = (+ { width: thumbnailWidth, height: thumbnailHeight }: Partial<ItemData>,+ file: EnteFile,+) => {+ const { w: imageWidth, h: imageHeight } = file.pubMagicMetadata?.data ?? {};+ if (thumbnailWidth && thumbnailHeight && imageWidth && imageHeight) {+ const arThumb = thumbnailWidth / thumbnailHeight;+ const arImage = imageWidth / imageHeight;+ if (Math.abs(arThumb - arImage) < 0.1) {+ return { width: imageWidth, height: imageHeight };+ }+ }+ return { width: thumbnailWidth, height: thumbnailHeight };+};+/**+ * Return a new validity for a HLS playlist containing pre-signed URLs.+ *+ * The content chunks in HLS playlist generated by+ * {@link hlsPlaylistDataForFile} use pre-signed URLs generated by remote (see+ * `PreSignedRequestValidityDuration` in the museum source). These have a+ * validity of 7 days. We keep a 2 day buffer, and consider any item data that+ * uses such playlist as stale after 5 days.+ */+const createHLSPlaylistItemDataValidity = () =>+ new Date(Date.now() + 5 * 24 * 60 * 60 * 1000); /* 5 days */++/**+ * Return the cached Exif data for the given {@link file}.+ *+ * The shape of the returned data is such that it can directly be used by the+ * {@link FileInfo} sidebar.+ *+ * Exif extraction is not too expensive, and takes around 10-200 ms usually, so+ * this can be done preemptively. As soon as we get data for a particular item+ * as the user swipes through the file viewer, we extract its exif data using+ * {@link updateFileInfoExifIfNeeded}.+ *+ * Then if the user were to open the file info sidebar for that particular file,+ * the associated exif data will be returned by this function. Since the happy+ * path is for synchronous use in a React component, this function synchronously+ * returns the cached value (and the callback is never invoked).+ *+ * The user can open the file info sidebar before the original has been fetched,+ * so it is possible that this function gets called before+ * {@link updateFileInfoExifIfNeeded} has completed. In such cases, this+ * function will synchronously return `undefined`, and then later call the+ * provided {@link observer} once the extraction results are available.+ */+export const fileInfoExifForFile = (+ file: EnteFile,+ observer: (exifData: FileInfoExif) => void,+) => {+ const fileID = file.id;+ const exifData = _state.fileInfoExifByFileID.get(fileID);+ if (exifData) return exifData;++ _state.exifObserverByFileID.set(fileID, observer);+ return undefined;+};++/**+ * Update, if needed, the cached Exif data for with the given {@link itemData}.+ *+ * This function is expected to be called when an item is loaded as PhotoSwipe+ * content. It can be safely called multiple times - it will ignore calls until+ * the item has an associated {@link originalImageBlob}, and it will also ignore calls+ * that are made after exif data has already been extracted.+ *+ * If required, it will extract the exif data from the file, massage it to a+ * form suitable for use by {@link FileInfo}, and stash it in its caches, and+ * notify the most recent observer for that file attached via+ * {@link fileInfoExifForFile}.+ *+ * See also {@link forgetExifForItemData}.+ */+export const updateFileInfoExifIfNeeded = async (itemData: ItemData) => {+ const { fileID, fileType, originalImageBlob } = itemData;++ // We already have it available.+ if (_state.fileInfoExifByFileID.has(fileID)) return;++ const update = (exifData: FileInfoExif) => {+ _state.fileInfoExifByFileID.set(fileID, exifData);+ _state.exifObserverByFileID.get(fileID)?.(exifData);+ };++ // For videos, insert a placeholder.+ if (fileType == FileType.video) {+ update(createPlaceholderFileInfoExif());+ return;+ }++ // This is not a video, but the original image is not available yet.+ if (!originalImageBlob) return;++ try {+ const file = new File([originalImageBlob], "");+ const tags = await extractRawExif(file);+ const parsed = parseExif(tags);+ update({ tags, parsed });+ } catch (e) {+ log.error("Failed to extract exif", e);+ // Save the empty placeholder exif corresponding to the file, no point+ // in unnecessarily retrying this, it will deterministically fail again.+ update(createPlaceholderFileInfoExif());+ }+};++const createPlaceholderFileInfoExif = (): FileInfoExif => ({+ tags: undefined,+ parsed: undefined,+});++/**+ * Clear any cached {@link FileInfoExif} for the given {@link ItemData}.+ */+export const forgetExifForItemData = ({ fileID }: ItemData) => {+ _state.fileInfoExifByFileID.delete(fileID);+ _state.exifObserverByFileID.delete(fileID);+};++/**+ * Clear all cached {@link FileInfoExif}.+ */+export const forgetExif = () => {+ _state.fileInfoExifByFileID.clear();+ _state.exifObserverByFileID.clear();+};diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/icons.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/icons.tsxnew file mode 100644index 0000000000..562a049f1d--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/icons.tsx@@ -0,0 +1,127 @@+/**+ * @file [Note: SVG paths of MUI icons]+ *+ * When creating buttons for use with PhotoSwipe, we need to provide just the+ * contents of the SVG element (e.g. paths) as an HTML string.+ *+ * Since we only need a handful, these strings were created by temporarily+ * adding the following code in some existing React component to render the+ * corresponding MUI icon React component to a string, and retain the path.+ *+ *+ * import { renderToString } from "react-dom/server";+ * import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";+ *+ * console.log(renderToString(<InfoOutlinedIcon />));+ */++// The transforms are not part of the originals, they have been applied+// separately to get these icons to align with the ones built into PhotoSwipe.+const paths = {+ // "@mui/icons-material/ErrorOutline"+ error: '<path d="M11 15h2v2h-2zm0-8h2v6h-2zm.99-5C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8" transform="translate(7, 5.7) scale(0.85)"',+ // Custom heart outline icon (30x26 viewBox)+ heart: '<path d="M12.4926 23.4794C8.64537 20.6025 1.02344 14.0254 1.02344 8.10676C1.02344 4.19475 3.89425 1.02344 7.84162 1.02344C9.88707 1.02344 11.9325 1.70526 14.6598 4.43253C17.3871 1.70526 19.4325 1.02344 21.478 1.02344C25.4253 1.02344 28.2962 4.19475 28.2962 8.10676C28.2962 14.0254 20.6743 20.6025 16.827 23.4794C15.5324 24.4474 13.7872 24.4474 12.4926 23.4794Z" stroke="white" stroke-width="2.04545" stroke-linecap="round" stroke-linejoin="round" fill="none"',+ // Custom heart filled icon (30x26 viewBox) - green fill for liked state+ "heart-fill":+ '<path d="M12.4926 23.4794C8.64537 20.6025 1.02344 14.0254 1.02344 8.10676C1.02344 4.19475 3.89425 1.02344 7.84162 1.02344C9.88707 1.02344 11.9325 1.70526 14.6598 4.43253C17.3871 1.70526 19.4325 1.02344 21.478 1.02344C25.4253 1.02344 28.2962 4.19475 28.2962 8.10676C28.2962 14.0254 20.6743 20.6025 16.827 23.4794C15.5324 24.4474 13.7872 24.4474 12.4926 23.4794Z" stroke="#22c55e" stroke-width="2.04545" stroke-linecap="round" stroke-linejoin="round" fill="#22c55e"',+ // Custom comment bubble icon (28x28 viewBox, scaled to match heart)+ comment:+ '<path d="M13.636 25.9087C16.0633 25.9087 18.4361 25.189 20.4544 23.8404C22.4726 22.4919 24.0456 20.5751 24.9745 18.3326C25.9034 16.09 26.1465 13.6224 25.6729 11.2417C25.1994 8.86105 24.0305 6.67426 22.3141 4.95788C20.5978 3.24151 18.411 2.07265 16.0303 1.5991C13.6496 1.12556 11.182 1.3686 8.93944 2.29749C6.69689 3.22639 4.78015 4.79941 3.43161 6.81765C2.08306 8.83589 1.36328 11.2087 1.36328 13.636C1.36328 15.6651 1.85419 17.5783 2.72692 19.2637L1.36328 25.9087L8.00828 24.5451C9.69373 25.4178 11.6083 25.9087 13.636 25.9087Z" stroke="white" stroke-width="2.04545" stroke-linecap="round" stroke-linejoin="round" fill="none" transform="translate(1.5, 1.5) scale(0.9)"',+ // "@mui/icons-material/AlbumOutlined"+ live: '<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8m0-12.5c-2.49 0-4.5 2.01-4.5 4.5s2.01 4.5 4.5 4.5 4.5-2.01 4.5-4.5-2.01-4.5-4.5-4.5m0 5.5c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1" transform="translate(2, 8.7) scale(0.75)"',+ // "@mui/icons-material/VolumeUp"+ vol: '<path d="M3 9v6h4l5 5V4L7 9zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02M14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77" transform="translate(0, 9) scale(0.75)"',+ // Custom star icon (outline)+ favorite:+ '<path d="M8.69381 1.56975C9.38617 0.609562 10.7995 0.609562 11.4919 1.56975L13.7114 4.64784C13.9253 4.9445 14.2255 5.16569 14.5699 5.28031L18.1427 6.46961C19.2572 6.84061 19.6939 8.20365 19.0073 9.16808L16.8062 12.2597C16.5941 12.5577 16.4794 12.9156 16.4783 13.2831L16.4669 17.0962C16.4634 18.2857 15.32 19.1281 14.2033 18.764L10.6234 17.5966C10.2784 17.4841 9.90729 17.4841 9.56228 17.5966L5.98245 18.764C4.86575 19.1281 3.72231 18.2857 3.71876 17.0962L3.70737 13.2831C3.70628 12.9156 3.5916 12.5577 3.37946 12.2597L1.17839 9.16808C0.491785 8.20365 0.928537 6.84061 2.04305 6.46961L5.61584 5.28031C5.96017 5.16569 6.26041 4.9445 6.47432 4.64784L8.69381 1.56975Z" fill="none" stroke="white" stroke-width="1.7" transform="translate(5.5, 6)"',+ // Custom star icon (filled)+ "favorite-fill":+ '<path d="M8.69381 1.56975C9.38617 0.609562 10.7995 0.609562 11.4919 1.56975L13.7114 4.64784C13.9253 4.9445 14.2255 5.16569 14.5699 5.28031L18.1427 6.46961C19.2572 6.84061 19.6939 8.20365 19.0073 9.16808L16.8062 12.2597C16.5941 12.5577 16.4794 12.9156 16.4783 13.2831L16.4669 17.0962C16.4634 18.2857 15.32 19.1281 14.2033 18.764L10.6234 17.5966C10.2784 17.4841 9.90729 17.4841 9.56228 17.5966L5.98245 18.764C4.86575 19.1281 3.72231 18.2857 3.71876 17.0962L3.70737 13.2831C3.70628 12.9156 3.5916 12.5577 3.37946 12.2597L1.17839 9.16808C0.491785 8.20365 0.928537 6.84061 2.04305 6.46961L5.61584 5.28031C5.96017 5.16569 6.26041 4.9445 6.47432 4.64784L8.69381 1.56975Z" transform="translate(5.5, 6)"',+ // "@mui/icons-material/FileDownloadOutlined"+ download:+ '<path d="M18 15v3H6v-3H4v3c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-3zm-1-4-1.41-1.41L13 12.17V4h-2v8.17L8.41 9.59 7 11l5 5z" transform="translate(0, 4)"',+ // "@mui/icons-material/InfoOutlined"+ info: '<path d="M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8" transform="translate(1, 4.5) scale(0.95)"',+ // "@mui/icons-material/MoreHoriz"+ more: '<path d="M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2" transform="translate(0, 4.5)"',+ // "@mui/icons-material/FullscreenOutlined"+ fullscreen:+ '<path d="M7 14H5v5h5v-2H7zm-2-4h2V7h3V5H5zm12 7h-3v2h5v-5h-2zM14 5v2h3v3h2V5z" transform="translate(0, 4.5)"',+ // "@mui/icons-material/FullscreenExitOutlined"+ "fullscreen-exit":+ '<path d="M5 16h3v3h2v-5H5zm3-8H5v2h5V5H8zm6 11h2v-3h3v-2h-5zm2-11V5h-2v5h5V8z" transform="translate(0, 4.5)"',+};++type IconKeys = Exclude<+ keyof typeof paths,+ "favorite-fill" | "fullscreen-exit"+>;++/**+ * Return an object that can be passed verbatim to the "html" option expected by+ * PhotoSwipe's registerElement function.+ *+ * API docs for registerElement:+ * https://photoswipe.com/adding-ui-elements/#uiregisterelement-api+ *+ * Example:+ *+ * html: {+ * isCustomSVG: true,+ * inner: '<path d="M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8" transform="translate(3.5, 3.5)" id="pswp__icn-info" />',+ * outlineID: "pswp__icn-info",+ * }+ *+ */+export const createPSRegisterElementIconHTML = (name: IconKeys) => ({+ isCustomSVG: true,+ inner:+ name == "favorite"+ ? favoriteInner()+ : name == "fullscreen"+ ? fullscreenInner()+ : `${paths[name]} id="pswp__icn-${name}" />`,+ outlineID: `pswp__icn-${name}`,+});++// Favorite is a special case since it consists of two layers: outline and fill.+const favoriteInner = () => {+ // Main outline (white stroke)+ const outline = `${paths.favorite} id="pswp__icn-favorite" />`;+ // Fill (for favorited state)+ const fill = `${paths["favorite-fill"]} id="pswp__icn-favorite-fill" />`;+ return outline + fill;+};++// Fullscreen is also a special case since it has two states.+const fullscreenInner = () =>+ `${paths.fullscreen} id="pswp__icn-fullscreen" />${paths["fullscreen-exit"]} id="pswp__icn-fullscreen-exit" />`;++/**+ * The path of "@mui/icons-material/Settings" as as string.+ *+ * Assumes `viewBox="0 0 24 24"`.+ */+export const settingsSVGPath = `<path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6"></path>`;++/**+ * The path for the custom heart outline icon.+ *+ * Assumes `viewBox="0 0 30 26"`.+ */+export const heartSVGPath = paths.heart;++/**+ * The path for the custom heart filled icon (green).+ *+ * Assumes `viewBox="0 0 30 26"`.+ */+export const heartFillSVGPath = paths["heart-fill"];++/**+ * The path for the custom comment bubble icon.+ *+ * Assumes `viewBox="0 0 28 28"`.+ */+export const commentSVGPath = paths.comment;diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/photoswipe.ts b/web/apps/albums/vendor/ente-gallery/components/viewer/photoswipe.tsnew file mode 100644index 0000000000..3cda405e47--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/photoswipe.ts@@ -0,0 +1,2174 @@+import log from "ente-base/log";+import type { EnteFile } from "ente-media/file";+import { FileType } from "ente-media/file-type";+import "hls-video-element";+import { t } from "i18next";+import "media-chrome";+import { MediaMuteButton } from "media-chrome";+import "media-chrome/menu";+import { MediaChromeMenu, MediaChromeMenuButton } from "media-chrome/menu";+import PhotoSwipe, { type SlideData } from "photoswipe";+import {+ fileViewerDidClose,+ fileViewerWillOpen,+ forgetExifForItemData,+ forgetItemDataForFileID,+ forgetItemDataForFileIDIfNeeded,+ itemDataForFile,+ updateFileInfoExifIfNeeded,+ type ItemData,+} from "./data-source";+import {+ type FileViewerAnnotatedFile,+ type FileViewerProps,+} from "./FileViewer";+import {+ commentSVGPath,+ createPSRegisterElementIconHTML,+ heartFillSVGPath,+ heartSVGPath,+ settingsSVGPath,+} from "./icons";++export interface FileViewerPhotoSwipeDelegate {+ /**+ * Called to obtain the latest list of files.+ *+ * [Note: Changes to underlying files when file viewer is open]+ *+ * The list of files shown by the viewer might change while the viewer is+ * open. We do not actively refresh the viewer when this happens since that+ * would result in the user's zoom / pan state being lost.+ *+ * However, we always read the latest list via the delegate, so any+ * subsequent user initiated slide navigation (e.g. moving to the next+ * slide) will use the new list.+ */+ getFiles: () => EnteFile[];+ /**+ * Return `true` if the provided file has been marked as a favorite by the+ * user.+ *+ * The toggle favorite button will not be shown for the file if+ * this callback returns `undefined`. Otherwise the return value determines+ * the toggle state of the toggle favorite button for the file.+ */+ isFavorite: (annotatedFile: FileViewerAnnotatedFile) => boolean | undefined;+ /**+ * Return `true` if there is an inflight request to update the favorite+ * status of the file.+ */+ isFavoritePending: (annotatedFile: FileViewerAnnotatedFile) => boolean;+ /**+ * Called when the user activates the toggle favorite action on a file.+ *+ * The toggle favorite button will be disabled for the file until the+ * promise returned by this function returns fulfills.+ *+ * > Note: The caller is expected to handle any errors that occur, and+ * > should not reject for foreseeable failures, otherwise the button will+ * > remain in the disabled state (until the file viewer is closed).+ */+ toggleFavorite: (annotatedFile: FileViewerAnnotatedFile) => Promise<void>;+ /**+ * Return `true` if the provided file has a green_heart reaction from the+ * current user.+ */+ isLiked: (annotatedFile: FileViewerAnnotatedFile) => boolean;+ /**+ * Return the number of comments on the provided file.+ *+ * If the file is viewed from within a collection context, this should+ * return the count of comments in that collection. Otherwise (gallery+ * view), it should return the count from the collection with most comments.+ */+ getCommentCount: (annotatedFile: FileViewerAnnotatedFile) => number;+ /**+ * Return `true` if social buttons (like, comment) should be shown for the+ * given file.+ *+ * This is used for gallery view where the file might belong to a shared+ * collection even though we're not directly viewing that collection.+ */+ shouldShowSocialButtons: (+ annotatedFile: FileViewerAnnotatedFile,+ ) => boolean;+ /**+ * Called when there is a keydown event, and our PhotoSwipe instance wants+ * to know if it should ignore it or handle it.+ *+ * The delegate should return true when, e.g., the file info dialog is+ * being displayed.+ */+ shouldIgnoreKeyboardEvent: () => boolean;+ /**+ * Called when the user triggers a potential action using a keyboard+ * shortcut.+ *+ * The caller does not check if the action is valid in the current context,+ * so the delegate must validate and only then perform the action if it is+ * appropriate.+ */+ performKeyAction: (+ action:+ | "delete"+ | "toggle-archive"+ | "copy"+ | "toggle-fullscreen"+ | "help",+ ) => void;+}++type FileViewerPhotoSwipeOptions = Pick<+ FileViewerProps,+ "initialIndex" | "showFullscreenButton" | "disableEscapeClose"+> & {+ /**+ * `true` if we're running in the context of a logged in user, and so+ * various actions that modify the file should be shown.+ *+ * This is the static variant of various per file annotations that control+ * various modifications. If this is not `true`, then various actions like+ * favorite, delete etc are never shown. If this is `true`, then their+ * visibility depends on the corresponding annotation.+ *+ * For example, the favorite action is shown only if both this and the+ * {@link showFavorite} file annotation are true.+ */+ haveUser: boolean;+ /**+ * `true` when viewing a public album.+ */+ isPublicAlbum: boolean;+ /**+ * `true` if the like and comment action buttons should be shown.+ *+ * These buttons are shown only when viewing files in a shared album+ * (incoming or outgoing) or in a public album.+ */+ showSocialButtons: boolean;+ /**+ * `true` if comments are enabled on the public link.+ *+ * When `false`, the comment button will be hidden even if+ * {@link showSocialButtons} is `true`.+ */+ enableComment: boolean;+ /**+ * Dynamic callbacks.+ *+ * The extra level of indirection allows these to be updated without+ * recreating us.+ */+ delegate: FileViewerPhotoSwipeDelegate;+ /**+ * Called when the file viewer is closed.+ */+ onClose: () => void;+ /**+ * Called whenever the slide is initially displayed or changes, to obtain+ * various derived data for the file that is about to be displayed.+ *+ * @param file The current {@link EnteFile}. This is the same value as the+ * corresponding value in the current index of {@link getFiles} returned by+ * the delegate.+ *+ * @param itemData This is the best currently available {@link ItemData}+ * corresponding to the current file.+ */+ onAnnotate: (file: EnteFile, itemData: ItemData) => FileViewerAnnotatedFile;+ /**+ * Called when the user activates the info action on a file.+ */+ onViewInfo: (annotatedFile: FileViewerAnnotatedFile) => void;+ /**+ * Called when the user activates the comments action on a file.+ */+ onViewComments: () => void;+ /**+ * Called when the user activates the likes action on a file (right-click on heart).+ */+ onViewLikes: () => void;+ /**+ * Called when the user clicks the like button (left-click on heart).+ */+ onLikeClick: () => void;+ /**+ * Called when the user activates the download action on a file.+ */+ onDownload: (annotatedFile: FileViewerAnnotatedFile) => void;+ /**+ * Called when the user activates the more action.+ *+ * @param buttonElement The more button DOM element.+ */+ onMore: (buttonElement: HTMLElement) => void;+};++/**+ * The ID that is used by the "more" action button (if one is being displayed).+ *+ * @see also {@link moreMenuID}.+ */+export const moreButtonID = "ente-pswp-more-button";++/**+ * The ID this is expected to be used by the more menu that is shown in response+ * to the more action button being activated.+ *+ * @see also {@link moreButtonID}.+ */+export const moreMenuID = "ente-pswp-more-menu";++/**+ * A wrapper over {@link PhotoSwipe} to tailor its interface for use by our file+ * viewer.+ *+ * This is somewhat akin to the {@link PhotoSwipeLightbox}, except this doesn't+ * have any UI of its own, it only modifies PhotoSwipe Core's behaviour.+ *+ * [Note: PhotoSwipe]+ *+ * PhotoSwipe is a library that behaves similarly to the OG "lightbox" image+ * gallery JavaScript component from the middle ages.+ *+ * We don't need the lightbox functionality since we already have our own+ * thumbnail list (the "gallery"), so we only use the "Core" PhotoSwipe module+ * as our image viewer component.+ *+ * When the user clicks on one of the thumbnails in our gallery, we make the+ * root PhotoSwipe component visible. Within the DOM this is a dialog-like div+ * that takes up the entire viewport, shows the image, various controls etc.+ *+ * Documentation: https://photoswipe.com/.+ */+export class FileViewerPhotoSwipe {+ /**+ * The PhotoSwipe instance which we wrap.+ */+ private pswp: PhotoSwipe;++ constructor({+ initialIndex,+ haveUser,+ isPublicAlbum,+ showSocialButtons,+ enableComment,+ showFullscreenButton,+ disableEscapeClose,+ delegate,+ onClose,+ onAnnotate,+ onViewInfo,+ onViewComments,+ onViewLikes,+ onLikeClick,+ onDownload,+ onMore,+ }: FileViewerPhotoSwipeOptions) {+ const pswp = new PhotoSwipe({+ // Opaque background.+ bgOpacity: 1,+ // The default, "zoom", cannot be used since we're not animating+ // from a thumbnail, so effectively "fade" is in effect anyway. Set+ // it still, just for and explicitness and documentation.+ showHideAnimationType: "fade",+ // The default imageClickAction is "zoom-or-close". When the image+ // is small and cannot be zoomed into further (which is common when+ // just the thumbnail has been loaded), this causes PhotoSwipe to+ // close. Disable this behaviour.+ clickToCloseNonZoomable: false,+ // The default `bgClickAction` is "close", but it is not always+ // apparent where the background is and where the controls are,+ // since everything is black, and so accidentally closing PhotoSwipe+ // is easy.+ //+ // Disable this behaviour, instead repurposing this action to behave+ // the same as the `tapAction` ("tap on PhotoSwipe viewport+ // content") and toggle the visibility of UI controls (We also have+ // auto hide based on mouse activity, but that would not have any+ // effect on touch devices)+ bgClickAction: "toggle-controls",+ // In single-file public viewer mode we keep Escape for nested UI+ // interactions while preventing accidental viewer closure.+ escKey: !disableEscapeClose,+ // At least on macOS, manual zooming with the trackpad is very+ // cumbersome (possibly because of the small multiplier in the+ // PhotoSwipe source, but I'm not sure). The other option to do a+ // manual zoom is to scroll (e.g. with the trackpad) but with the+ // CTRL key pressed, however on macOS this invokes the system zoom+ // if enabled in accessibility settings.+ //+ // Taking a step back though, the PhotoSwipe viewport is fixed, so+ // we can just directly map wheel / trackpad scrolls to zooming.+ wheelToZoom: true,+ // Chrome yells about incorrectly mixing focus and aria-hidden if we+ // leave this at the default (true) and then swipe between slides+ // fast, or show MUI drawers etc.+ //+ // See: [Note: Workarounds for unactionable ARIA warnings], but time+ // with a different library.+ trapFocus: false,+ // Set the index within files that we should open to. Subsequent+ // updates to the index will be tracked by PhotoSwipe internally.+ index: initialIndex,+ // Use "pswp-ente" as the main class name. Note that this is not+ // necessary, we could've target the "pswp" class too in our CSS+ // since we only have a single PhotoSwipe instance.+ mainClass: isPublicAlbum+ ? "pswp-ente pswp-ente-public-album"+ : "pswp-ente",+ closeTitle: t("close"),+ zoomTitle: t("zoom"),+ arrowPrevTitle: t("previous"),+ arrowNextTitle: t("next"),+ errorMsg: t("unpreviewable_file_message"),+ });++ this.pswp = pswp;++ // Various helper routines to obtain the file at `currIndex`.++ /**+ * Derived data about the currently displayed file.+ *+ * This is recomputed on-demand (by using the {@link onAnnotate}+ * callback) each time the slide changes, and cached until the next+ * slide change.+ *+ * Instead of accessing this property directly, code should funnel+ * through the `currentAnnotatedFile` helper function.+ */+ let _currentAnnotatedFile: FileViewerAnnotatedFile | undefined;++ /**+ * Non-null assert and casted the given {@link SlideData} as+ * {@link ItemData}.+ *+ * PhotoSwipe types specify currSlide.data to be of type `SlideData`,+ * but in our case these are {@link ItemData} instances which the type+ * doesn't reflect. So this is a method to consolidate the cast and+ * non-null assertion (the PhotoSwipe dialog shouldn't be visible if+ * there are no slides left).+ */+ const asItemData = (slideData: SlideData | undefined) =>+ slideData! as ItemData;++ const currSlideData = () => asItemData(pswp.currSlide?.data);++ const currentFile = () => delegate.getFiles()[pswp.currIndex]!;++ const currentAnnotatedFile = (): FileViewerAnnotatedFile => {+ const file = currentFile();+ let annotatedFile = _currentAnnotatedFile;+ if (+ !annotatedFile ||+ annotatedFile.file.id != file.id ||+ annotatedFile.file.updationTime != file.updationTime+ ) {+ // Guard: slide data can be unavailable during state transitions.+ // If unavailable, we keep using the cached annotatedFile.+ const slideData = pswp.currSlide?.data as ItemData | undefined;+ if (slideData) {+ annotatedFile = onAnnotate(file, slideData);+ _currentAnnotatedFile = annotatedFile;+ }+ }+ // By design, this should never be undefined after the initial slide+ // is shown. Use non-null assertion to maintain API contract.+ return annotatedFile!;+ };++ const currentFileAnnotation = () => currentAnnotatedFile().annotation;++ /**+ * [Note: Updates to the files prop for FileViewer]+ *+ * This function is called when the list of underlying files changes.+ *+ * These updates can be possibly spurious, since the list changes on+ * identity and not deep equality. Or they might be real but affect a+ * file that is not currently being shown.+ *+ * Apart from those cases, there are real updates that effect us:+ *+ * - If the file that was previously being shown is no longer being+ * shown (e.g. it was deleted, or if the marked it archived in a+ * context like "All" where archived files are not being shown), move+ * to the next slide if possible, or close the viewer otherwise (e.g.+ * user deleted the last one).+ *+ * - If the file that was previously being shown has moved to a new+ * index (e.g. user changed the date in the file info panel), go to+ * that new index.+ *+ * - If the file is still the same but the underlying file's updation+ * time has changed (e.g. the user changed the name of the file in the+ * file info panel), refresh the annotated file data cached by the+ * viewer.+ *+ * When handling these cases, the intent is to minimize the need to call+ * `refreshSlideContent` as much as possible since that would cause the+ * zoom and pan state to be reset too.+ */+ this.refreshSlideOnFilesUpdateIfNeeded = () => {+ const prevFileID = _currentAnnotatedFile?.file.id;+ if (!prevFileID) return;++ const files = delegate.getFiles();+ const newFileCount = files.length;++ const newFile = files[pswp.currIndex];+ if (!newFile || newFile.id != prevFileID) {+ // File is either no longer there, or has moved.+ //+ // In either case, after repositioning ourselves to the new+ // index we also need to refresh the next (or both) neighbours.+ //+ // E.g. assume item at index 3 was removed. After refreshing,+ // the contents of the item previously at index 4, and now at+ // index 3, would be displayed. But the preloaded slide next to+ // us (showing item at index 4) would already be displaying the+ // same item, so that also needs to be refreshed to displaying+ // the item previously at index 5 (now at index 4).++ const newIndex = files.findIndex(({ id }) => id == prevFileID);++ if (newIndex == -1) {+ // File is no longer present.+ const i = pswp.currIndex;++ if (i >= newFileCount) {+ // If the last slide was removed, take one step back+ // first (the code that calls us ensures that we don't+ // get called if there are no more slides left).+ this.pswp.prev();+ }++ // Refresh the slide at current index (the erstwhile+ // neighbour), and refresh its subsequent neighbour (to get+ // the new neighbour).+ pswp.refreshSlideContent(i);+ pswp.refreshSlideContent(i + 1 == newFileCount ? 0 : i + 1);+ } else {+ // File has moved. Go to new index, and also refresh both+ // its neighbours.+ const i = newIndex;++ pswp.goTo(i);+ pswp.refreshSlideContent(i == 0 ? newFileCount - 1 : i - 1);+ pswp.refreshSlideContent(i + 1 == newFileCount ? 0 : i + 1);+ }+ } else {+ // Calling `currentAnnotatedFile` has the side effect of+ // refreshing the cached annotated file if the `updationTime`+ // has changed.+ currentAnnotatedFile();+ }+ };++ /**+ * File (ID)s for which we should render the original, non-streamable,+ * video even if a HLS playlist is available.+ */+ const originalVideoFileIDs = new Set<number>();++ const intendedVideoQualityForFileID = (fileID: number) =>+ originalVideoFileIDs.has(fileID) ? "original" : "auto";++ // Provide data about slides to PhotoSwipe via callbacks+ // https://photoswipe.com/data-sources/#dynamically-generated-data++ pswp.addFilter("numItems", () => delegate.getFiles().length);++ pswp.addFilter("itemData", (_, index) => {+ const files = delegate.getFiles();+ const file = files[index]!;++ const videoQuality = intendedVideoQualityForFileID(file.id);++ const itemData = itemDataForFile(file, { videoQuality }, () => {+ // When we get updated item data,+ // 1. Clear cached data.+ _currentAnnotatedFile = undefined;+ // 2. Request a refresh.+ pswp.refreshSlideContent(index);+ });++ if (itemData.fileType == FileType.video) {+ const { videoPlaylistURL, videoURL } = itemData;+ if (videoPlaylistURL && videoQuality == "auto") {+ const mcID = `ente-mc-hls-${file.id}`;+ return {+ ...itemData,+ html: hlsVideoHTML(videoPlaylistURL, mcID),+ mediaControllerID: mcID,+ };+ } else if (videoURL) {+ const mcID = `ente-mc-orig-${file.id}`;+ return {+ ...itemData,+ html: videoHTML(videoURL, mcID),+ mediaControllerID: mcID,+ };+ }+ }++ return itemData;+ });++ pswp.addFilter("isContentLoading", (isLoading, content) => {+ return asItemData(content.data).isContentLoading ?? isLoading;+ });++ pswp.addFilter("isContentZoomable", (isZoomable, content) => {+ return asItemData(content.data).isContentZoomable ?? isZoomable;+ });++ /**+ * File IDs for which we've already done initial live photo playback+ * attempts in the current session (invocation of file viewer).+ *+ * This not only allows us to skip triggering initial playback when+ * coming back to the same slide again (a behavioural choice), it also+ * allows us to skip retriggering playback when decoding of the image+ * component completes (a functional need).+ */+ const livePhotoInitialVisitedFileIDs = new Set<number>();++ /**+ * Last state of the live photo playback on initial display.+ */+ let livePhotoPlayInitial = true;++ /**+ * Set to the event listener that will be called at the end of the+ * initial playback of a live photo on the currently displayed slide.+ *+ * This will be present only during the initial playback (it will be+ * cleared when initial playback completes), and can also thus be used+ * as a pseudo `isPlayingLivePhotoInitial`.+ */+ let livePhotoPlayInitialEndedEvent:+ | { listener: () => void; video: HTMLVideoElement }+ | undefined;++ /**+ * Last state of the live photo muted toggle.+ */+ let livePhotoMute = true;++ /**+ * The live photo playback toggle DOM button element.+ */+ let livePhotoPlayButtonElement: HTMLElement | undefined;++ /**+ * The live photo muted toggle DOM button element.+ */+ let livePhotoMuteButtonElement: HTMLElement | undefined;++ /**+ * Update the state of the given {@link videoElement} and the+ * {@link livePhotoPlayButtonElement} to reflect+ * {@link livePhotoPlayInitial}.+ *+ * [Note: Live photo playback]+ *+ * 1. When opening a live photo, play it once unless+ * {@link livePhotoPlayInitial} is disabled. This is the behaviour+ * controlled by the {@link livePhotoUpdatePlayInitial} function.+ *+ * 2. If the user toggles playback of during the initial video playback,+ * then remember their choice for the current session (invocation of+ * file viewer) by disabling {@link livePhotoPlayInitial}.+ *+ * 3. Also keep track of which files have already been initial played in+ * the current session (using {@link livePhotoInitialVisitedFileIDs}).+ *+ * 3. Post initial playback, user can play the video again in a loop by+ * activating the {@link livePhotoPlayButtonElement}, which triggers+ * the {@link livePhotoUpdatePlayToggle} function (and also resets+ * {@link livePhotoPlayInitial}).+ */+ const livePhotoUpdatePlayInitial = (video: HTMLVideoElement) => {+ livePhotoUpdateUIState(video);++ // Ignore if we've already visited this file.+ const currFileID = currSlideData().fileID;+ if (livePhotoInitialVisitedFileIDs.has(currFileID)) {+ return;+ }++ // Otherwise mark it as visited.+ livePhotoInitialVisitedFileIDs.add(currFileID);++ // Remove any loop attributes we might've inherited from a+ // previously displayed live photos elements on the current slide.+ video.removeAttribute("loop");++ // Clear any other initial playback listeners.+ if (livePhotoPlayInitialEndedEvent) {+ const { video, listener } = livePhotoPlayInitialEndedEvent;+ video.removeEventListener("ended", listener);+ livePhotoPlayInitialEndedEvent = undefined;+ }++ if (livePhotoPlayInitial) {+ // Initial playback is enabled - Play the video once.+ //+ // There are a few playback cases (initial, resumed, adjacent+ // slide with a reused video element, new slide with a new video+ // element). Always start at the beginning in all cases for user+ // the feel the app is responding consistently.+ video.currentTime = 0;+ void abortablePlayVideo(video);+ video.style.display = "initial";+ const listener = () => {+ livePhotoPlayInitialEndedEvent = undefined;+ livePhotoUpdateUIState(video);+ };+ livePhotoPlayInitialEndedEvent = { video, listener };+ video.addEventListener("ended", listener, { once: true });+ } else {+ video.pause();+ }++ livePhotoUpdateUIState(video);+ };++ const livePhotoUpdateUIState = (video: HTMLVideoElement) => {+ const button = livePhotoPlayButtonElement;+ if (button) showIf(button, true);++ if (video.paused || video.ended) {+ button?.classList.add("pswp-ente-off");+ video.style.display = "none";+ } else {+ button?.classList.remove("pswp-ente-off");+ video.style.display = "initial";+ }+ };++ /**+ * See: [Note: Live photo playback]+ *+ * This function handles the playback toggled via an explicit user+ * action (button activation or keyboard shortcut).+ */+ const livePhotoUpdatePlayToggle = (video: HTMLVideoElement) => {+ if (video.paused || video.ended) {+ // Add the loop attribute.+ video.setAttribute("loop", "");++ // Take an explicit playback trigger as a signal to reset the+ // initial playback flag.+ //+ // This is the only way for the user to reset the initial+ // playback state (short of repopening the file viewer).+ livePhotoPlayInitial = true;++ video.currentTime = 0;+ void abortablePlayVideo(video);+ } else {+ // Remove the loop attribute (not necessarily needed because we+ // remove it on slide change too, but good to clean up after+ // ourselves).+ video.removeAttribute("loop");++ // If we're in the middle of the initial playback, remember the+ // user's choice to disable autoplay.+ if (livePhotoPlayInitialEndedEvent) {+ livePhotoPlayInitial = false;++ // And reset the event handler.+ const { video, listener } = livePhotoPlayInitialEndedEvent;+ video.removeEventListener("ended", listener);+ livePhotoPlayInitialEndedEvent = undefined;+ }++ video.pause();+ }++ livePhotoUpdateUIState(video);+ };++ /**+ * A wrapper over video.play that prevents Chrome from spamming the+ * console with errors about interrupted plays when scrolling through+ * files fast by keeping arrow keys pressed, or when the slide is reloaded.+ */+ const abortablePlayVideo = async (videoElement: HTMLVideoElement) => {+ try {+ await videoElement.play();+ } catch (e) {+ // Known message strings prefixes.+ // - "The play() request was interrupted by a call to pause()."+ // - "The play() request was interrupted because the media was removed from the document."++ if (+ e instanceof Error &&+ e.name == "AbortError" &&+ e.message.startsWith("The play() request was interrupted")+ ) {+ // Ignore.+ } else {+ throw e;+ }+ }+ };++ /**+ * Update the state of the given {@link videoElement} and the+ * {@link livePhotoMuteButtonElement} to reflect {@link livePhotoMute}.+ */+ const livePhotoUpdateMute = (video: HTMLVideoElement) => {+ const button = livePhotoMuteButtonElement;+ if (button) showIf(button, true);++ if (livePhotoMute) {+ button?.classList.add("pswp-ente-off");+ video.muted = true;+ } else {+ button?.classList.remove("pswp-ente-off");+ video.muted = false;+ }+ };++ /**+ * Toggle the playback, if possible, of a live photo that's being shown+ * on the current slide.+ */+ const livePhotoTogglePlayIfPossible = () => {+ const buttonElement = livePhotoPlayButtonElement;+ const video = livePhotoVideoOnSlide(pswp.currSlide);+ if (!buttonElement || !video) return;++ livePhotoUpdatePlayToggle(video);+ };++ /**+ * Toggle the muted status, if possible, of a live photo that's being shown+ * on the current slide.+ */+ const livePhotoToggleMuteIfPossible = () => {+ const buttonElement = livePhotoMuteButtonElement;+ const video = livePhotoVideoOnSlide(pswp.currSlide);+ if (!buttonElement || !video) return;++ livePhotoMute = !livePhotoMute;+ livePhotoUpdateMute(video);+ };++ /**+ * The DOM element housing the media-control-bar and friends.+ */+ let mediaControlsContainerElement: HTMLElement | undefined;++ /**+ * True if the next change to the videoQuality is initiated by us. This+ * is used by the "change" event listener to ignore these events,+ * avoiding a cyclic update loop.+ */+ let shouldIgnoreNextVideoQualityChange = false;++ /**+ * Update the media controls for the given {@link itemData}.+ *+ * - Show controls only for videos.+ * - Keep controls visible but disabled while video playback is loading.+ * - Link controls to the media controller once available.+ */+ const updateVideoControlsAndPlayback = (itemData: ItemData) => {+ // For reasons possibly related to the 1 tick wait in the hls-video+ // implementation (`await Promise.resolve()`), the association+ // between media-controller and media-control-bar doesn't get+ // established on the first slide if we reopen the file viewer.+ //+ // See also: https://github.com/muxinc/media-chrome/issues/940+ //+ // As a workaround, defer the association to the next tick.+ setTimeout(() => _updateVideoControlsAndPlayback(itemData), 0);+ };++ /**+ * Handle click on the media-fullscreen-button by intercepting it and+ * using document-level fullscreen instead.+ *+ * The default behavior of media-fullscreen-button puts only the+ * media-controller element into fullscreen, which hides the PhotoSwipe+ * UI controls (close, info, navigation, etc.). By using document-level+ * fullscreen on document.body, all controls remain accessible.+ *+ * In fullscreen mode, we hide the top navigation bar and only show the+ * video timeline controls at the bottom (with auto-hide behavior).+ */+ const handleFullscreenButtonClick = (e: Event) => {+ e.stopPropagation();+ e.preventDefault();+ if (document.fullscreenElement) {+ void document.exitFullscreen();+ } else {+ void document.body.requestFullscreen();+ // Hide top navigation bar in fullscreen, show only video controls+ pswp.element?.classList.add("pswp--video-fullscreen");+ // Track mouse movement to show controls when near bottom+ document.addEventListener(+ "mousemove",+ handleMouseMoveInFullscreen,+ );+ }+ };++ /**+ * Update UI state when fullscreen mode changes (e.g., user presses Esc).+ */+ const handleFullscreenChange = () => {+ if (!document.fullscreenElement) {+ // Exiting fullscreen - restore the top navigation bar+ pswp.element?.classList.remove("pswp--video-fullscreen");+ pswp.element?.classList.remove("pswp--controls-visible");+ document.removeEventListener(+ "mousemove",+ handleMouseMoveInFullscreen,+ );+ }+ };++ /**+ * Timer ID for hiding controls after mouse inactivity in fullscreen.+ */+ let hideControlsTimer: ReturnType<typeof setTimeout> | undefined;++ /**+ * Show video controls on mouse movement, hide after inactivity.+ */+ const handleMouseMoveInFullscreen = () => {+ pswp.element?.classList.add("pswp--controls-visible");++ // Clear any pending hide timer+ if (hideControlsTimer) {+ clearTimeout(hideControlsTimer);+ }++ // Hide controls after inactivity+ hideControlsTimer = setTimeout(() => {+ pswp.element?.classList.remove("pswp--controls-visible");+ hideControlsTimer = undefined;+ }, 2000);+ };++ const _updateVideoControlsAndPlayback = (itemData: ItemData) => {+ const container = mediaControlsContainerElement;+ const showVideoControls =+ itemData.fileType == FileType.video && !itemData.fetchFailed;+ const areVideoControlsDisabled =+ showVideoControls &&+ (!!itemData.isContentLoading || !itemData.mediaControllerID);+ container?.classList.toggle(+ "pswp__media-controls--visible",+ showVideoControls,+ );+ container?.classList.toggle(+ "pswp__media-controls--disabled",+ areVideoControlsDisabled,+ );++ const controls =+ container?.querySelectorAll(+ "media-control-bar, media-playback-rate-menu",+ ) ?? [];+ for (const control of controls) {+ const { mediaControllerID } = itemData;+ if (mediaControllerID) {+ control.setAttribute("mediacontroller", mediaControllerID);+ } else {+ control.removeAttribute("mediacontroller");+ }+ }++ const qualityMenu = container?.querySelector("#ente-quality-menu");+ if (qualityMenu instanceof MediaChromeMenu) {+ const { videoPlaylistURL, fileID } = itemData;++ // Hide the auto option, keeping track of if we did indeed+ // change something.+ const item = qualityMenu.radioGroupItems[0]!;+ let didChangeHide = false;+ if (item.hidden && videoPlaylistURL) {+ didChangeHide = true;+ item.hidden = false;+ } else if (!item.hidden && !videoPlaylistURL) {+ didChangeHide = true;+ item.hidden = true;+ }++ const value =+ intendedVideoQualityForFileID(fileID) == "auto" &&+ videoPlaylistURL+ ? t("auto")+ : t("original");+ // Check first to avoid spurious updates.+ if (qualityMenu.value != value) {+ // Set a flag to avoid infinite update loop.+ shouldIgnoreNextVideoQualityChange = true;+ // Setting the value will close it.+ qualityMenu.value = value;+ } else {+ // Close it ourselves otherwise if we changed the menu.+ if (didChangeHide) {+ closeMediaChromeSettingsMenuIfOpen();+ }+ }+ }++ // Autoplay (unless the video has ended).+ const video = videoVideoEl;+ if (video?.paused && !video.ended) void video.play();+ };++ /**+ * Toggle the settings menu by activating the menu button.+ *+ * This should be more robust than us trying to reverse engineer the+ * internal media chrome logic to open and close the menu. However, the+ * caveat is that this will only work for closing the menu (our goal)+ * if the menu is already open.+ */+ const toggleMediaChromeSettingsMenu = () => {+ const menuButton = document.querySelector(+ "media-settings-menu-button",+ );+ if (menuButton instanceof MediaChromeMenuButton) {+ menuButton.handleClick();++ // See: [Note: Media chrome focus workaround]+ //+ // Whatever media chrome is doing internally, it requires us to+ // drop the focus multiple times (Removing either of these calls+ // is not enough).+ const blurAllFocused = () =>+ document+ .querySelectorAll(":focus")+ .forEach((e) => e instanceof HTMLElement && e.blur());++ blurAllFocused();+ setTimeout(blurAllFocused, 0);+ }+ };++ const closeMediaChromeSettingsMenuIfOpen = () => {+ if (document.querySelector("media-settings-menu:not([hidden])"))+ toggleMediaChromeSettingsMenu();+ };++ pswp.on("contentAppend", (e) => {+ // PhotoSwipe emits stale contentAppend events. e.g. when changing+ // the video quality, we'll first get "contentAppend" (and "change")+ // with the latest item data, but then later PhotoSwipe will call+ // "contentAppend" again with stale data.+ //+ // To ignore these, we check the `hasSlide` attribute. I'm not sure+ // if this is a foolproof workaround.+ //+ // See also https://github.com/dimsemenov/PhotoSwipe/issues/2045.+ if (!e.content.hasSlide) {+ log.debug(() => ["Ignoring stale contentAppend", e]);+ return;+ }++ const { fileID, fileType, videoURL } = asItemData(e.content.data);++ // For the initial slide, "contentAppend" will get called after the+ // "change" event, so we need to wire up the controls, or hide them,+ // for the initial slide here also (in addition to in "change").+ if (currSlideData().fileID == fileID) {+ updateVideoControlsAndPlayback(currSlideData());+ }++ if (fileType != FileType.livePhoto || !videoURL) {+ // Not a live photo, or its video hasn't loaded yet.+ return;+ }++ // Rest of this function deals with live photos.++ // This slide is displaying a live photo. Append a video element to+ // show its video part.++ const img = e.content.element!;+ const video = createElementFromHTMLString(+ livePhotoVideoHTML(videoURL),+ ) as HTMLVideoElement;+ const container = e.content.slide!.container;+ container.style = "position: relative";+ container.appendChild(video);+ // Set z-index to 1 to keep it on top, and set pointer-events to+ // none to pass the clicks through.+ video.style =+ "position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;";++ // Size it to the underlying image.+ video.style.width = img.style.width;+ video.style.height = img.style.height;++ // "contentAppend" can get called both before, or after, "change",+ // and we need to handle both potential sequences for the initial+ // display of the video. Here we handle the case where "change" has+ // already been called, but now "contentAppend" is happening.++ if (currSlideData().fileID == fileID) {+ livePhotoUpdatePlayInitial(video);+ livePhotoUpdateMute(video);+ }+ });++ /**+ * Helper function to extract the video element from a slide that is+ * showing a live photo.+ */+ const livePhotoVideoOnSlide = (slide: typeof pswp.currSlide) =>+ asItemData(slide?.data).fileType == FileType.livePhoto+ ? slide?.container.getElementsByTagName("video")[0]+ : undefined;++ pswp.on("imageSizeChange", ({ content, width, height }) => {+ const video = livePhotoVideoOnSlide(content.slide);+ if (!video) {+ // We might have been called before "contentAppend".+ return;+ }++ // This slide is displaying a live photo. Resize the size of the+ // video element to match that of the image.++ video.style.width = `${width}px`;+ video.style.height = `${height}px`;+ });++ /**+ * Get the video element, if any, that is a descendant of the given HTML+ * element.+ *+ * While the return type is an {@link HTMLVideoElement}, the result can+ * also be an instance of a media-chrome `CustomVideoElement`,+ * specifically a {@link HlsVideoElement}.+ * https://github.com/muxinc/media-elements/blob/main/packages/hls-video-element/hls-video-element.js+ *+ * The media-chrome `CustomVideoElement`s provide the same API as the+ * browser's built-in {@link HTMLVideoElement}s, so we can use the same+ * methods on them.+ *+ * For ergonomic use at call sites, it accepts an optional.+ */+ const queryVideoElement = (element: HTMLElement | undefined) =>+ element?.querySelector<HTMLVideoElement>("video, hls-video");++ pswp.on("contentDeactivate", (e) => {+ // PhotoSwipe invokes this event when moving away from a slide.+ //+ // However it might not have an effect until we move out of preload+ // range. See: [Note: File viewer preloading and contentDeactivate].++ const fileID = asItemData(e.content.data).fileID;+ if (fileID) forgetItemDataForFileIDIfNeeded(fileID);++ // Pause the video element, if any, when we move away from the+ // slide.+ const video = queryVideoElement(e.content.slide?.container);+ video?.pause();+ });++ pswp.on(+ "loadComplete",+ (e) => void updateFileInfoExifIfNeeded(asItemData(e.content.data)),+ );++ pswp.on(+ "change",+ () => void updateFileInfoExifIfNeeded(currSlideData()),+ );++ pswp.on("contentDestroy", (e) =>+ forgetExifForItemData(asItemData(e.content.data)),+ );++ /**+ * If the current slide is showing a video, then the DOM video element+ * showing that video.+ *+ * See also {@link queryVideoElement}.+ */+ let videoVideoEl: HTMLVideoElement | undefined;++ /**+ * The epoch time (milliseconds) when the latest slide change happened.+ */+ let lastSlideChangeEpochMilli = Date.now();++ pswp.on("change", () => {+ const itemData = currSlideData();++ // For each slide ("item holder"), mirror the "aria-hidden" state+ // into the "inert" property so that keyboard navigation via tabs+ // does not cycle through to the hidden slides (e.g. if the hidden+ // slide is a video element with browser provided controls).++ pswp.mainScroll.itemHolders.forEach(({ el }) => {+ if (el.getAttribute("aria-hidden") == "true") {+ el.setAttribute("inert", "");+ } else {+ el.removeAttribute("inert");+ }+ });++ if (itemData.fileType == FileType.video) {+ // We use content.element instead of container here because+ // pswp.currSlide.container.getElementsByTagName("video") does+ // not work for the first slide when we reach here during the+ // initial "change".+ //+ // It works subsequently, which is why, e.g., we can use it to+ // pause the video in "contentDeactivate".+ const contentElement = pswp.currSlide?.content.element;+ videoVideoEl = queryVideoElement(contentElement) ?? undefined;+ } else {+ videoVideoEl = undefined;+ }++ lastSlideChangeEpochMilli = Date.now();+ });++ /**+ * Toggle the playback, if possible, of the video that's being shown on+ * the current slide.+ */+ const videoTogglePlayIfPossible = () => {+ const video = videoVideoEl;+ if (!video) return;++ if (video.paused || video.ended) {+ void video.play();+ } else {+ video.pause();+ }+ };++ /**+ * Toggle the muted status, if possible, of the video that's being shown on+ * the current slide.+ */+ const videoToggleMuteIfPossible = () => {+ // Go via the media chrome mute button when muting, because+ // otherwise the local storage that the media chrome internally+ // manages ('media-chrome-pref-muted' which can be 'true' or+ // 'false') gets out of sync with the playback state.+ const muteButton = document.querySelector("media-mute-button");+ if (muteButton instanceof MediaMuteButton) muteButton.handleClick();+ };++ const handleViewInfo = () => onViewInfo(currentAnnotatedFile());++ let favoriteButtonElement: HTMLButtonElement | undefined;++ const toggleFavorite = () =>+ delegate.toggleFavorite(currentAnnotatedFile());++ const updateFavoriteButtonIfNeeded = () => {+ const favoriteIconFill = document.getElementById(+ "pswp__icn-favorite-fill",+ );+ if (!favoriteIconFill) {+ // Early return if we're not currently being shown, to implement+ // the "IfNeeded" semantics.+ return;+ }++ const button = favoriteButtonElement!;++ const af = currentAnnotatedFile();+ const showFavorite = af.annotation.showFavorite;+ showIf(button, showFavorite);++ if (!showFavorite) {+ // Nothing more to do.+ return;+ }++ // Update the button interactivity based on pending requests.+ button.disabled = delegate.isFavoritePending(af);++ // Update the fill visibility based on the favorite status.+ showIf(favoriteIconFill, !!delegate.isFavorite(af));+ };++ this.refreshCurrentSlideFavoriteButtonIfNeeded =+ updateFavoriteButtonIfNeeded;++ const updateLikeButtonIfNeeded = () => {+ const heartIconFill = document.getElementById(+ "pswp__icn-heart-fill",+ );+ const heartIconOutline = document.getElementById("pswp__icn-heart");+ if (!heartIconFill || !heartIconOutline) {+ // Early return if we're not currently being shown.+ return;+ }++ const af = currentAnnotatedFile();+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition+ if (!af) return; // Guard against undefined during initialization+ const isLiked = delegate.isLiked(af);++ // Show fill (green) if liked, show outline (white) if not liked+ showIf(heartIconFill, isLiked);+ showIf(heartIconOutline, !isLiked);+ };++ this.refreshCurrentSlideLikeButtonIfNeeded = updateLikeButtonIfNeeded;++ const updateCommentCountIfNeeded = () => {+ const commentCountElement = document.querySelector<HTMLElement>(+ ".pswp__comment-count",+ );+ if (!commentCountElement) {+ // Early return if we're not currently being shown.+ return;+ }++ const af = currentAnnotatedFile();+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition+ if (!af) return; // Guard against undefined during initialization+ const count = delegate.getCommentCount(af);+ commentCountElement.textContent = String(count);+ };++ this.refreshCurrentSlideCommentCountIfNeeded =+ updateCommentCountIfNeeded;++ const handleToggleFavorite = () => void toggleFavorite();++ const handleToggleFavoriteIfEnabled = () => {+ if (+ haveUser &&+ currentAnnotatedFile().annotation.showFavorite &&+ !delegate.isFavoritePending(currentAnnotatedFile())+ ) {+ handleToggleFavorite();+ }+ };++ const handleDownload = () => onDownload(currentAnnotatedFile());++ const handleDownloadIfEnabled = () => {+ if (currentFileAnnotation().showDownload) handleDownload();+ };++ const onVideoQualityChange = () => {+ if (shouldIgnoreNextVideoQualityChange) {+ // Ignore changes that we ourselves initiated on slide change.+ shouldIgnoreNextVideoQualityChange = false;+ return;+ }++ // The menu is open at this point, so toggling it is equivalent to+ // closing it.+ toggleMediaChromeSettingsMenu();++ // Currently there are only two entries in the video quality menu,+ // and the callback only gets invoked if the value gets changed from+ // the current value. So we can assume toggle semantics when+ // implementing the logic below.++ const fileID = currentAnnotatedFile().file.id;+ forgetItemDataForFileID(fileID);+ if (originalVideoFileIDs.has(fileID)) {+ originalVideoFileIDs.delete(fileID);+ } else {+ originalVideoFileIDs.add(fileID);+ }++ // Refresh the slide so that the video is fetched afresh, but using+ // the updated `originalVideoFileIDs` value for it.+ pswp.refreshSlideContent(pswp.currIndex);+ };++ const showIf = (element: HTMLElement, condition: boolean) =>+ condition+ ? element.classList.remove("pswp__hidden")+ : element.classList.add("pswp__hidden");++ // Add our custom UI elements to inside the PhotoSwipe dialog.+ //+ // API docs for registerElement:+ // https://photoswipe.com/adding-ui-elements/#uiregisterelement-api+ //+ // The "order" prop is used to position items. Some landmarks:+ // - counter: 5+ // - zoom: 6 (default is 10)+ // - preloader: 10 (default is 7)+ // - close: 20+ pswp.on("uiRegister", () => {+ const ui = pswp.ui!;++ // Move the zoom button to the left so that it is in the same place+ // as the other items like preloader or the error indicator that+ // come and go as files get loaded. Also modify the default orders+ // so that there is more space for the error / live indicators.+ //+ // We cannot use the PhotoSwipe "uiElement" filter to modify the+ // order since that only allows us to edit the DOM element, not the+ // underlying UI element data.+ ui.uiElementsData.find((e) => e.name == "zoom")!.order = 6;+ ui.uiElementsData.find((e) => e.name == "preloader")!.order = 10;++ // Register our custom elements...++ if (isPublicAlbum) {+ ui.registerElement({+ name: "ente-logo",+ order: 5,+ isButton: true,+ title: "Ente",+ html: publicAlbumEnteLogoHTML(),+ onClick: () => {+ window.open(+ "https://ente.io",+ "_blank",+ "noopener,noreferrer",+ );+ },+ });+ }++ ui.registerElement({+ name: "live",+ title: t("live"),+ order: 7,+ isButton: true,+ html: createPSRegisterElementIconHTML("live"),+ onInit: (buttonElement) => {+ livePhotoPlayButtonElement = buttonElement;+ pswp.on("change", () => {+ const video = livePhotoVideoOnSlide(pswp.currSlide);+ if (video) {+ livePhotoUpdatePlayInitial(video);+ } else {+ // Not a live photo, or its video hasn't loaded yet.+ showIf(buttonElement, false);+ }+ });+ },+ onClick: livePhotoTogglePlayIfPossible,+ });++ ui.registerElement({+ name: "vol",+ title: t("audio"),+ order: 8,+ isButton: true,+ html: createPSRegisterElementIconHTML("vol"),+ onInit: (buttonElement) => {+ livePhotoMuteButtonElement = buttonElement;+ pswp.on("change", () => {+ const video = livePhotoVideoOnSlide(pswp.currSlide);+ if (video) {+ livePhotoUpdateMute(video);+ } else {+ // Not a live photo, or its video hasn't loaded yet.+ showIf(buttonElement, false);+ }+ });+ },+ onClick: livePhotoToggleMuteIfPossible,+ });++ ui.registerElement({+ name: "error",+ order: 9,+ html: createPSRegisterElementIconHTML("error"),+ onInit: (errorElement, pswp) => {+ pswp.on("change", () => {+ const { fetchFailed, isContentLoading } =+ currSlideData();+ errorElement.classList.toggle(+ "pswp__error--active",+ !!fetchFailed && !isContentLoading,+ );+ });+ },+ });++ // Only one of these two ("favorite" and "download") will end+ // up being shown, so they can safely share the same order.+ if (haveUser) {+ ui.registerElement({+ name: "favorite",+ title: t("favorite"),+ order: 11,+ isButton: true,+ html: createPSRegisterElementIconHTML("favorite"),+ onInit: (buttonElement) => {+ favoriteButtonElement =+ // The cast should be safe (unless there is a+ // PhotoSwipe bug) since we set isButton to true.+ buttonElement as HTMLButtonElement;+ pswp.on("change", updateFavoriteButtonIfNeeded);+ },+ onClick: handleToggleFavorite,+ });+ } else {+ // When we don't have a user (i.e. in the context of public+ // albums), the download button is shown (if enabled for that+ // album) instead of the favorite button as the first action.+ ui.registerElement({+ name: "download",+ title: t("download"),+ order: 11,+ isButton: true,+ html: createPSRegisterElementIconHTML("download"),+ onInit: (buttonElement) =>+ pswp.on("change", () =>+ showIf(+ buttonElement,+ currentFileAnnotation().showDownload == "bar",+ ),+ ),+ onClick: handleDownload,+ });+ }++ ui.registerElement({+ name: "info",+ title: t("info"),+ order: 13,+ isButton: true,+ html: createPSRegisterElementIconHTML("info"),+ onClick: handleViewInfo,+ });++ // Only show the more button if there are meaningful items to display.+ // When fullscreen is shown in the toolbar (showFullscreenButton=true)+ // and we're in a context without user actions (no delete, archive, etc),+ // hide the more menu since it would only contain fullscreen and shortcuts.+ const shouldShowMoreButton = !showFullscreenButton || haveUser;++ if (shouldShowMoreButton) {+ ui.registerElement({+ name: "more",+ title: t("more"),+ order: 16,+ isButton: true,+ html: createPSRegisterElementIconHTML("more"),+ onInit: (buttonElement) => {+ buttonElement.setAttribute("id", moreButtonID);+ buttonElement.setAttribute("aria-haspopup", "true");+ },+ onClick: (_, buttonElement) => {+ // See also: `resetMoreMenuButtonOnMenuClose`.+ buttonElement.setAttribute("aria-controls", moreMenuID);+ buttonElement.setAttribute("aria-expanded", "true");+ onMore(buttonElement);+ },+ });+ }++ // Add fullscreen button as a primary action for embed app+ if (showFullscreenButton) {+ ui.registerElement({+ name: "fullscreen",+ title: t("toggle_fullscreen"),+ order: 18,+ isButton: true,+ html: createPSRegisterElementIconHTML("fullscreen"),+ onInit: (buttonElement, pswp) => {+ const updateIcon = () => {+ const isFullscreen = !!document.fullscreenElement;+ const fullscreenIcon = buttonElement.querySelector(+ "#pswp__icn-fullscreen",+ );+ const exitIcon = buttonElement.querySelector(+ "#pswp__icn-fullscreen-exit",+ );+ if (fullscreenIcon && exitIcon) {+ showIf(+ fullscreenIcon as HTMLElement,+ !isFullscreen,+ );+ showIf(exitIcon as HTMLElement, isFullscreen);+ }+ };++ // Update icon on fullscreen changes+ document.addEventListener(+ "fullscreenchange",+ updateIcon,+ );+ pswp.on("destroy", () => {+ document.removeEventListener(+ "fullscreenchange",+ updateIcon,+ );+ });++ // Initialize icon state+ updateIcon();+ },+ onClick: handleToggleFullscreen,+ });+ }++ ui.registerElement({+ name: "media-controls",+ // Arbitrary order towards the end.+ order: 30,+ appendTo: "root",+ html: hlsVideoControlsHTML(),+ onInit: (element, pswp) => {+ mediaControlsContainerElement = element;+ const menu = element.querySelector("#ente-quality-menu");+ if (menu instanceof MediaChromeMenu) {+ menu.addEventListener("change", onVideoQualityChange);+ }+ // Override the media-fullscreen-button to use document-level+ // fullscreen instead of element-level fullscreen. This+ // ensures the PhotoSwipe UI controls remain accessible.+ const fullscreenButton = element.querySelector(+ "media-fullscreen-button",+ );+ fullscreenButton?.addEventListener(+ "click",+ handleFullscreenButtonClick,+ { capture: true },+ );+ pswp.on("change", () =>+ updateVideoControlsAndPlayback(currSlideData()),+ );+ },+ });++ ui.registerElement({+ name: "bottom-right-controls",+ // After the video controls so that we don't get occluded by+ // them (nb: the caption will hide when the video is playing).+ order: 31,+ appendTo: "root",+ html: bottomRightControlsHTML(),+ onInit: (element, pswp) => {+ const captionEl =+ element.querySelector<HTMLElement>(".pswp__caption")!;+ // Get the action buttons container.+ const actionButtonsEl = element.querySelector<HTMLElement>(+ ".pswp__action-buttons",+ );++ const updateSocialButtonsVisibility = () => {+ if (!actionButtonsEl) return;+ // Guard: _currentAnnotatedFile can be undefined during+ // initialization before the first slide is shown.+ if (!_currentAnnotatedFile) return;+ // Show buttons if: static showSocialButtons is true+ // (public album) OR delegate says this file should+ // show buttons (file in shared collection).+ // For public albums (no logged-in user), also check+ // if comments are enabled on the public link.+ const af = currentAnnotatedFile();+ const baseShow =+ showSocialButtons ||+ delegate.shouldShowSocialButtons(af);+ // For public albums (!haveUser), also require enableComment+ const shouldShow =+ baseShow && (haveUser || enableComment);+ actionButtonsEl.style.display = shouldShow+ ? "flex"+ : "none";+ };++ pswp.on("change", () => {+ const { fileType, alt } = currSlideData();+ const { text: captionText, wasTruncated } =+ truncateCaptionIfNeeded(alt);+ const captionP = captionEl.querySelector("p")!;+ captionP.innerText = captionText ?? "";+ if (wasTruncated) {+ const moreLink = document.createElement("span");+ moreLink.className = "pswp__caption-more";+ moreLink.textContent = "More";+ moreLink.addEventListener("click", handleViewInfo);+ captionP.appendChild(moreLink);+ }+ captionEl.style.display = captionText+ ? "block"+ : "none";+ captionEl.classList.toggle(+ "ente-video",+ fileType == FileType.video,+ );+ // Update social buttons visibility on each slide change.+ updateSocialButtonsVisibility();+ });+ // Wire up click handler for the comment button.+ const commentButton = element.querySelector<HTMLElement>(+ '.pswp__action-button[aria-label="Comment"]',+ );+ commentButton?.addEventListener("click", onViewComments);+ // Wire up click handlers for the like button.+ const likeButton = element.querySelector<HTMLElement>(+ '.pswp__action-button[aria-label="Like"]',+ );+ // Left-click: trigger like action (may open album selector)+ likeButton?.addEventListener("click", onLikeClick);+ // Right-click: open likes sidebar+ likeButton?.addEventListener("contextmenu", (e) => {+ e.preventDefault();+ onViewLikes();+ });+ // Update like button state on slide change and initially.+ pswp.on("change", updateLikeButtonIfNeeded);+ updateLikeButtonIfNeeded();+ // Update comment count on slide change and initially.+ pswp.on("change", updateCommentCountIfNeeded);+ updateCommentCountIfNeeded();+ // Initial visibility check.+ updateSocialButtonsVisibility();+ },+ });+ });++ // Pan action handlers++ const panner = (key: "w" | "a" | "s" | "d") => () => {+ const slide = pswp.currSlide!;+ const d = 80;+ switch (key) {+ case "w":+ slide.pan.y += d;+ break;+ case "a":+ slide.pan.x += d;+ break;+ case "s":+ slide.pan.y -= d;+ break;+ case "d":+ slide.pan.x -= d;+ break;+ }+ slide.panTo(slide.pan.x, slide.pan.y);+ };++ // Actions we handle ourselves.++ const handlePreviousSlide = () => pswp.prev();++ const handleNextSlide = () => pswp.next();++ /**+ * The arrow keys are used both for navigating through slides, and for+ * scrubbing through the video.+ *+ * When on a video, the navigation requires the option prefix (since+ * scrubbing through the video is a more common requirement). However+ * this breaks the user's flow when they are navigating between slides+ * fast by using the arrow keys - they land on a video and the+ * navigation stops.+ *+ * So as a special case, we keep using arrow keys for navigation for the+ * first 700 milliseconds when the user lands on a slide.+ */+ const isUserLikelyNavigatingBetweenSlides = () =>+ Date.now() - lastSlideChangeEpochMilli < 700; /* ms */++ const handleSeekBackOrPreviousSlide = () => {+ const video = videoVideoEl;+ if (+ video &&+ !isUserLikelyNavigatingBetweenSlides() &&+ // If the video is at the beginning, then use the left arrow to+ // move to the preview slide.+ video.currentTime > 0+ ) {+ video.currentTime = Math.max(video.currentTime - 5, 0);+ } else {+ handlePreviousSlide();+ }+ };++ const handleSeekForwardOrNextSlide = () => {+ const video = videoVideoEl;+ if (+ video &&+ !isUserLikelyNavigatingBetweenSlides() &&+ // If the video has ended, then use right arrow to move to the+ // next slide.+ !video.ended+ ) {+ video.currentTime = video.currentTime + 5;+ } else {+ handleNextSlide();+ }+ };++ const handleTogglePlayIfPossible = () => {+ switch (currentAnnotatedFile().itemData.fileType) {+ case FileType.video:+ videoTogglePlayIfPossible();+ break;+ case FileType.livePhoto:+ livePhotoTogglePlayIfPossible();+ break;+ }+ };++ const handleToggleMuteIfPossible = () => {+ switch (currentAnnotatedFile().itemData.fileType) {+ case FileType.video:+ videoToggleMuteIfPossible();+ break;+ case FileType.livePhoto:+ livePhotoToggleMuteIfPossible();+ break;+ }+ };++ // Toggle controls infrastructure++ const handleToggleUIControls = () =>+ pswp.element!.classList.toggle("pswp--ui-visible");++ // Return true if the current keyboard focus is on any of the UI+ // controls (e.g. as a result of user tabbing through them).+ const isFocusVisibledOnUIControl = () => {+ const fv = document.querySelector(":focus-visible");+ if (fv && !fv.classList.contains("pswp")) {+ return true;+ }++ // Media Chrome does its own thing and doesn't seem to gain the+ // :focus-visible pseudo class even though it visually looks that+ // way. We need to add a special case for it.+ const f = document.querySelector(":focus");+ if (f?.tagName.startsWith("MEDIA-")) {+ return true;+ }++ return false;+ };++ // Some actions routed via the delegate++ const handleDelete = () => delegate.performKeyAction("delete");++ const handleToggleArchive = () =>+ delegate.performKeyAction("toggle-archive");++ const handleCopy = () => delegate.performKeyAction("copy");++ const handleToggleFullscreen = () =>+ delegate.performKeyAction("toggle-fullscreen");++ const handleHelp = () => delegate.performKeyAction("help");++ pswp.on("keydown", (pswpEvent) => {+ // Ignore keyboard events when one of our sub-dialogs are open.+ if (delegate.shouldIgnoreKeyboardEvent()) {+ pswpEvent.preventDefault();+ return;+ }++ const e: KeyboardEvent = pswpEvent.originalEvent;++ const key = e.key;+ // Even though we ignore shift, Caps lock might still be on.+ const lkey = e.key.toLowerCase();++ // When one of the controls on the screen has a visible focus+ // indicator, we want the Escape key to blur its focus instead of+ // closing the PhotoSwipe dialog.+ if (isFocusVisibledOnUIControl() && key == "Escape") {+ const activeElement = document.activeElement;+ if (activeElement instanceof HTMLElement) activeElement.blur();+ pswpEvent.preventDefault();+ return;+ }++ // Keep the keybindings such that they don't use modifiers, because+ // these are more likely to interfere with browser shortcuts.+ //+ // For example, Cmd-D adds a bookmark, which is why we don't use it+ // for download.+ //+ // There are some exception, e.g. Ctrl/Cmd-C, which we intercept to+ // copy the image since that should match the user's expectation.++ let cb: (() => void) | undefined;+ if (e.shiftKey) {+ // Ignore except "?" for help.+ if (key == "?") cb = handleHelp;+ } else if (e.altKey) {+ // Ignore except if for arrow keys since when showing a video,+ // the arrow keys are used for seeking, and the normal arrow key+ // function (slide movement) needs the Alt/Opt modifier.+ switch (key) {+ case "ArrowLeft":+ cb = handlePreviousSlide;+ break;+ case "ArrowRight":+ cb = handleNextSlide;+ break;+ }+ } else if (e.metaKey || e.ctrlKey) {+ // Ignore except Ctrl/Cmd-C for copy+ if (lkey == "c") cb = handleCopy;+ } else {+ switch (key) {+ case " ":+ // Space activates controls when they're focused, so+ // only act on it if no specific control is focused.+ if (!isFocusVisibledOnUIControl()) {+ cb = handleTogglePlayIfPossible;+ }+ // Prevent the browser's default space behaviour of+ // scrolling the file list in the background (which is+ // not appropriate when the file viewer is visible).+ if (e.target == document.body) e.preventDefault();+ break;+ case "Backspace":+ case "Delete":+ cb = handleDelete;+ break;+ case "ArrowLeft":+ cb = handleSeekBackOrPreviousSlide;+ // Prevent PhotoSwipe's default handling of this key.+ pswpEvent.preventDefault();+ break;+ case "ArrowRight":+ cb = handleSeekForwardOrNextSlide;+ // Prevent PhotoSwipe's default handling of this key.+ pswpEvent.preventDefault();+ break;+ // We check for "?"" both with an without shift, since some+ // keyboards might have it emittable without shift.+ case "?":+ cb = handleHelp;+ break;+ }+ switch (lkey) {+ case "w":+ case "a":+ case "s":+ case "d":+ cb = panner(lkey);+ break;+ case "h":+ cb = handleToggleUIControls;+ break;+ case "m":+ cb = handleToggleMuteIfPossible;+ break;+ case "l":+ cb = handleToggleFavoriteIfEnabled;+ break;+ case "i":+ cb = handleViewInfo;+ break;+ case "k":+ cb = handleDownloadIfEnabled;+ break;+ case "x":+ cb = handleToggleArchive;+ break;+ case "f":+ cb = handleToggleFullscreen;+ break;+ }+ }++ cb?.();+ });++ /**+ * [Note: Media chrome focus workaround]+ *+ * The media-chrome-button elements (e.g, the play button, but also+ * others, including the menu) retain focus after clicking on them.+ * e.g., if I click the "media-mute-button" to activate it, then the+ * mute button grabs focus (but not :focus-visible). So it doesn't+ * appear focused visually, but then later if I press Space or Enter,+ * then the mute button activates again instead of toggling video+ * playback (as our keyboard shortcut is meant to do).+ *+ * I'm not sure who is at fault here, but this behaviour ends up being+ * irritating. e.g. say I change the quality in the menu, and press+ * space to play - well, the space no longer works because the media+ * chrome has grabbed focus and instead activates itself, reopening the+ * settings menu.+ *+ * As a workaround, we ask media chrome to drop focus on mouse clicks.+ * This should not impact keyboard activations.+ *+ * This workaround is likely to cause problems in the future, but I+ * can't find a better way short of upstream media chrome changes.+ */+ const blurMediaChromeFocus = (e: MouseEvent) => {+ const target = e.target;+ if (target instanceof HTMLElement) {+ switch (target.tagName) {+ case "MEDIA-TIME-RANGE":+ case "MEDIA-PLAY-BUTTON":+ case "MEDIA-MUTE-BUTTON":+ case "MEDIA-PIP-BUTTON":+ case "MEDIA-FULLSCREEN-BUTTON":+ setTimeout(() => target.blur(), 0);+ break;+ }+ }+ };++ pswp.on("initialLayout", () => {+ pswp.element!.addEventListener("mousedown", blurMediaChromeFocus);+ document.addEventListener(+ "fullscreenchange",+ handleFullscreenChange,+ );+ });++ // The PhotoSwipe dialog has being closed and the animations have+ // completed.+ pswp.on("destroy", () => {+ pswp.element?.removeEventListener(+ "mousedown",+ blurMediaChromeFocus,+ );+ document.removeEventListener(+ "fullscreenchange",+ handleFullscreenChange,+ );+ document.removeEventListener(+ "mousemove",+ handleMouseMoveInFullscreen,+ );+ if (hideControlsTimer) {+ clearTimeout(hideControlsTimer);+ }+ fileViewerDidClose();+ // Let our parent know that we have been closed.+ onClose();+ });++ // Let our data source know that we're about to open.+ fileViewerWillOpen();++ // Initializing PhotoSwipe adds it to the DOM as a dialog-like div with+ // the class "pswp".+ pswp.init();+ }++ /**+ * Close this instance of {@link FileViewerPhotoSwipe} if it hasn't itself+ * initiated the close.+ *+ * This instance **cannot** be used after this function has been called.+ */+ closeIfNeeded() {+ // Closing PhotoSwipe removes it from the DOM.+ //+ // This will only have an effect if we're being closed externally (e.g.+ // if the user selects an album in the file info).+ //+ // If this cleanup function is running in the sequence where we were+ // closed internally (e.g. the user activated the close button within+ // the file viewer), then PhotoSwipe will ignore this extra close.+ this.pswp.close();+ }++ /**+ * Reload the current slide, asking the data source for its data afresh.+ */+ refreshCurrentSlideContent() {+ this.pswp.refreshSlideContent(this.pswp.currIndex);+ }++ /**+ * Ask the delegate for the files information afresh, and perform the+ * sequence described in [Note: Updates to the files prop for FileViewer].+ */+ refreshSlideOnFilesUpdateIfNeeded: () => void;++ /**+ * Refresh the favorite button (if indeed it is visible at all) on the+ * current slide, asking the delegate for the latest state.+ *+ * We do this piecemeal update instead of a full refresh because a full+ * refresh would cause, e.g., the pan and zoom to be reset.+ */+ refreshCurrentSlideFavoriteButtonIfNeeded: () => void;++ /**+ * Refresh the like button (heart) on the current slide, asking the+ * delegate for the latest like state.+ */+ refreshCurrentSlideLikeButtonIfNeeded: () => void;++ /**+ * Refresh the comment count on the current slide, asking the delegate+ * for the latest comment count.+ */+ refreshCurrentSlideCommentCountIfNeeded: () => void;+}++// Requires the following imports to register the Web components we use:+//+// import "hls-video-element";+// import "media-chrome";+// import "media-chrome/menu";+//+const hlsVideoHTML = (url: string, mediaControllerID: string) => `+<media-controller id="${mediaControllerID}" nohotkeys>+ <hls-video playsinline slot="media" src="${url}"></hls-video>+</media-controller>+`;++const videoHTML = (url: string, mediaControllerID: string) => `+<media-controller class="ente-vanilla-video" id="${mediaControllerID}" nohotkeys>+ <video playsinline slot="media" src="${url}"></video>+</media-controller>+`;++/**+ * HTML for controls associated with {@link hlsVideoHTML} or {@link videoHTML}.+ *+ * To make these functional, the `media-control-bar` requires the+ * `mediacontroller="${mediaControllerID}"` attribute.+ *+ * Notes:+ *+ * - Examples: https://media-chrome.mux.dev/examples/vanilla/+ *+ * - When PiP is active and the video moves out, the browser displays some+ * indicator (browser specific) in the in-page video element. This element and+ * text is not under our control.+ *+ * - The media-cast-button currently doesn't work with the `hls-video` player.+ *+ * - We don't use media chrome tooltips: Media chrome has mechanism for+ * statically providing translations but it wasn't working when I tried with+ * 4.9.0. The media chrome tooltips also get clipped for the cornermost+ * buttons. Finally, the rest of the buttons on this screen don't have a+ * tooltip either.+ *+ * Revisit this when we have a custom tooltip element we can then also use on+ * this screen, which can also be used enhancement for the other buttons on+ * this screen which use "title" (which get clipped when they are multi-word).+ *+ * - See: [Note: Spurious media chrome resize observer errors]+ *+ * - If something is not working as expected, a possible reason might be the+ * focus workaround. See: [Note: Media chrome focus workaround].+ */+const hlsVideoControlsHTML = () => `+<div>+ <media-settings-menu id="ente-settings-menu" hidden anchor="ente-settings-menu-btn">+ <media-settings-menu-item>+ ${t("quality")}+ <media-chrome-menu id="ente-quality-menu" slot="submenu" hidden>+ <div slot="title">${t("quality")}</div>+ <media-chrome-menu-item type="radio">${t("auto")}</media-chrome-menu-item>+ <media-chrome-menu-item type="radio">${t("original")}</media-chrome-menu-item>+ </media-chrome-menu>+ </media-settings-menu-item>+ <media-settings-menu-item>+ ${t("speed")}+ <media-playback-rate-menu slot="submenu" hidden>+ <div slot="title">${t("speed")}</div>+ </media-playback-rate-menu>+ </media-settings-menu-item>+ </media-settings-menu>+ <media-control-bar>+ <media-loading-indicator noautohide></media-loading-indicator>+ </media-control-bar>+ <media-control-bar>+ <media-time-range></media-time-range>+ </media-control-bar>+ <media-control-bar>+ <media-play-button notooltip></media-play-button>+ <media-mute-button notooltip></media-mute-button>+ <media-time-display showduration notoggle></media-time-display>+ <media-text-display></media-text-display>+ <media-settings-menu-button id="ente-settings-menu-btn" invoketarget="ente-settings-menu" notooltip>+ <svg slot="icon" viewBox="0 0 24 24">${settingsSVGPath}</svg>+ </media-settings-menu-button>+ <media-pip-button notooltip></media-pip-button>+ <media-fullscreen-button notooltip></media-fullscreen-button>+ </media-control-bar>+</div>+`;++// playsinline will play the video inline on mobile browsers (where the default+// is to open a full screen player).+const livePhotoVideoHTML = (videoURL: string) => `+<video muted playsinline oncontextmenu="return false;">+ <source src="${videoURL}" />+</video>+`;++/**+ * HTML for the bottom controls (caption on left, action buttons on right).+ *+ * The caption uses the line-clamp CSS property, which behaves unexpectedly+ * when we also assign padding to the "p" element on which we're setting the+ * line clamp: the "clipped" lines show through in the padding area.+ *+ * As a workaround, wrap the p in a div. Set the line-clamp on the p, and the+ * padding on the div.+ */+const bottomRightControlsHTML = () => `+<div class="pswp__caption"><p></p></div>+<div class="pswp__action-buttons">+ <button class="pswp__action-button" aria-label="Like">+ <svg viewBox="0 0 30 26" fill="none">${heartSVGPath} id="pswp__icn-heart" />${heartFillSVGPath} id="pswp__icn-heart-fill" /></svg>+ </button>+ <button class="pswp__action-button pswp__action-button--comment" aria-label="Comment">+ <svg viewBox="0 0 28 28" fill="none">${commentSVGPath} /></svg>+ <span class="pswp__comment-count"></span>+ </button>+</div>+`;++const publicAlbumEnteLogoHTML = () => `+<svg class="pswp__ente-logo-svg" viewBox="0 0 43 13" fill="currentColor" xmlns="http://www.w3.org/2000/svg">+ <path d="M6.102 12.144C4.998 12.144 4.026 11.928 3.186 11.496C2.358 11.064 1.716 10.476 1.26 9.732C0.804 8.976 0.576 8.118 0.576 7.158C0.576 6.186 0.798 5.328 1.242 4.584C1.698 3.828 2.316 3.24 3.096 2.82C3.876 2.388 4.758 2.172 5.742 2.172C6.69 2.172 7.542 2.376 8.298 2.784C9.066 3.18 9.672 3.756 10.116 4.512C10.56 5.256 10.782 6.15 10.782 7.194C10.782 7.302 10.776 7.428 10.764 7.572C10.752 7.704 10.74 7.83 10.728 7.95H2.862V6.312H9.252L8.172 6.798C8.172 6.294 8.07 5.856 7.866 5.484C7.662 5.112 7.38 4.824 7.02 4.62C6.66 4.404 6.24 4.296 5.76 4.296C5.28 4.296 4.854 4.404 4.482 4.62C4.122 4.824 3.84 5.118 3.636 5.502C3.432 5.874 3.33 6.318 3.33 6.834V7.266C3.33 7.794 3.444 8.262 3.672 8.67C3.912 9.066 4.242 9.372 4.662 9.588C5.094 9.792 5.598 9.894 6.174 9.894C6.69 9.894 7.14 9.816 7.524 9.66C7.92 9.504 8.28 9.27 8.604 8.958L10.098 10.578C9.654 11.082 9.096 11.472 8.424 11.748C7.752 12.012 6.978 12.144 6.102 12.144ZM18.5375 2.172C19.3055 2.172 19.9895 2.328 20.5895 2.64C21.2015 2.94 21.6815 3.408 22.0295 4.044C22.3775 4.668 22.5515 5.472 22.5515 6.456V12H19.7435V6.888C19.7435 6.108 19.5695 5.532 19.2215 5.16C18.8855 4.788 18.4055 4.602 17.7815 4.602C17.3375 4.602 16.9355 4.698 16.5755 4.89C16.2275 5.07 15.9515 5.352 15.7475 5.736C15.5555 6.12 15.4595 6.612 15.4595 7.212V12H12.6515V2.316H15.3335V4.998L14.8295 4.188C15.1775 3.54 15.6755 3.042 16.3235 2.694C16.9715 2.346 17.7095 2.172 18.5375 2.172ZM29.0568 12.144C27.9168 12.144 27.0288 11.856 26.3928 11.28C25.7568 10.692 25.4388 9.822 25.4388 8.67V0.174H28.2468V8.634C28.2468 9.042 28.3548 9.36 28.5708 9.588C28.7868 9.804 29.0808 9.912 29.4528 9.912C29.8968 9.912 30.2748 9.792 30.5868 9.552L31.3428 11.532C31.0548 11.736 30.7068 11.892 30.2988 12C29.9028 12.096 29.4888 12.144 29.0568 12.144ZM23.9448 4.692V2.532H30.6588V4.692H23.9448ZM37.4262 12.144C36.3222 12.144 35.3502 11.928 34.5102 11.496C33.6822 11.064 33.0402 10.476 32.5842 9.732C32.1282 8.976 31.9002 8.118 31.9002 7.158C31.9002 6.186 32.1222 5.328 32.5662 4.584C33.0222 3.828 33.6402 3.24 34.4202 2.82C35.2002 2.388 36.0822 2.172 37.0662 2.172C38.0142 2.172 38.8662 2.376 39.6222 2.784C40.3902 3.18 40.9962 3.756 41.4402 4.512C41.8842 5.256 42.1062 6.15 42.1062 7.194C42.1062 7.302 42.1002 7.428 42.0882 7.572C42.0762 7.704 42.0642 7.83 42.0522 7.95H34.1862V6.312H40.5762L39.4962 6.798C39.4962 6.294 39.3942 5.856 39.1902 5.484C38.9862 5.112 38.7042 4.824 38.3442 4.62C37.9842 4.404 37.5642 4.296 37.0842 4.296C36.6042 4.296 36.1782 4.404 35.8062 4.62C35.4462 4.824 35.1642 5.118 34.9602 5.502C34.7562 5.874 34.6542 6.318 34.6542 6.834V7.266C34.6542 7.794 34.7682 8.262 34.9962 8.67C35.2362 9.066 35.5662 9.372 35.9862 9.588C36.4182 9.792 36.9222 9.894 37.4982 9.894C38.0142 9.894 38.4642 9.816 38.8482 9.66C39.2442 9.504 39.6042 9.27 39.9282 8.958L41.4222 10.578C40.9782 11.082 40.4202 11.472 39.7482 11.748C39.0762 12.012 38.3022 12.144 37.4262 12.144Z" />+</svg>+`;++/**+ * Truncate caption text to 154 characters.+ *+ * @returns An object with the (possibly truncated) text and a flag indicating+ * whether or not the text was truncated.+ */+const truncateCaptionIfNeeded = (+ text: string | undefined,+): { text: string | undefined; wasTruncated: boolean } => {+ if (!text) return { text, wasTruncated: false };+ const maxLength = 154;+ if (text.length <= maxLength) return { text, wasTruncated: false };+ return { text: text.slice(0, maxLength) + "… ", wasTruncated: true };+};++const createElementFromHTMLString = (htmlString: string) => {+ const template = document.createElement("template");+ // Excess whitespace causes excess DOM nodes, causing our firstChild to not+ // be what we wanted them to be.+ template.innerHTML = htmlString.trim();+ return template.content.firstChild!;+};++/**+ * Update the ARIA attributes for the button that controls the more menu when+ * the menu is closed.+ */+export const resetMoreMenuButtonOnMenuClose = (buttonElement: HTMLElement) => {+ buttonElement.removeAttribute("aria-controls");+ buttonElement.removeAttribute("aria-expanded");+};diff --git a/web/apps/albums/vendor/ente-gallery/export-dirs.ts b/web/apps/albums/vendor/ente-gallery/export-dirs.tsnew file mode 100644index 0000000000..40229741ed--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/export-dirs.ts@@ -0,0 +1,11 @@+/**+ * Name of the directory in which we put our metadata when exporting to the file+ * system.+ */+export const exportMetadataDirectoryName = "metadata";++/**+ * Name of the directory in which we keep trash items when deleting files that+ * have been exported to the local disk previously.+ */+export const exportTrashDirectoryName = "Trash";diff --git a/web/apps/albums/vendor/ente-gallery/services/convert.ts b/web/apps/albums/vendor/ente-gallery/services/convert.tsnew file mode 100644index 0000000000..5568f7d19b--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/convert.ts@@ -0,0 +1,324 @@+import { isDesktop } from "ente-base/app";+import { lowercaseExtension } from "ente-base/file-name";+import log from "ente-base/log";+import { workerBridge } from "ente-base/worker/worker-bridge";+import type { EnteFile } from "ente-media/file";+import { FileType, KnownFileTypeInfos } from "ente-media/file-type";+import { isHEICExtension, needsJPEGConversion } from "ente-media/formats";+import { heicToJPEG } from "ente-media/heic-convert";+import { detectFileTypeInfo } from "../utils/detect-type";+import { convertToMP4 } from "./ffmpeg";++/**+ * Return a new {@link Blob} containing an image's data in a format that the+ * browser (likely) knows how to render (in an img tag, or on the canvas).+ *+ * The type of the returned blob is set, whenever possible, to the MIME type of+ * the data that we're dealing with.+ *+ * @param imageBlob A {@link Blob} containing the contents of an image file.+ *+ * @param fileName The name of the file whose data {@link imageBlob} is.+ *+ * The logic used by this function is:+ *+ * 1. Try to detect the MIME type of the file from its contents and/or name.+ *+ * 2. If this detected type is one of the types that we know that the browser+ * likely cannot render, continue. Otherwise return the imageBlob that was+ * passed in (after setting its MIME type).+ *+ * 3. If we're running in our desktop app and this MIME type is something our+ * desktop app can natively convert to a JPEG (using ffmpeg), do that and+ * return the resultant JPEG blob.+ *+ * 4. If this is an HEIC file and the browser does not have native HEIC support,+ * then use our (Wasm) HEIC converter and return the resultant JPEG blob.+ *+ * 5. Otherwise return the original (with the MIME type if we were able to+ * deduce one).+ *+ * In will catch all errors and return the original in those cases.+ */+export const renderableImageBlob = async (+ imageBlob: Blob,+ fileName: string,+): Promise<Blob> => {+ try {+ const file = new File([imageBlob], fileName);+ const fileTypeInfo = await detectFileTypeInfo(file);+ const { extension, mimeType } = fileTypeInfo;++ if (needsJPEGConversion(extension)) {+ log.debug(() => [`Converting ${fileName} to JPEG`, fileTypeInfo]);++ // If we're running in our desktop app, see if our Node.js layer can+ // convert this into a JPEG using native tools.++ if (isDesktop) {+ try {+ return await nativeConvertToJPEG(imageBlob);+ } catch (e) {+ log.error("Native conversion to JPEG failed", e);+ }+ }++ // If the previous step failed, or if native JPEG conversion is not+ // available on this platform, for HEIC/HEIF files we can fallback+ // to our web HEIC converter.++ if (isHEICExtension(extension)) {+ // But first, check if the browser already knows how to natively+ // render HEICs, e.g. Safari 17+. In such cases not only is the+ // Wasm conversion unnecessary, the native hardware accelerated+ // support will also be _much_ faster.+ if (mimeType == "image/heic" && (await isHEICSupported())) {+ log.debug(+ () => `Using native HEIC support for ${fileName}`,+ );+ } else {+ return await heicToJPEG(imageBlob);+ }+ }+ }++ // Either it is something that the browser already knows how to render+ // (e.g. JPEG/PNG), or is a file extension that might be supported in+ // some browsers (e.g. JPEG 2000), or a file extension that we haven't+ // specifically whitelisted for conversion (any arbitrary extension not+ // part of `needsJPEGConversion`).+ //+ // Give it to the browser, attaching the mime type if possible.++ if (!mimeType) {+ log.info(+ "Attempting to convert a file without a MIME type",+ fileName,+ );+ return imageBlob;+ } else {+ return new Blob([imageBlob], { type: mimeType });+ }+ } catch (e) {+ log.error(`Failed to convert ${fileName}, will use the original`, e);+ return imageBlob;+ }+};++/**+ * Convert {@link imageBlob} to a JPEG blob.+ *+ * The presumption is that method used by our desktop app for converting to JPEG+ * should be able to handle files with all extensions for which+ * {@link needsJPEGConversion} returns true.+ */+const nativeConvertToJPEG = async (imageBlob: Blob) => {+ const startTime = Date.now();+ const imageData = new Uint8Array(await imageBlob.arrayBuffer());+ const electron = globalThis.electron;+ // If we're running in a worker, we need to reroute the request back to+ // the main thread since workers don't have access to the `window` (and+ // thus, to the `window.electron`) object.+ const jpegData = electron+ ? await electron.convertToJPEG(imageData)+ : await workerBridge!.convertToJPEG(imageData);+ log.debug(() => `Native JPEG conversion took ${Date.now() - startTime} ms`);+ return new Blob([jpegData], { type: "image/jpeg" });+};++let _isHEICSupported: Promise<boolean> | undefined;++/**+ * Return true if the browser can natively render HEIC files.+ *+ * For performance, the result of the check is cached. There shouldn't be a+ * reason for this cache to need be invalidated, the browser shouldn't suddenly+ * drop its HEIC support in the middle of it running (but I'm sure posterity+ * will prove this assumption wrong in a way I can't yet anticipate).+ *+ * Some more details:+ *+ * - The check works by trying to load a small HEIC file.+ *+ * - Currently (Spring 2025), the only browser with support for HEIC is Safari.+ */+const isHEICSupported = () =>+ (_isHEICSupported ??= new Promise((resolve) => {+ const image = new Image();+ image.onload = () => resolve(true);+ image.onerror = () => resolve(false);+ image.src = testHEICDataURL;+ }));++/**+ * A data URL encoding the smallest HEIC image (439 bytes).+ *+ * Source:+ * https://github.com/vvideo/detect-audio-video/blob/main/src/image/smallest/index.ts+ */+const testHEICDataURL =+ "data:image/heic;base64,AAAAGGZ0eXBoZWljAAAAAG1pZjFoZWljAAABaW1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAHBpY3QAAAAAAAAAAAAAAAAAAAAADnBpdG0AAAAAAAEAAAAiaWxvYwAAAABEQAABAAEAAAAAAYkAAQAAAAAAAAAuAAAAI2lpbmYAAAAAAAEAAAAVaW5mZQIAAAAAAQAAaHZjMQAAAADpaXBycAAAAMppcGNvAAAAdmh2Y0MBA3AAAAAAAAAAAAAe8AD8/fj4AAAPAyAAAQAYQAEMAf//A3AAAAMAkAAAAwAAAwAeugJAIQABACpCAQEDcAAAAwCQAAADAAADAB6gIIEFluqumubgIaDAgAAAAwCAAAADAIQiAAEABkQBwXPBiQAAABRpc3BlAAAAAAAAAEAAAABAAAAAKGNsYXAAAAABAAAAAQAAAAEAAAAB////wQAAAAL////BAAAAAgAAABBwaXhpAAAAAAMICAgAAAAXaXBtYQAAAAAAAAABAAEEgQKDBAAAADZtZGF0AAAAKigBrwayEx2gkim3i/2Rd0CR/V6h6GbEyV3dheegYfLV9ZwraCH8nff+7w==";++/**+ * Return a object URL containing a video's data in a format that the browser+ * (likely) knows how to play back using an video tag.+ *+ * Unlike {@link renderableImageBlob}, this uses a much simpler flowchart:+ *+ * 1. If the browser thinks it can play the video, then return the an object URL+ * created by directly using the provided {@link videoBlob}.+ *+ * 2. Otherwise try to convert using FFmpeg. This conversion always happens on+ * the desktop app, but in the browser the conversion only happens for short+ * videos since the Wasm FFmpeg implementation is much slower.+ *+ * 3. On errors, return the original (as would've happened for step 1).+ *+ * A special case if for FileType.livePhoto on Linux in the desktop app, where+ * the conversion always happens to workaround the audio only playback in that+ * specific scenario.+ *+ * @param file The {@link EnteFile} with which this video is associated.+ *+ * @param videoFileName The name of the video.+ *+ * @param videoBlob The contents of the video.+ *+ * @returns An object URL that can be used to playback the provided+ * {@link videoBlob}.+ */+export const playableVideoURL = async (+ file: EnteFile,+ videoFileName: string,+ videoBlob: Blob,+): Promise<string> => {+ // Safari-only MIME correction for blob URLs to avoid NotSupportedError.+ // Prefer extension-based lookup first (fast, no sniff). Fallback to+ // content detection only if extension is unknown.+ let typedBlob: Blob = videoBlob;+ // Note: We use isHEICSupported() as a Safari proxy. As of 2025, Safari is+ // the only browser with native HEIC support, so gating here effectively+ // targets Safari engines where stricter blob MIME handling applies.+ if (await isHEICSupported()) {+ const ext = lowercaseExtension(videoFileName);+ const known = KnownFileTypeInfos.find((f) => f.extension === ext);+ const knownMIME = known?.mimeType;+ if (knownMIME && knownMIME !== videoBlob.type) {+ typedBlob = new Blob([videoBlob], { type: knownMIME });+ } else {+ try {+ const detected = await detectFileTypeInfo(+ new File([videoBlob], videoFileName),+ );+ if (detected.mimeType && detected.mimeType !== videoBlob.type) {+ typedBlob = new Blob([videoBlob], {+ type: detected.mimeType,+ });+ }+ } catch {+ // Best-effort only; fall back to original blob on detection failure.+ }+ }+ }++ const videoObjectURL = URL.createObjectURL(typedBlob);+ const isPlayable = await isPlaybackPossible(videoObjectURL);++ let shouldConvert = false;++ if (isPlayable) {+ // The browser thinks it can play this video.+ //+ // But it is not a guarantee. In particular, a problematic case is when+ // for a particular codec combination, browser can play the audio+ // stream, but not the video stream. `isPlaybackPossible` would return+ // true, but when the user will hear only audio and not see the video.+ //+ // For videos themselves, we solve this (and other issues) by providing+ // a streaming variant. However it can still happen for live photos.+ //+ // Unfortunately, I haven't found a way yet of detecting if this+ // scenario is going to arise (open a issue if you've found one).+ // Fortunately, this particular failure mode has only been reported on+ // Linux desktop app (which uses Chromium underneath). So we add a+ // special case - if (desktop && livePhoto && linux) then forceConvert.+ // Practically this is a reasonable fallback since the video component+ // of a live photo is going to be a few seconds only, and the video+ // conversion is fast in the desktop app.+ if (+ isDesktop &&+ file.metadata.fileType == FileType.livePhoto &&+ // eslint-disable-next-line @typescript-eslint/no-deprecated+ navigator.platform.startsWith("Linux")+ ) {+ shouldConvert = true;+ }+ } else {+ // The browser doesn't think it can play this video, try transcoding.+ if (isDesktop) {+ // Always on desktop.+ shouldConvert = true;+ } else {+ // Don't try to transcode on the web if the file is too big.+ if (videoBlob.size < 100 * 1024 * 1024 /* 100 MB, arbitrary */) {+ shouldConvert = true;+ }+ }+ }++ if (shouldConvert) {+ try {+ log.info(`Converting ${videoFileName} to mp4`);+ const convertedBlob = await convertToMP4(videoBlob);+ return URL.createObjectURL(+ new Blob([convertedBlob], { type: "video/mp4" }),+ );+ } catch (e) {+ log.error(`Video conversion failed for ${videoFileName}`, e);+ }+ }++ return videoObjectURL;+};++/**+ * Try to see if the browser thinks it can play the video pointed to by the+ * given {@link url} by creating a <video> element and initiating playback.+ *+ * Note that this can sometimes cause false positives if the browser can play+ * some of the streams in the video, but not all. For example, the browser may+ * be able to play back the video stream, but not the audio stream (say due to+ * some codec issue): in such cases this function will return true, causing us+ * to skip conversion, but when the user actually plays the video there will be+ * no sound.+ *+ * To deal with such cases in an holistic manner, we have a streaming variant of+ * the video that gets transcoded into a (near) universal format.+ */+const isPlaybackPossible = async (url: string) =>+ new Promise((resolve) => {+ const t = setTimeout(() => {+ video.remove();+ resolve(false);+ }, 1000);++ const video = document.createElement("video");+ video.addEventListener("canplay", () => {+ clearTimeout(t);+ // Clean up the video element.+ video.remove();+ // Check for duration > 0 to make sure it is not a broken video.+ if (video.duration > 0) {+ resolve(true);+ } else {+ resolve(false);+ }+ });+ video.addEventListener("error", () => {+ clearTimeout(t);+ video.remove();+ resolve(false);+ });++ video.src = url;+ });diff --git a/web/apps/albums/vendor/ente-gallery/services/download.ts b/web/apps/albums/vendor/ente-gallery/services/download.tsnew file mode 100644index 0000000000..7cfed9c48a--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/download.ts@@ -0,0 +1,873 @@+import { blobCache, type BlobCache } from "ente-base/blob-cache";+import {+ decryptBlobBytes,+ decryptStreamBytes,+ decryptStreamChunk,+ initChunkDecryption,+} from "ente-base/crypto";+import {+ authenticatedPublicAlbumsRequestHeaders,+ authenticatedRequestHeaders,+ publicRequestHeaders,+ retryEnsuringHTTPOk,+ type PublicAlbumsCredentials,+} from "ente-base/http";+import log from "ente-base/log";+import { apiURL, customAPIOrigin } from "ente-base/origins";+import { ensureAuthToken } from "ente-base/token";+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 { detectFileTypeInfoFromChunk } from "../utils/detect-type";+import { playableVideoURL, renderableImageBlob } from "./convert";++/**+ * URL(s) for the original image or video, alongwith with potential conversions+ * applied to make it more likely that the browser (or desktop app) will be able+ * to render (or play) it.+ *+ * The word "renderable" or "playable" is not a guarantee, but rather a best+ * effort indicator as we might not always be able to convert all formats to+ * something that the browser (or desktop app) can show.+ */+export type RenderableSourceURLs =+ | {+ type: "image";+ /**+ * An object URL that can be directly provided to the browser to get+ * it to render the image.+ *+ * This is a best effort basis. Not all images will be renderable in+ * all browsers, so the file might still not be previewable.+ *+ * In cases where we detect that the browser can natively render this+ * image, this can be just the an object URL created from+ * {@link originalImageBlob}. In other cases, this will point to a+ * separate, converted blob.+ */+ imageURL: string;+ /**+ * A {@link Blob} from the original image.+ *+ * This is useful for extracting the Exif.+ */+ originalImageBlob: Blob;+ /**+ * Best effort attempt at obtaining the MIME type.+ *+ * It should usually be present, but it is not guaranteed that we'll+ * be able to detect the MIME type for all images. However, the only+ * scenario where it is needed currently is by the image editor, where+ * if we can't detect the MIME type, then the image can't be shown (or+ * edited) in the current browser anyway.+ */+ mimeType?: string;+ }+ | {+ type: "video";+ /**+ * An object URL that can be directly provided to the browser to get+ * it to render the image.+ *+ * This is a best effort basis. Not all videos will be playable in all+ * browsers, so the file might still not be previewable.+ */+ videoURL: string;+ }+ | {+ type: "livePhoto";+ /**+ * Similar to the {@link imageURL} for type "image", except+ * as a promise since we might want to operate on the different+ * components of a live image in a staggered order.+ */+ imageURL: () => Promise<string>;+ /**+ * Similar to the {@link originalImageBlob} for type "image".+ */+ originalImageBlob: Blob;+ /**+ * Similar to the {@link videoURL} for type "video", except as+ * a promise since we might want to operate on the different+ * components of a live image in a staggered order.+ */+ videoURL: () => Promise<string>;+ };++/**+ * A class that tracks the state of in-progress downloads and conversions,+ * including caching them for subsequent retrieval if appropriate.+ *+ * External code can use it via its singleton instance, {@link downloadManager}.+ * The class will initialize itself on first use, however {@link logout} should+ * 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;+ /**+ * Local cache for thumbnail blobs.+ *+ * `undefined` indicates that the cache has not yet been initialized. It is+ * also possible that the cache might not be available, in which case it'd+ * be set to `null`.+ */+ private thumbnailCache: BlobCache | null | undefined;+ /**+ * An in-memory cache for an object URL to a file's thumbnail.+ *+ * This object URL can be directly used to render the thumbnail (e.g. in an+ * img tag). The entries are keyed by the file ID.+ */+ private thumbnailURLPromises = new Map<+ number,+ Promise<string | undefined>+ >();+ /**+ * An in-memory cache for an object URL to a file's original data.+ *+ * Unlike {@link thumbnailURLPromises}, there is no guarantee that the+ * browser will be able to render the original file (e.g. it might be in an+ * unsupported format). If a renderable URL is needed for the file,+ * {@link renderableSourceURLs} should be used instead.+ *+ * The entries are keyed by the file ID.+ */+ private fileURLPromises = new Map<number, Promise<string>>();+ /**+ * An in-memory cache for {@link RenderableSourceURLs} for a file.+ *+ * These are saved as a result of invocation of+ * {@link renderableSourceURLs}, which goes one step beyond+ * {@link fileURLPromises}, and also attempts to convert the downloaded file+ * into a URL that the browser (or the desktop app) is likely to be able to+ * render or play.+ *+ * The entries are keyed by file ID.+ */+ private renderableSourceURLPromises = new Map<+ number,+ Promise<RenderableSourceURLs>+ >();++ /**+ * A map from file ID to the progress (0-100%) of its active download (if+ * any).+ *+ * [Note: Tracking active file download progress in the UI]+ *+ * The download manager maintains a map of download progress for all files+ * which are being downloaded in a streaming manner (which is currently only+ * videos). The UI can observe this by using {@link useSyncExternalStore} in+ * combination with the {@link fileDownloadProgressSubscribe} and+ * {@link fileDownloadProgressSnapshot} methods of the download manager.+ */+ private fileDownloadProgress = new Map<number, number>();+ private fileDownloadProgressListeners: (() => void)[] = [];++ 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,+ );+ }+ }+ }++ /**+ * Reset the internal state of the download manager.+ */+ logout() {+ this.publicAlbumsCredentials = undefined;+ this.thumbnailURLPromises.clear();+ this.fileURLPromises.clear();+ this.renderableSourceURLPromises.clear();+ this.fileDownloadProgress.clear();+ this.fileDownloadProgressListeners = [];+ }++ /**+ * Set the credentials that should be used for download files when we're+ * running in the context of the public albums app.+ */+ setPublicAlbumsCredentials(+ credentials: PublicAlbumsCredentials | undefined,+ ) {+ this.publicAlbumsCredentials = credentials;+ }++ /**+ * See: [Note: Tracking active file download progress in the UI]+ */+ fileDownloadProgressSubscribe(onChange: () => void) {+ this.fileDownloadProgressListeners.push(onChange);+ return () => {+ this.fileDownloadProgressListeners =+ this.fileDownloadProgressListeners.filter((l) => l != onChange);+ };+ }++ /**+ * See: [Note: Tracking active file download progress in the UI]+ */+ fileDownloadProgressSnapshot() {+ return this.fileDownloadProgress;+ }++ private setFileDownloadProgress(progress: Map<number, number>) {+ this.fileDownloadProgress = progress;+ this.fileDownloadProgressListeners.forEach((l) => l());+ }++ /**+ * Resolves with an URL that points to the file's thumbnail.+ *+ * The thumbnail will be downloaded if needed (unless {@link cachedOnly} is+ * true). It will also be cached for subsequent fetches.+ *+ * The optional {@link cachedOnly} parameter can be set to indicate that+ * this is being called as part of a scroll, so the downloader should not+ * attempt to download the file but should instead fulfill the request from+ * the disk cache. This avoids an unbounded flurry of requests on scroll,+ * only downloading when the position has quiescized.+ *+ * The returned URL is actually an object URL, but it should not be revoked+ * since the download manager caches it for future use.+ *+ * If {@link cachedOnly} is false (the default), then this method will+ * indicate errors by throwing but will never return `undefined`.+ */+ 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) {+ // Do not cache a failed promise; allow follow-up calls to retry.+ 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;+ }++ /**+ * Returns the thumbnail data for a file, downloading it if needed.+ *+ * The data is cached on disk for subsequent fetches.+ *+ * @param file The {@link EnteFile} whose thumbnail we want.+ *+ * @param cachedOnly If true, then the thumbnail is not downloaded if it is+ * not already present in the disk cache.+ *+ * @returns The bytes of the thumbnail, as a {@link Uint8Array}. This method+ * can return `undefined` iff the thumbnail is not already cached, and+ * {@link cachedOnly} is set to `true`.+ */+ 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 decryptBlobBytes({ encryptedData, decryptionHeader }, file.key);+ };++ private async _downloadThumbnail(file: EnteFile) {+ if (this.publicAlbumsCredentials) {+ return publicAlbums_downloadThumbnail(+ file,+ this.publicAlbumsCredentials,+ );+ } else {+ return photos_downloadThumbnail(file);+ }+ }++ /**+ * Return a URL (and associated metadata) that can be used to show the given+ * {@link file} within the app, converting its format (on the fly) if needed+ * (if possible).+ *+ * See the documentation of {@link RenderableSourceURLs} for more details.+ */+ renderableSourceURLs = async (+ file: EnteFile,+ ): Promise<RenderableSourceURLs> => {+ let promise = this.renderableSourceURLPromises.get(file.id);+ if (!promise) {+ promise = createRenderableSourceURLs(+ file,+ this.fileURLDownloadAndCacheIfNeeded(file),+ );+ this.renderableSourceURLPromises.set(file.id, promise);+ }++ try {+ return await promise;+ } catch (e) {+ log.error("Failed to obtain renderableSourceURLs", e);+ this.renderableSourceURLPromises.delete(file.id);+ throw e;+ }+ };++ /**+ * Return a blob to the file's contents, downloading it needed.+ *+ * This is a convenience abstraction over {@link fileStream} that converts+ * it into a {@link Blob}.+ */+ async fileBlob(file: EnteFile, opts?: FileDownloadOpts) {+ return this.fileStream(file, opts).then((stream) =>+ this.blobWithInferredType(file, stream),+ );+ }++ /**+ * Return an stream to the file's contents, downloading it needed.+ *+ * Note that the results are not cached in-memory. That is, while the+ * request may be served from the existing item in the in-memory cache, if+ * it is not found and a download is required, that result will not be+ * cached for subsequent use.+ *+ * @param file The {@link EnteFile} whose data we want.+ *+ * @param opts Optional options to modify the download.+ */+ async fileStream(+ file: EnteFile,+ opts?: FileDownloadOpts,+ ): Promise<ReadableStream<Uint8Array> | null> {+ const cachedURL = this.fileURLPromises.get(file.id);+ if (cachedURL) {+ try {+ const url = await cachedURL;+ const res = await fetch(url);+ return res.body;+ } catch (e) {+ log.warn("Failed to use cached object URL", e);+ this.fileURLPromises.delete(file.id);+ }+ }++ return this.downloadFile(file, opts);+ }++ /**+ * A private variant of {@link fileStream} that also caches the results.+ */+ private async fileURLDownloadAndCacheIfNeeded(file: EnteFile) {+ const cachedURL = this.fileURLPromises.get(file.id);+ if (cachedURL) return cachedURL;++ const url = this.downloadFile(file)+ .then((stream) => this.blobWithInferredType(file, stream))+ .then((blob) => URL.createObjectURL(blob));+ this.fileURLPromises.set(file.id, url);++ try {+ return await url;+ } catch (e) {+ this.fileURLPromises.delete(file.id);+ throw e;+ }+ }++ private async downloadFile(+ file: EnteFile,+ opts?: FileDownloadOpts,+ ): Promise<ReadableStream<Uint8Array> | null> {+ log.info(`download attempted for file id ${file.id}`);++ const res = await wrapErrors(() => this._downloadFile(file, opts));++ if (+ file.metadata.fileType == FileType.image ||+ file.metadata.fileType == FileType.livePhoto+ ) {+ const encryptedData = new Uint8Array(+ await wrapErrors(() => res.arrayBuffer()),+ );++ const decrypted = await decryptStreamBytes(+ { encryptedData, decryptionHeader: file.file.decryptionHeader },+ file.key,+ );+ return new Response(decrypted).body;+ }++ const body = res.body;+ if (!body) return null;+ const reader = body.getReader();++ const onDownloadProgress = this.trackDownloadProgress(+ file.id,+ file.info?.fileSize,+ );++ const contentLength =+ parseInt(res.headers.get("Content-Length") ?? "") || 0;+ let downloadedBytes = 0;++ const { pullState, decryptionChunkSize } = await initChunkDecryption(+ file.file.decryptionHeader,+ file.key,+ );++ let leftoverBytes = new Uint8Array();++ return new ReadableStream({+ pull: async (controller) => {+ // Each time pull is called, we want to enqueue at least once.+ let didEnqueue = false;+ do {+ // done is a boolean and value is an Uint8Array. When done+ // is true value will be empty.+ const { done, value } = await wrapErrors(() =>+ reader.read(),+ );++ let data: Uint8Array;+ if (done) {+ data = leftoverBytes;+ } else {+ downloadedBytes += value.length;+ onDownloadProgress({+ loaded: downloadedBytes,+ total: contentLength,+ });++ data = new Uint8Array(+ leftoverBytes.length + value.length,+ );+ data.set(new Uint8Array(leftoverBytes), 0);+ data.set(new Uint8Array(value), leftoverBytes.length);+ }++ // data.length might be a multiple of decryptionChunkSize,+ // and we might need multiple iterations to drain it all.+ while (data.length >= decryptionChunkSize) {+ const decryptedData = await decryptStreamChunk(+ data.slice(0, decryptionChunkSize),+ pullState,+ );+ controller.enqueue(decryptedData);+ didEnqueue = true;+ data = data.slice(decryptionChunkSize);+ }++ if (done) {+ // Send off the remaining bytes without waiting for a+ // full chunk, no more bytes are going to come.+ if (data.length) {+ const decryptedData = await decryptStreamChunk(+ data,+ pullState,+ );+ controller.enqueue(decryptedData);+ }+ // Don't loop again even if we didn't enqueue.+ didEnqueue = true;+ controller.close();+ } else {+ // Save it for the next pull.++ // See: [Note: Revisit some Node.js types errors post 22+ // upgrade]+ //+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ // @ts-ignore+ leftoverBytes = data;+ }+ } while (!didEnqueue);+ },+ });+ }++ /**+ * Download the full contents of {@link file}, automatically choosing the+ * credentials for the logged in user or the public albums depending on the+ * current app context we are in.+ */+ private async _downloadFile(file: EnteFile, opts?: FileDownloadOpts) {+ if (this.publicAlbumsCredentials) {+ return publicAlbums_downloadFile(+ file,+ this.publicAlbumsCredentials,+ );+ } else {+ return photos_downloadFile(file, opts);+ }+ }++ private async blobWithInferredType(+ file: EnteFile,+ stream: ReadableStream<Uint8Array> | null,+ ) {+ const blob = await new Response(stream).blob();+ if (blob.type) return blob;++ try {+ const { mimeType } = await detectFileTypeInfoFromChunk(+ async () =>+ new Uint8Array(await blob.slice(0, 4100).arrayBuffer()),+ fileFileName(file),+ );+ return mimeType ? blob.slice(0, blob.size, mimeType) : blob;+ } catch {+ return blob;+ }+ }++ private trackDownloadProgress(+ fileID: number,+ fileSize: number | undefined,+ ) {+ return (event: { loaded: number; total: number }) => {+ if (isNaN(event.total) || event.total === 0) {+ if (!fileSize) {+ return;+ }+ event.total = fileSize;+ }+ const progress = new Map(this.fileDownloadProgress);+ if (event.loaded === event.total) {+ progress.delete(fileID);+ } else {+ progress.set(+ fileID,+ Math.round((event.loaded * 100) / event.total),+ );+ }+ this.setFileDownloadProgress(progress);+ };+ }+}++/**+ * Singleton instance of {@link DownloadManager}.+ */+export const downloadManager = new DownloadManager();++/**+ * A custom Error that is thrown if a download fails during network I/O.+ *+ * [Note: Identifying network related errors during download]+ *+ * We dealing with code that touches the network, we often don't specifically+ * care about the specific error - there is a lot that can go wrong when a+ * network is involved - but need to identify if an error was in the network+ * related phase of an action, since these are usually transient and can be+ * dealt with more softly than other errors.+ *+ * To that end, network related phases of download operations are wrapped in+ * catches that intercept the error and wrap it in our custom+ * {@link NetworkDownloadError} whose presence can be checked using the+ * {@link isNetworkDownloadError} predicate.+ */+export class NetworkDownloadError extends Error {+ error: unknown;++ constructor(e: unknown) {+ super(+ `NetworkDownloadError: ${e instanceof Error ? e.message : String(e)}`,+ );++ // Cargo culted from+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition+ if (Error.captureStackTrace)+ Error.captureStackTrace(this, NetworkDownloadError);++ this.error = e;+ }+}++export const isNetworkDownloadError = (e: unknown) =>+ e instanceof NetworkDownloadError;++/**+ * A helper function to convert all rejections of the given promise {@link op}+ * into {@link NetworkDownloadError}s.+ */+const wrapErrors = <T>(op: () => Promise<T>) =>+ op().catch((e: unknown) => {+ throw new NetworkDownloadError(e);+ });++/**+ * Create and return a {@link RenderableSourceURLs} for the given {@link file},+ * where {@link originalFileURLPromise} is a promise that resolves with an+ * (object) URL to the contents of the original file.+ */+const createRenderableSourceURLs = async (+ file: EnteFile,+ originalFileURLPromise: Promise<string>,+): Promise<RenderableSourceURLs> => {+ const originalFileURL = await originalFileURLPromise;+ const fileBlob = await fetch(originalFileURL).then((res) => res.blob());+ const fileName = fileFileName(file);+ const fileType = file.metadata.fileType;++ switch (fileType) {+ case FileType.image: {+ const convertedBlob = await renderableImageBlob(fileBlob, fileName);+ const imageURL =+ convertedBlob === fileBlob+ ? originalFileURL+ : URL.createObjectURL(convertedBlob);+ const originalImageBlob = fileBlob;+ const mimeType = convertedBlob.type;+ return { type: "image", imageURL, originalImageBlob, mimeType };+ }++ case FileType.livePhoto: {+ const livePhoto = await decodeLivePhoto(fileName, fileBlob);+ const originalImageBlob = new Blob([livePhoto.imageData]);++ const imageURL = async () =>+ URL.createObjectURL(+ await renderableImageBlob(+ originalImageBlob,+ livePhoto.imageFileName,+ ),+ );++ const videoURL = () =>+ playableVideoURL(+ file,+ livePhoto.videoFileName,+ new Blob([livePhoto.videoData]),+ );++ return { type: "livePhoto", imageURL, originalImageBlob, videoURL };+ }++ case FileType.video: {+ const videoURL = await playableVideoURL(file, fileName, fileBlob);+ return { type: "video", videoURL };+ }++ default: {+ throw new Error(`Unsupported file type ${fileType}`);+ }+ }+};++/**+ * The various photos_* functions are used for the actual downloads when+ * we're running in the context of the the photos app.+ */+const photos_downloadThumbnail = async (file: EnteFile) => {+ const customOrigin = await customAPIOrigin();++ const getThumbnail = async () => {+ if (customOrigin) {+ // See: [Note: Passing credentials for self-hosted file fetches]+ 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());+};++interface FileDownloadOpts {+ /**+ * `true` if the request is for a background task. These are considered less+ * latency sensitive than user initiated interactive requests.+ *+ * See: [Note: User initiated vs background downloads of files].+ *+ * This parameter is ignored for requests made when using public albums+ * credentials to download files; those are always considered interactive.+ */+ background?: boolean;+}++/**+ * Download the full contents of the given {@link EnteFile}+ */+const photos_downloadFile = async (+ file: EnteFile,+ opts?: FileDownloadOpts,+): Promise<Response> => {+ const { background } = opts ?? {};++ const customOrigin = await customAPIOrigin();++ // [Note: Passing credentials for self-hosted file fetches]+ //+ // Fetching files (or thumbnails) in the default self-hosted Ente+ // configuration involves a redirection:+ //+ // 1. The browser makes a HTTP GET to a museum with credentials. Museum+ // inspects the credentials, in this case the auth token, and if they're+ // valid, returns a HTTP 307 redirect to the pre-signed S3 URL that to+ // the file in the configured S3 bucket.+ //+ // 2. The browser follows the redirect to get the actual file. The URL is+ // pre-signed, i.e. already has all credentials needed to prove to the S3+ // object storage that it should serve this response.+ //+ // For the first step normally we'd pass the auth the token via the+ // "X-Auth-Token" HTTP header. In this case though, that would be+ // problematic because the browser preserves the request headers when it+ // follows the HTTP 307 redirect, and the "X-Auth-Token" header also gets+ // sent to the redirected S3 request made in second step.+ //+ // To avoid this, we pass the token as a query parameter. Generally this is+ // not a good idea, but in this case (a) the URL is not a user visible one+ // and (b) even if it gets logged, it'll be in the self-hosters own service.+ //+ // Note that Ente's own servers don't have these concerns because we use a+ // slightly different flow involving a proxy instead of directly connecting+ // to the S3 storage.+ //+ // 1. The web browser makes a HTTP GET request to a proxy passing it the+ // credentials in the "X-Auth-Token".+ //+ // 2. The proxy then does both the original steps: (a). Use the credentials+ // to get the pre-signed URL, and (b) fetch that pre-signed URL and+ // stream back the response.+ //+ // [Note: User initiated vs background downloads of files]+ //+ // The faster proxy approach is used for interactive requests to reduce the+ // latency for the user (e.g. when the user is waiting to see a full+ // resolution file). It can be faster than a direct connection as the proxy+ // is network-nearer to the user (See: [Note: Faster uploads via workers])+ //+ // For background processing (e.g., ML indexing, HLS generation), the direct+ // S3 connection (as what'd happen when self hosting) gets used.++ const getFile = async () => {+ if (customOrigin || background) {+ const token = await ensureAuthToken();+ const url = await apiURL(`/files/download/${file.id}`, { token });+ return fetch(url, { headers: publicRequestHeaders() });+ } else {+ return fetch(`https://files.ente.io/?fileID=${file.id}`, {+ headers: await authenticatedRequestHeaders(),+ });+ }+ };++ return retryEnsuringHTTPOk(getFile);+};++/**+ * The various publicAlbums_* functions are used for the actual downloads when+ * we're running in the context of the the public albums app.+ */+const publicAlbums_downloadThumbnail = async (+ file: EnteFile,+ credentials: PublicAlbumsCredentials,+) => {+ const customOrigin = await customAPIOrigin();++ const getThumbnail = async () => {+ if (customOrigin) {+ // See: [Note: Passing credentials for self-hosted file fetches]+ 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());+};++const publicAlbums_downloadFile = async (+ file: EnteFile,+ credentials: PublicAlbumsCredentials,+) => {+ const customOrigin = await customAPIOrigin();++ const getFile = () => {+ if (customOrigin) {+ // See: [Note: Passing credentials for self-hosted file fetches]+ const { accessToken, accessTokenJWT } = credentials;+ const params = new URLSearchParams({+ accessToken,+ ...(accessTokenJWT && { accessTokenJWT }),+ });+ return fetch(+ `${customOrigin}/public-collection/files/download/${file.id}?${params.toString()}`,+ );+ } else {+ return fetch(+ `https://public-albums.ente.io/download/?fileID=${file.id}`,+ {+ headers:+ authenticatedPublicAlbumsRequestHeaders(credentials),+ },+ );+ }+ };++ return retryEnsuringHTTPOk(getFile);+};diff --git a/web/apps/albums/vendor/ente-gallery/services/exif.ts b/web/apps/albums/vendor/ente-gallery/services/exif.tsnew file mode 100644index 0000000000..833c8487fd--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/exif.ts@@ -0,0 +1,666 @@+import { inWorker } from "ente-base/env";+import {+ parseMetadataDate,+ type ParsedMetadata,+ type ParsedMetadataDate,+} from "ente-media/file-metadata";+import ExifReader from "exifreader";++/**+ * Extract Exif and other metadata from the given file.+ *+ * [Note: Exif]+ *+ * Exif is a standard for metadata embedded in photos. Exif tags arise from the+ * TIFF specification but now can be found in other file formats, notably JPG,+ * PNG, AVI, MOV, TIFF-based RAW images (and TIFF itself)+ *+ * The standard uses "Exif" (not "EXIF") to refer to itself. We do the same.+ *+ * Exif is now commonly used as a synedoche for all forms of metadata that gets+ * embedded in a file, and this is also how we use the term. So these functions+ * extract and operate on not just Exif tags, but also XMP (XML metadata+ * embedded in images) and IPTC (another metadat standard) tags.+ *+ * A list for metadata tags can be found in exiftool's documentation:+ * https://exiftool.org/TagNames+ *+ * The library we use is https://github.com/mattiasw/ExifReader.+ */+export const extractExif = async (file: File) =>+ await extractRawExif(file).then(parseExif);++/**+ * Parse an already extracted {@link RawExifTags}.+ *+ * See: {@link extractExif}. This function does just the parsing step, for use+ * when we've already extracted the raw data.+ */+export const parseExif = (tags: RawExifTags) => {+ const location = parseLocation(tags);+ const creationDate = parseCreationDate(tags);+ const dimensions = parseDimensions(tags);+ const description = parseDescription(tags);+ const camera = parseCamera(tags);++ const metadata: ParsedMetadata = dimensions ?? {};+ if (creationDate) metadata.creationDate = creationDate;+ if (location) metadata.location = location;+ if (description) metadata.description = description;+ if (camera?.make) metadata.cameraMake = camera.make;+ if (camera?.model) metadata.cameraModel = camera.model;+ return metadata;+};++/**+ * Parse GPS location from the metadata embedded in the file.+ *+ * - If a location is returned, then both latitude and longitude will be+ * defined.+ * - NaNs are ignored, and treated as if they are not defined.+ */+const parseLocation = (tags: RawExifTags) => {+ const latitude = tags.gps?.Latitude;+ const longitude = tags.gps?.Longitude;++ if (latitude === undefined || longitude === undefined) return undefined;+ if (Number.isNaN(latitude) || Number.isNaN(longitude)) return undefined;++ return { latitude, longitude };+};++/**+ * Parse a single "best" creation date for an image from the metadata embedded+ * in the file.+ *+ * A file has multiple types of metadata, and each of these has multiple types+ * of dates, so we use some an a heuristic ordering (based on experience with+ * the photos we find out in the wild) to pick a "best" date.+ */+const parseCreationDate = (tags: RawExifTags) => {+ const { DateTimeOriginal, DateTimeDigitized, MetadataDate, DateTime } =+ parseDates(tags);+ return DateTimeOriginal ?? DateTimeDigitized ?? MetadataDate ?? DateTime;+};++/**+ * Dates extracted from the Exif and other metadata embedded in a file.+ *+ * These are the dates corresponding to the various options we show to the user+ * for the "Fix date" functionality. These don't come solely from the Exif but+ * from all forms of metadata we support (Exif, XMP, IPTC). They roughly+ * correspond to the three Exif DateTime* tags, and the XMP MetadataDate tag.+ */+interface ParsedExifDates {+ DateTimeOriginal: ParsedMetadataDate | undefined;+ DateTimeDigitized: ParsedMetadataDate | undefined;+ DateTime: ParsedMetadataDate | undefined;+ MetadataDate: ParsedMetadataDate | undefined;+}++/**+ * Extract dates from Exif and other metadata for the given file.+ */+export const extractExifDates = (file: File): Promise<ParsedExifDates> =>+ extractRawExif(file).then(parseDates);++/**+ * Parse all date related fields from the metadata embedded in the file,+ * grouping them into chunks that somewhat reflect the Exif ontology.+ */+const parseDates = (tags: RawExifTags) => {+ // Ignore dates whose epoch is 0.+ //+ // Some customers (not sure how prevalent this is) reported photos with Exif+ // dates set to "0000:00:00 00:00:00". Ignore any date whose timestamp is 0+ // so that we try with a subsequent (possibly correct) date in the sequence.+ //+ // Filter out a known corrupted date value, "4501:01:01 00:00:00".+ // Certain devices default to this bogus timestamp, so skip it to allow other dates.+ const valid = (d: ParsedMetadataDate | undefined) => {+ if (!d?.timestamp) return undefined;+ if (d.dateTime === "4501-01-01T00:00:00.000") return undefined;+ return d;+ };++ const exif = parseExifDates(tags);+ const iptc = parseIPTCDates(tags);+ const xmp = parseXMPDates(tags);++ return {+ DateTimeOriginal:+ valid(xmp.DateTimeOriginal) ??+ valid(iptc.DateTimeOriginal) ??+ valid(exif.DateTimeOriginal) ??+ valid(xmp.DateCreated),+ DateTimeDigitized:+ valid(xmp.DateTimeDigitized) ??+ valid(iptc.DateTimeDigitized) ??+ valid(exif.DateTimeDigitized) ??+ valid(xmp.CreateDate),+ DateTime: valid(xmp.DateTime ?? exif.DateTime ?? xmp.ModifyDate),+ MetadataDate: valid(xmp.MetadataDate),+ };+};++/**+ * Parse a date from an Exif date and offset tag combination.+ *+ * @param tags Metadata tags associated with a file.+ *+ * @param dateTag The name of the date tag to use.+ *+ * @param offsetTag The name of the offset tag corresponding to {@link dateTag}.+ *+ * @returns a {@link Date} (UTC epoch milliseconds).+ *+ * [Note: Exif dates]+ *+ * The most important bit we usually wish out of Exif is the date and time when+ * the photo was taken. The Exif specification has the following tags related to+ * photo's date:+ *+ * - DateTimeOriginal+ * - DateTimeDigitized (aka "CreateDate")+ * - DateTime (aka "ModifyDate")+ *+ * DateTimeOriginal is meant to signify best when the original image was taken,+ * and we use it as the photo's creation date whenever it is present. If not, we+ * fallback to DateTimeDigitized or DateTime (in that order).+ *+ * Each of these is a string of the format+ *+ * YYYY:MM:DD HH:mm:ss+ *+ * where+ *+ * YYYY 4 digit (zero padded) year+ * MM 2 digit (zero padded) month, with Jan as 01 and Dec as 12.+ * DD 2 digit (zero padded) day of the month (1 to 31)+ * HH 2 digit (zero padded) hours since midnight (00 to 23)+ * mm 2 digit (zero padded) minutes (00 to 59)+ * ss 2 digit (zero padded) seconds (00 to 59)+ *+ * Additionally (and optionally), there are three SubSecTime* tags that provide+ * the fractional seconds (one for each of the above):+ *+ * - SubSecTimeOriginal+ * - SubSecTimeDigitized+ * - SubSecTime+ *+ * Each of which is a string specifying the fractional digits.+ *+ * The dates are all in the local time of the place where the photo was taken.+ * To convert these to UTC, we also need to know the offset from UTC of that+ * local time. This is provided by the three OffsetTime* tags (one for each of+ * the above):+ *+ * - OffsetTimeOriginal+ * - OffsetTimeDigitized+ * - OffsetTime+ *+ * Each of these is a string of the format+ *+ * ±HH:mm+ *+ * denoting the signed hour and minute offset from UTC.+ *+ * Note that these OffsetTime* tags are relatively new additions (prior to+ * smartphones, cameras did not have a good way of knowing their TZ), and most+ * old photos will not have this information. In such cases, we assume that+ * these photos are in the local time where this code is running. This is+ * manifestly going to be incorrect in some cases, but it is a better assumption+ * than assuming UTC, which, while deterministic, is going to incorrect in an+ * overwhelming majority of cases.+ */+const parseExifDates = ({ exif }: RawExifTags) => ({+ DateTimeOriginal: parseExifDate(+ exif?.DateTimeOriginal,+ exif?.SubSecTimeOriginal,+ exif?.OffsetTimeOriginal,+ ),+ DateTimeDigitized: parseExifDate(+ exif?.DateTimeDigitized,+ exif?.SubSecTimeDigitized,+ exif?.OffsetTimeDigitized,+ ),+ DateTime: parseExifDate(exif?.DateTime, exif?.SubSecTime, exif?.OffsetTime),+});++const parseExifDate = (+ dateTag: ExifReader.StringArrayTag | undefined,+ subSecTag: ExifReader.StringArrayTag | undefined,+ offsetTag: ExifReader.StringArrayTag | undefined,+) => {+ const [dateString] = dateTag?.value ?? [];+ if (!dateString) return undefined;++ const [subSecString] = subSecTag?.value ?? [];+ const [offsetString] = offsetTag?.value ?? [];++ // Perform minor syntactic changes to the Exif date, and add the optional+ // offset, to construct a string in the Javascript date time string format.+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format+ //+ // YYYY:MM:DD HH:mm:ss±HH:mm+ // YYYY-MM-DDTHH:mm:ss±HH:mm+ //+ // When the offset string is missing, the date time is interpreted as local+ // time. This is the behaviour we want.+ //+ // For details see [Note: Exif dates]++ return parseMetadataDate(+ dateString.replace(":", "-").replace(":", "-").replace(" ", "T") ++ (subSecString ? "." + subSecString : "") ++ (offsetString ?? ""),+ );+};++/**+ * Parse date related tags from XMP.+ *+ * The XMP information in the file can have the date related information in tags+ * spread across multiple namespaces.+ *+ * For a list of XMP tags, see https://exiftool.org/TagNames/XMP.html.+ */+const parseXMPDates = ({ xmp }: RawExifTags) => ({+ /* XMP namespace is indicated for each group */+ // exif:+ DateTimeOriginal: parseXMPDate(xmp?.DateTimeOriginal),+ DateTimeDigitized: parseXMPDate(xmp?.DateTimeDigitized),+ // exif: or tiff:+ DateTime: parseXMPDate(xmp?.DateTime),+ // xmp:+ CreateDate: parseXMPDate(xmp?.CreateDate),+ ModifyDate: parseXMPDate(xmp?.ModifyDate),+ MetadataDate: parseXMPDate(xmp?.MetadataDate),+ // photoshop:+ DateCreated: parseXMPDate(xmp?.DateCreated),+});++/**+ * Parse an XMP date tag.+ *+ * [Note: XMP dates]+ *+ * XMP dates use a format same as the ISO-8601 format that is used by JavaScript+ * as its date time string format.+ *+ * YYYY-MM-DDThh:mm:ss.sTZD+ *+ * The main difference being, unlike JavaScript, all of the above components+ * except YYYY are optional. In practice, browsers gracefully handle these+ * scenarios, so we can directly use the JavaScript date constructor.+ *+ * References:+ * - https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata#date-value-type+ * - https://developer.adobe.com/xmp/docs/XMPNamespaces/XMPDataTypes/#date+ */+const parseXMPDate = (xmpTag: ExifReader.XmpTag | undefined) => {+ if (!xmpTag) return undefined;+ const s = xmpTag.value;+ if (typeof s != "string") return undefined;++ return parseMetadataDate(s);+};++/**+ * Parse date related tags from IPTC.+ */+const parseIPTCDates = ({ iptc }: RawExifTags) => ({+ DateTimeOriginal: parseIPTCDate(+ iptc?.["Date Created"],+ iptc?.["Time Created"],+ ),+ DateTimeDigitized: parseIPTCDate(+ iptc?.["Digital Creation Date"],+ iptc?.["Digital Creation Time"],+ ),+});++/**+ * Parse an IPTC date tag.+ *+ * [Note: IPTC dates]+ *+ * IPTC date time values are split across two tag:+ *+ * - A tag containing the date as as 8 digit number of the form `YYYYMMDD`.+ *+ * - A tag containing the time as an 11 character string of the form+ * `HHMMSS±HHMM`.+ *+ * They lack separators, but together these tags are meant to encode the same+ * information as the ISO 8601 date format (that XMP and JavaScript also use).+ *+ * Reference:+ * - http://www.iptc.org/std/IIM/4.1/specification/IIMV4.1.pdf+ *+ * ---+ *+ * @param dateTag The tag containing the date part of the date.+ *+ * @param timeTag The tag containing the time part of the date.+ */+const parseIPTCDate = (+ dateTag: ExifReader.NumberArrayTag | undefined,+ timeTag: ExifReader.NumberArrayTag | undefined,+) => {+ // The library we use (ExifReader) parses them into a usable representation,+ // which we can use directly. Some notes:+ //+ // - There are currently no separate TypeScript types for the IPTC tags, and+ // instead they are listed as part of the ExifTags.+ //+ // - For the date, whenever possible ExifReader parses the raw data into a+ // description of the form 'YYYY-MM-DD' (See `getCreationDate` in its+ // source code).+ //+ // - For the time, whenever possible ExifReader parses the raw data into a+ // description either of the form 'HH:mm:ss` or `HH:mm:ss±HH:mm` (See+ // `getCreationTime` in its source code).+ if (!dateTag) return undefined;+ let s = dateTag.description;++ if (timeTag) s = s + "T" + timeTag.description;++ return parseMetadataDate(s);+};++/**+ * Parse the width and height of the image from the metadata embedded in the+ * file, taking into account any orientation tags that are also present.+ */+const parseDimensions = (tags: RawExifTags) => {+ // Go through all possibilities in order, returning the first pair with both+ // the width and height defined, and non-zero.++ const pair = (w: number | undefined, h: number | undefined) =>+ w && h ? { width: w, height: h } : undefined;++ const shouldSwapForExifOrientation = (orientation: number | undefined) => {+ switch (orientation) {+ case 5:+ case 6:+ case 7:+ case 8:+ return true;+ default:+ return false;+ }+ };++ const shouldSwapForXMPOrientation = (+ orientation: ExifReader.XmpTag["value"] | undefined,+ ) => {+ if (typeof orientation != "string") return false;+ switch (orientation) {+ case "5":+ case "6":+ case "7":+ case "8":+ return true;+ default:+ return false;+ }+ };++ // 1. Use the width and height from the file itself (e.g. JPEG data).++ let wh =+ pair(+ tags.file?.["Image Width"]?.value,+ tags.file?.["Image Height"]?.value,+ ) ??+ pair(+ tags.pngFile?.["Image Width"]?.value,+ tags.pngFile?.["Image Height"]?.value,+ ) ??+ pair(+ tags.gif?.["Image Width"]?.value,+ tags.gif?.["Image Height"]?.value,+ ) ??+ pair(tags.riff?.ImageWidth?.value, tags.riff?.ImageHeight?.value);+ if (wh) {+ // The dimensions read from the file headers can still correspond to+ // the un-rotated pixel matrix. For orientations 5-8, we need to swap+ // them to represent the display dimensions used by masonry.+ const shouldSwap =+ shouldSwapForExifOrientation(tags.exif?.Orientation?.value) ||+ (tags.exif?.Orientation?.value == undefined &&+ shouldSwapForXMPOrientation(tags.xmp?.Orientation?.value));+ return shouldSwap ? { width: wh.height, height: wh.width } : wh;+ }++ // 2. Exif dimensions, taking Orientation also into account if needed.++ wh =+ pair(+ tags.exif?.ImageWidth?.value,+ /* The Exif spec calls it ImageLength, not ImageHeight. */+ tags.exif?.ImageLength?.value,+ ) ??+ pair(+ tags.exif?.PixelXDimension?.value,+ tags.exif?.PixelYDimension?.value,+ );+ if (wh) {+ // Exif Orientation tags can have the following values:+ //+ // 1 = Horizontal (normal)+ // 2 = Mirror horizontal+ // 3 = Rotate 180+ // 4 = Mirror vertical+ // 5 = Mirror horizontal and rotate 270 CW+ // 6 = Rotate 90 CW+ // 7 = Mirror horizontal and rotate 90 CW+ // 8 = Rotate 270 CW+ //+ // Ref: https://exiftool.org/TagNames/EXIF.html++ const swap = shouldSwapForExifOrientation(+ tags.exif?.Orientation?.value,+ );++ return swap ? { width: wh.height, height: wh.width } : wh;+ }++ // 3. XMP dimensions, taking Orientation also into account if needed.++ wh =+ pair(+ parseXMPNum(tags.xmp?.ImageWidth),+ parseXMPNum(tags.xmp?.ImageLength),+ ) ??+ pair(+ parseXMPNum(tags.xmp?.PixelXDimension),+ parseXMPNum(tags.xmp?.PixelYDimension),+ );++ if (wh) {+ // The Orientation present in XMP (as a TIFF tag) also uses the same+ // constants as Exif above.+ //+ // Ref: https://exiftool.org/TagNames/XMP.html++ const swap = shouldSwapForXMPOrientation(tags.xmp?.Orientation?.value);++ return swap ? { width: wh.height, height: wh.width } : wh;+ }++ return undefined;+};++/**+ * Try to parse the given XMP tag as a number.+ */+const parseXMPNum = (xmpTag: ExifReader.XmpTag | undefined) => {+ if (!xmpTag) return undefined;+ const s = xmpTag.value;+ if (typeof s != "string") return undefined;++ const n = parseInt(s, 10);+ if (isNaN(n)) return undefined;+ return n;+};++export type RawExifTags = Omit<ExifReader.ExpandedTags, "Thumbnail" | "xmp"> & {+ xmp?: ExifReader.XmpTags;+};++/**+ * Extract "raw" exif and other metadata from the given file.+ *+ * @param blob A {@link Blob} containing the data of an {@link EnteFile}.+ *+ * @return A JSON object containing the raw exif and other metadata that was+ * found in the given {@link blob}.+ *+ * ---+ *+ * [Note: Defining "raw" Exif]+ *+ * We wish for a canonical "raw" JSON representing all the Exif data associated+ * with a file. This goal is tricky to achieve because:+ *+ * - While Exif itself is a standard, with a standard set of tags (a numeric+ * id), in practice vendors can use tags more than what are currently listed+ * in the standard.+ *+ * - We're not just interested in Exif tags, but rather at all forms of metadata+ * (e.g. XMP, IPTC) that can be embedded in a file.+ *+ * By default, the library we use (ExifReader) returns a merged object+ * containing all tags it understands from all forms of metadata that it knows+ * about.+ *+ * Since it only returns the tags it understands, it acts an an implicit+ * whitelist. This implicit whitelist behaviour can be turned off by specifying+ * the `includeUnknown` flag, but for our case it is useful since it acts as a+ * safeguard against extracting an unbounded amounts of data (for example, there+ * is an Exif tag for thumbnails. While we specifically filter out that+ * particular tag, it is not hard to imagine some other unforeseen vendor+ * specific tag containing a similarly large amounts of embedded data).+ *+ * So we keep the default behaviour of returning only the tags that the library+ * knows about. Luckily for us, it returns all the XMP tags even if this flag is+ * specified, and that is one place where we'd like unknown tags so that we can+ * selectively start adding support for them.+ *+ * The other default behaviour, of returning a merged object, is a bit more+ * problematic for our use case, since it loses information. Thus, to keep+ * things more deterministic, we specify the `expanded` flag which returns all+ * these different forms of metadata separately.+ *+ * That's for the tags we get. Now to their contents. Generally for each tag+ * (but not for always), we get an entry with an "id", "value" (e.g. the raw+ * bytes), and a "description" (which is the raw data parsed to a form that is+ * more usable). Technically speaking, the value is the raw data we want, but in+ * some cases, the availability of a pre-parsed description will be convenient+ * too. So we don't prune anything, and keep all three.+ *+ * All this means we end up with a JSON whose exact structure is tied to the+ * library we're using (ExifReader), or even its version (the library reserves+ * the right to change the formatting of the "description" fields in minor+ * version updates).+ *+ * So this is not really "raw" Exif. But with that caveat out of the way,+ * practically this should be raw enough given the tradeoffs mentioned above,+ * while allowing us to consume this JSON in arbitrary clients without needing+ * to know about ExifReader specifically.+ */+export const extractRawExif = async (blob: Blob): Promise<RawExifTags> => {+ // The browser's DOMParser is not available in web workers. So if this+ // function gets called in from a web worker, then it would not be able to+ // parse XMP tags.+ //+ // There is a way around this problem, by also installing ExifReader's+ // optional peer dependency "@xmldom/xmldom". But since we currently have no+ // use case for calling this code in a web worker, we just abort immediately+ // to let future us know that we need to install it.+ if (inWorker())+ throw new Error("DOMParser is not available in web workers");++ const tags = await ExifReader.load(await blob.arrayBuffer(), {+ async: true,+ expanded: true,+ });++ // Remove the embedded thumbnail (if any).+ delete tags.Thumbnail;+ delete tags.exif?.Thumbnail;++ // Remove the embedded MPF images (if any).+ //+ // The TypeScript definition is out of data and doesn't include the top+ // level 'mpf', so we need to cast. From the source:+ //+ // > The images can be accessed by the tags.Images array (tags.mpf.Images if+ // > using expanded: true).+ //+ delete (tags as Record<string, unknown>).mpf;++ // Remove the raw XMP (if any).+ //+ // The `includeUnknown` flag does not have any effect on the XMP parser, so+ // we already get all the key value pairs in the XMP as part of the "xmp"+ // object, retaining the raw string is unnecessary.+ //+ // We need to cast to remove the non-optional _raw property. Be aware that+ // this means that from this point onwards, the TypeScript type is out of+ // sync with the actual value (TypeScript type says _raw is always present,+ // while the actual value doesn't have it).+ delete (tags.xmp as Partial<typeof tags.xmp>)?._raw;++ return tags;+};++/**+ * Return a number from a raw Exif tag value.+ *+ * Some numeric Exif values are stored as arrays of two numbers [p, q]+ * representing a rational number p/q. ExifReader usually converts this and for+ * us, but not always.+ *+ * This function takes such potentially ambiguous (already converted or not)+ * values and returns a number.+ */+export const tagNumericValue = (+ tag: ExifReader.NumberTag | ExifReader.NumberArrayTag,+) => {+ const v = tag.value;+ return Array.isArray(v) ? (v[0] ?? 0) / (v[1] ?? 1) : v;+};++const parseCamera = (tags: RawExifTags) => {+ const makeDescription = tags.exif?.Make?.description;+ const modelDescription = tags.exif?.Model?.description;+ const make = makeDescription?.trim();+ const model = modelDescription?.trim();+ if (!make && !model) return undefined;+ return { make, model };+};++/**+ * Parse the description for an image from the metadata embedded in the file.+ *+ * This function will read the description from the following fields, in order:+ *+ * 1. XMP-dc:description+ * 2. IPTC | Caption/Abstract (120)+ * 3. EXIF IFD0 | 0x010e | ImageDescription+ *+ * For an overview of why this ordering was chosen, see+ * https://github.com/ente-io/ente/discussions/3857#discussioncomment-11764990+ */+const parseDescription = (tags: RawExifTags) =>+ // While the TypeScript tags for these three fields are varying (The XMP one+ // doesn't have a static type, the IPTC one is marked as a number array, and+ // the Exif one is a string array), for all three of these, the ExifReader+ // description property (not related to the image "description" in the sense+ // of this function) holds the singular string we're interested in.+ tags.xmp?.description?.description ??+ tags.iptc?.["Caption/Abstract"]?.description ??+ tags.exif?.ImageDescription?.description;diff --git a/web/apps/albums/vendor/ente-gallery/services/ffmpeg/constants.ts b/web/apps/albums/vendor/ente-gallery/services/ffmpeg/constants.tsnew file mode 100644index 0000000000..dae03a9976--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/ffmpeg/constants.ts@@ -0,0 +1,5 @@+/* Ditto in the desktop app's code (used by the native FFmpeg invocation). */++export const ffmpegPathPlaceholder = "FFMPEG";+export const inputPathPlaceholder = "INPUT";+export const outputPathPlaceholder = "OUTPUT";diff --git a/web/apps/albums/vendor/ente-gallery/services/ffmpeg/index.ts b/web/apps/albums/vendor/ente-gallery/services/ffmpeg/index.tsnew file mode 100644index 0000000000..8c7817ee4e--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/ffmpeg/index.ts@@ -0,0 +1,322 @@+import { ensureElectron } from "ente-base/electron";+import log from "ente-base/log";+import type { Electron } from "ente-base/types/ipc";+import {+ toPathOrZipEntry,+ type FileSystemUploadItem,+ type UploadItem,+} from "ente-gallery/services/upload";+import {+ initiateConvertToMP4,+ readVideoStream,+ videoStreamDone,+} from "ente-gallery/utils/native-stream";+import {+ parseMetadataDate,+ type ParsedMetadata,+} from "ente-media/file-metadata";+import {+ ffmpegPathPlaceholder,+ inputPathPlaceholder,+ outputPathPlaceholder,+} from "./constants";+import { determineVideoDurationWeb, ffmpegExecWeb } from "./web";++/**+ * Generate a thumbnail for the given video using a Wasm FFmpeg running in a web+ * worker.+ *+ * This function is called during upload, when we need to generate thumbnails+ * for the new files that the user is adding.+ *+ * @param blob The input video blob.+ *+ * @returns JPEG data of the generated thumbnail.+ *+ * See also {@link generateVideoThumbnailNative}.+ */+export const generateVideoThumbnailWeb = async (blob: Blob) =>+ _generateVideoThumbnail((seekTime: number) =>+ ffmpegExecWeb(makeGenThumbnailCommand(seekTime), blob, "jpeg"),+ );++const _generateVideoThumbnail = async (+ thumbnailAtTime: (seekTime: number) => Promise<Uint8Array>,+) => {+ try {+ // Try generating thumbnail at seekTime 1 second.+ return await thumbnailAtTime(1);+ } catch {+ // If that fails, try again at the beginning. If even this throws, let+ // it fail.+ return await thumbnailAtTime(0);+ }+};++/**+ * Generate a thumbnail for the given video using a native FFmpeg binary bundled+ * with our desktop app.+ *+ * This function is called during upload, when we need to generate thumbnails+ * for the new files that the user is adding.+ *+ * @param dataOrPath The input video's data or the path to the video on the+ * user's local file system. See: [Note: Reading a UploadItem].+ *+ * @returns JPEG data of the generated thumbnail.+ *+ * See also {@link generateVideoThumbnailNative}.+ */+export const generateVideoThumbnailNative = async (+ electron: Electron,+ fsUploadItem: FileSystemUploadItem,+) =>+ _generateVideoThumbnail((seekTime: number) =>+ electron.ffmpegExec(+ makeGenThumbnailCommand(seekTime),+ toPathOrZipEntry(fsUploadItem),+ "jpeg",+ ),+ );++const makeGenThumbnailCommand = (seekTime: number) => ({+ default: _makeGenThumbnailCommand(seekTime, false),+ hdr: _makeGenThumbnailCommand(seekTime, true),+});++const _makeGenThumbnailCommand = (seekTime: number, forHDR: boolean) => [+ ffmpegPathPlaceholder,+ "-i",+ inputPathPlaceholder,+ // Seek to seekTime in the video.+ "-ss",+ `00:00:0${seekTime}`,+ // Take the first frame+ "-vframes",+ "1",+ // Apply a filter to this frame+ "-vf",+ [+ // Scale it to a maximum height of 720 keeping aspect ratio, ensuring+ // that the dimensions are even (subsequent filters require this).+ "scale=-2:720",+ forHDR+ ? // Apply a tonemap to ensure that thumbnails of HDR videos do+ // not look washed out. See: [Note: Tonemapping HDR to HD].+ [+ "zscale=transfer=linear",+ "tonemap=tonemap=hable:desat=0",+ "zscale=primaries=709:transfer=709:matrix=709",+ ]+ : [],+ ]+ .flat()+ .join(","),+ outputPathPlaceholder,+];++/**+ * Extract metadata from the given video.+ *+ * When we're running in the context of our desktop app _and_ we're passed an+ * upload item that resolves to a path of the user's file system, this uses the+ * native FFmpeg bundled with our desktop app. Otherwise it uses a Wasm build of+ * FFmpeg running in a web worker.+ *+ * This function is called during upload, when we need to extract the+ * "ffmetadata" of videos that the user is uploading.+ *+ * @param uploadItem The video item being uploaded.+ */+export const extractVideoMetadata = async (+ uploadItem: UploadItem,+): Promise<ParsedMetadata> => {+ const command = extractVideoMetadataCommand;+ return parseFFmpegExtractedMetadata(+ uploadItem instanceof File+ ? await ffmpegExecWeb(command, uploadItem, "txt")+ : await ensureElectron().ffmpegExec(+ command,+ toPathOrZipEntry(uploadItem),+ "txt",+ ),+ );+};++/**+ * The FFmpeg command to use to extract metadata from videos.+ *+ * Options:+ *+ * - `-c [short for codex] copy`+ * - copy is the [stream_specifier](ffmpeg.org/ffmpeg.html#Stream-specifiers)+ * - copies all the stream without re-encoding+ *+ * - `-map_metadata`+ * - http://ffmpeg.org/ffmpeg.html#Advanced-options (search for map_metadata)+ * - copies all stream metadata to the output+ *+ * - `-f ffmetadata`+ * - https://ffmpeg.org/ffmpeg-formats.html#Metadata-2+ * - dump metadata from media files into a simple INI-like utf-8 text file+ */+const extractVideoMetadataCommand = [+ ffmpegPathPlaceholder,+ "-i",+ inputPathPlaceholder,+ "-c",+ "copy",+ "-map_metadata",+ "0",+ "-f",+ "ffmetadata",+ outputPathPlaceholder,+];++/**+ * Convert the output produced by running the FFmpeg+ * {@link extractVideoMetadataCommand} into a {@link ParsedMetadata}.+ *+ * @param ffmpegOutput The bytes containing the output of the FFmpeg command.+ */+const parseFFmpegExtractedMetadata = (ffmpegOutput: Uint8Array) => {+ // The output is a utf8 INI-like text file with key=value pairs interspersed+ // with comments and newlines.+ //+ // https://ffmpeg.org/ffmpeg-formats.html#Metadata-2+ //+ // On Windows, while I couldn't find it documented anywhere, the generated+ // ffmetadata file uses Unix line separators ("\n"). But for the sake of+ // extra (albeit possibly unnecessary) safety, handle both \r\n and \n+ // separators in the split. See: [Note: ffmpeg newlines]++ const lines = new TextDecoder().decode(ffmpegOutput).split(/\r?\n/);+ const isPair = (xs: string[]): xs is [string, string] => xs.length == 2;+ const kvPairs = lines.map((property) => property.split("=")).filter(isPair);++ const kv = new Map(kvPairs);++ const result: ParsedMetadata = {};++ const creationDate =+ parseFFMetadataDate(kv.get("com.apple.quicktime.creationdate")) ??+ parseFFMetadataDate(kv.get("creation_time"));+ if (creationDate) result.creationDate = creationDate;++ const location =+ parseFFMetadataLocation(+ kv.get("com.apple.quicktime.location.ISO6709"),+ ) ?? parseFFMetadataLocation(kv.get("location"));+ if (location) result.location = location;++ return result;+};++/**+ * Parse a location string found in the FFmpeg metadata attributes.+ *+ * This is meant to parse either the "com.apple.quicktime.location.ISO6709"+ * (preferable) or the "location" key (fallback).+ */+const parseFFMetadataLocation = (s: string | undefined) => {+ if (!s) return undefined;++ const m = s.match(/(\+|-)\d+\.*\d+/g);+ if (!m) {+ log.warn(`Ignoring unparseable location string "${s}"`);+ return undefined;+ }++ const [latitude, longitude] = m.map(parseFloat);+ if (!latitude || !longitude) {+ log.warn(`Ignoring unparseable video metadata location string "${s}"`);+ return undefined;+ }++ return { latitude, longitude };+};++/**+ * Parse a date/time string found in the FFmpeg metadata attributes.+ *+ * This is meant to parse either the "com.apple.quicktime.creationdate"+ * (preferable) or the "creation_time" key (fallback).+ *+ * Both of these are expected to be ISO 8601 date/time strings, but we prefer+ * "com.apple.quicktime.creationdate" since it includes the time zone offset.+ */+const parseFFMetadataDate = (s: string | undefined) => {+ if (!s) return undefined;++ const d = parseMetadataDate(s);+ if (!d) {+ log.warn(`Ignoring unparseable video metadata date string "${s}"`);+ return undefined;+ }++ // While not strictly required, we retain the same behaviour as the image+ // Exif parser of ignoring dates whose epoch is 0.+ if (!d.timestamp) {+ log.warn(`Ignoring zero video metadata date string "${s}"`);+ return undefined;+ }++ return d;+};++/**+ * Extract the duration (in seconds) from the given video+ *+ * This is a sibling of {@link extractVideoMetadata}, except it tries to+ * determine the duration of the video. The duration is not part of the+ * "ffmetadata", and is instead a property of the video itself.+ *+ * @param uploadItem The video item being uploaded.+ *+ * @return the duration of the video in seconds (a floating point number).+ */+export const determineVideoDuration = async (+ uploadItem: UploadItem,+): Promise<number> =>+ uploadItem instanceof File+ ? determineVideoDurationWeb(uploadItem)+ : ensureElectron().ffmpegDetermineVideoDuration(+ toPathOrZipEntry(uploadItem),+ );++/**+ * Convert a video from a format that is not supported in the browser to MP4.+ *+ * This function is called when the user views a video or a live photo, and we+ * want to play it back. The idea is to convert it to MP4 which has much more+ * universal support in browsers.+ *+ * @param blob The video blob.+ *+ * @returns The mp4 video blob.+ */+export const convertToMP4 = async (blob: Blob): Promise<Blob | Uint8Array> => {+ const electron = globalThis.electron;+ if (electron) {+ return convertToMP4Native(electron, blob);+ } else {+ const command = [+ ffmpegPathPlaceholder,+ "-i",+ inputPathPlaceholder,+ "-preset",+ "ultrafast",+ outputPathPlaceholder,+ ];+ return ffmpegExecWeb(command, blob, "mp4");+ }+};++const convertToMP4Native = async (electron: Electron, blob: Blob) => {+ const token = await initiateConvertToMP4(electron, blob);+ const mp4Blob = await readVideoStream(electron, token).then((res) =>+ res.blob(),+ );+ await videoStreamDone(electron, token);+ return mp4Blob;+};diff --git a/web/apps/albums/vendor/ente-gallery/services/ffmpeg/web.ts b/web/apps/albums/vendor/ente-gallery/services/ffmpeg/web.tsnew file mode 100644index 0000000000..f49a7f3201--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/ffmpeg/web.ts@@ -0,0 +1,345 @@+import { FFFSType, FFmpeg } from "@ffmpeg/ffmpeg";+import { joinPath } from "ente-base/file-name";+import { newID } from "ente-base/id";+import log from "ente-base/log";+import type { FFmpegCommand } from "ente-base/types/ipc";+import { PromiseQueue } from "ente-utils/promise";+import { z } from "zod";+import {+ ffmpegPathPlaceholder,+ inputPathPlaceholder,+ outputPathPlaceholder,+} from "./constants";++/** Lazily initialized and loaded FFmpeg instance. */+let _ffmpeg: Promise<FFmpeg> | undefined;++/** Queue of in-flight requests. */+const _ffmpegTaskQueue = new PromiseQueue<Uint8Array | number>();++/**+ * Return the shared {@link FFmpeg} instance, lazily creating and loading it if+ * needed.+ */+const ffmpegLazy = (): Promise<FFmpeg> => (_ffmpeg ??= createFFmpeg());++const createFFmpeg = async () => {+ const ffmpeg = new FFmpeg();+ await ffmpeg.load({+ coreURL: "https://assets.ente.io/ffmpeg-core-0.12.10/ffmpeg-core.js",+ wasmURL: "https://assets.ente.io/ffmpeg-core-0.12.10/ffmpeg-core.wasm",+ });+ // This is too noisy to enable even during development. Uncomment to taste.+ // ffmpeg.on("log", (e) => log.debug(() => ["[ffmpeg]", e.message]));+ return ffmpeg;+};++/**+ * Run the given FFmpeg command using a Wasm FFmpeg running in a web worker.+ *+ * This is a sibling of {@link ffmpegExec} exposed by the desktop app in+ * `ipc.ts`. As a rough ballpark, currently the native FFmpeg integration in the+ * desktop app is 10-20x faster than the Wasm one.+ *+ * See: [Note: FFmpeg in Electron].+ *+ * @param command The FFmpeg command to execute.+ *+ * @param blob The input blob on which to run the command.+ *+ * @param outputFileExtension The extension of the (temporary) output file which+ * will be generated by the command.+ *+ * @returns The contents of the output file generated as a result of executing+ * {@link command} on {@link blob}.+ */+export const ffmpegExecWeb = async (+ command: FFmpegCommand,+ blob: Blob,+ outputFileExtension: string,+): Promise<Uint8Array> => {+ const ffmpeg = await ffmpegLazy();+ // Interleaving multiple ffmpeg.execs causes errors like+ //+ // > "Out of bounds memory access (evaluating 'Module["_malloc"](len)')"+ //+ // So serialize them using a promise queue.+ return _ffmpegTaskQueue.add(() =>+ ffmpegExec(ffmpeg, command, outputFileExtension, blob),+ ) as Promise<Uint8Array>;+};++/**+ * Determine the duration of the given video blob.+ *+ * This is a specialized variant of {@link ffmpegExecWeb} that uses the same+ * queue but internally uses ffprobe to try and determine the video's duration.+ *+ * @param blob The input blob on which to run the command, provided as a blob.+ *+ * @returns The duration of the {@link blob} (if it indeed is a video).+ */+export const determineVideoDurationWeb = async (+ blob: Blob,+): Promise<number> => {+ const ffmpeg = await ffmpegLazy();+ return _ffmpegTaskQueue.add(() =>+ ffprobeExecVideoDuration(ffmpeg, blob),+ ) as Promise<number>;+};++const ffmpegExec = async (+ ffmpeg: FFmpeg,+ command: FFmpegCommand,+ outputFileExtension: string,+ blob: Blob,+) => {+ const outputSuffix = outputFileExtension ? "." + outputFileExtension : "";+ const outputPath = newID("out_") + outputSuffix;++ // Exit status of the ffmpeg.exec invocation.+ // `0` if no error, `!= 0` if timeout (1) or error.+ let status: number | undefined;++ return withInputMount(ffmpeg, blob, async (inputPath) => {+ try {+ const startTime = Date.now();++ let resolvedCommand: string[];+ if (Array.isArray(command)) {+ resolvedCommand = command;+ } else {+ const isHDR = await isHDRVideo(ffmpeg, inputPath);+ resolvedCommand = isHDR ? command.hdr : command.default;+ }++ const cmd = substitutePlaceholders(+ resolvedCommand,+ inputPath,+ outputPath,+ );++ status = await ffmpeg.exec(cmd);+ if (status !== 0) {+ log.info(+ `[wasm] ffmpeg command failed with exit code ${status}: ${cmd.join(" ")}`,+ );+ throw new Error(+ `ffmpeg command failed with exit code ${status}`,+ );+ }++ const result = await ffmpeg.readFile(outputPath);+ if (typeof result == "string")+ throw new Error("Expected binary data");++ const ms = Date.now() - startTime;+ log.debug(() => `[wasm] ffmpeg ${cmd.join(" ")} (${ms} ms)`);+ return result;+ } finally {+ try {+ await ffmpeg.deleteFile(outputPath);+ } catch (e) {+ // Output file might not even exist if the command did not succeed,+ // so only log on success.+ if (status === 0) {+ log.error(`Failed to remove output ${outputPath}`, e);+ }+ }+ }+ });+};++const withInputMount = async <T>(+ ffmpeg: FFmpeg,+ blob: Blob,+ f: (inputPath: string) => Promise<T>,+): Promise<T> => {+ const mountDir = "/mount";+ const inputFileName = newID("in_");+ const inputPath = joinPath(mountDir, inputFileName);++ const inputFile = new File([blob], inputFileName);++ try {+ await ffmpeg.createDir(mountDir);+ await ffmpeg.mount(FFFSType.WORKERFS, { files: [inputFile] }, mountDir);++ return await f(inputPath);+ } finally {+ try {+ await ffmpeg.unmount(mountDir);+ } catch (e) {+ log.error(`Failed to remove mount ${mountDir}`, e);+ }+ try {+ await ffmpeg.deleteDir(mountDir);+ } catch (e) {+ log.error(`Failed to delete mount directory ${mountDir}`, e);+ }+ }+};++const substitutePlaceholders = (+ command: string[],+ inputFilePath: string,+ outputFilePath: string,+) =>+ command+ .map((segment) => {+ if (segment == ffmpegPathPlaceholder) {+ return undefined;+ } else if (segment == inputPathPlaceholder) {+ return inputFilePath;+ } else if (segment == outputPathPlaceholder) {+ return outputFilePath;+ } else {+ return segment;+ }+ })+ .filter((s) => s !== undefined);++const FFProbeOutputIsHDR = z.object({+ streams: z.array(z.object({ color_transfer: z.string().optional() })),+});++/**+ * A variant of the {@link isHDRVideo} function in the desktop app source (see+ * `ffmpeg.ts`), except here we have access to ffprobe and can use that instead+ * of parsing the ffmpeg stderr.+ *+ * See: [Note: Alternative FFmpeg command for HDR videos]+ *+ * @param inputFilePath The path to a video file on the FFmpeg FS.+ *+ * @returns `true` if this file is likely a HDR video. Exceptions are treated as+ * `false` to make this function safe to invoke without breaking the happy path.+ */+const isHDRVideo = async (ffmpeg: FFmpeg, inputFilePath: string) => {+ let jsonString: string | undefined;+ try {+ jsonString = await ffprobeOutput(+ ffmpeg,+ [+ ["-i", inputFilePath],+ // Show information about streams.+ "-show_streams",+ // Select the first video stream. This is not necessarily+ // correct in a multi stream file because the ffmpeg automatic+ // mapping will use the highest resolution stream, but short of+ // reinventing ffmpeg's resolution mechanism, it is a reasonable+ // assumption for our current heuristic check.+ ["-select_streams", "v:0"],+ // Output JSON+ ["-of", "json"],+ ["-o", "output.json"],+ ].flat(),+ "output.json",+ );++ const output = FFProbeOutputIsHDR.parse(JSON.parse(jsonString));+ switch (output.streams[0]?.color_transfer) {+ case "smpte2084":+ case "arib-std-b67":+ return true;+ default:+ return false;+ }+ } catch (e) {+ log.warn("Could not detect HDR status", e);+ if (jsonString) log.debug(() => ["ffprobe-output", jsonString]);+ return false;+ }+};++/**+ * Return the textual output produced by verbatim invoking the given ffprobe+ * {@link cmd} that is expected to writes to a file named {@link outputFilePath}+ * in the FFmpeg FS.+ *+ * The file generated at {@link outputFilePath} is removed in all cases.+ */+const ffprobeOutput = async (+ ffmpeg: FFmpeg,+ cmd: string[],+ outputPath: string,+) => {+ // Exit status of the ffmpeg.ffprobe invocation.+ // `0` if no error, `!= 0` if timeout (1) or error.+ let status: number | undefined;++ try {+ status = await ffmpeg.ffprobe(cmd);+ // Currently, ffprobe incorrectly returns status -1 on success.+ // https://github.com/ffmpegwasm/ffmpeg.wasm/issues/817+ if (status !== 0 && status != -1) {+ log.info(+ `[wasm] ffprobe command failed with exit code ${status}: ${cmd.join(" ")}`,+ );+ throw new Error(`ffprobe command failed with exit code ${status}`);+ }++ const result = await ffmpeg.readFile(outputPath, "utf8");+ if (typeof result != "string") throw new Error("Expected text data");++ return result;+ } finally {+ try {+ await ffmpeg.deleteFile(outputPath);+ } catch (e) {+ // Output file might not even exist if the command did not succeed,+ // so only log on success.+ if (status !== 0 && status != -1) {+ log.error(`Failed to remove output ${outputPath}`, e);+ }+ }+ }+};++const FFProbeOutputDuration = z.object({+ format: z.object({ duration: z.string() }),+});++const ffprobeExecVideoDuration = async (ffmpeg: FFmpeg, blob: Blob) =>+ withInputMount(ffmpeg, blob, async (inputPath) => {+ // Determine the video duration from the container, bypassing the issues+ // with stream selection.+ //+ // ffprobe -v error -show_entries format=duration -of+ // default=noprint_wrappers=1:nokey=1 input.mp4+ //+ // Source:+ // https://trac.ffmpeg.org/wiki/FFprobeTips#Formatcontainerduration+ //+ // Reference: https://ffmpeg.org/ffprobe.html+ //+ // Since we cannot grab the stdout easily, the command has been modified+ // to output to a file instead. However, in doing the command seems to+ // have become flaky - for certain videos, it outputs extra lines and+ // not just the duration. So we also switch to the JSON output for more+ // robust behaviour, and parse the duration from it.++ const jsonString = await ffprobeOutput(+ ffmpeg,+ [+ ["-i", inputPath],+ ["-v", "error"],+ ["-show_entries", "format=duration"],+ ["-of", "json"],+ ["-o", "output.json"],+ ].flat(),+ "output.json",+ );++ const durationString = FFProbeOutputDuration.parse(+ JSON.parse(jsonString),+ ).format.duration;++ const duration = parseFloat(durationString);+ if (isNaN(duration)) {+ const msg = "Could not parse video duration";+ log.warn(msg, durationString);+ throw new Error(msg);+ }+ return duration;+ });diff --git a/web/apps/albums/vendor/ente-gallery/services/file-data.ts b/web/apps/albums/vendor/ente-gallery/services/file-data.tsnew file mode 100644index 0000000000..3d7165c277--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/file-data.ts@@ -0,0 +1,428 @@+import { encryptBlob } from "ente-base/crypto";+import type { EncryptedBlobB64 } from "ente-base/crypto/types";+import {+ authenticatedPublicAlbumsRequestHeaders,+ authenticatedRequestHeaders,+ ensureOk,+ retryEnsuringHTTPOk,+ type PublicAlbumsCredentials,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import type { EnteFile } from "ente-media/file";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";++/**+ * [Note: File data APIs]+ *+ * Remote provides some APIs that talk in terms of "file data", which refers to+ * all the files (original or derived) associated with an {@link EnteFile}.+ *+ * For example, for each original image that the user uploads, there will be an+ * associated thumbnail file, potentially one or more preview files (optimized+ * for size or compatibility across devices), various ML embeddings generated+ * for that file, and possibly more such files in the future.+ *+ * There are specialized APIs for fetching and uploading the originals and the+ * thumbnails. But for the other associated data, we can use the file data APIs.+ */+type FileDataType =+ | "mldata" /* See: [Note: "mldata" format] */+ | "vid_preview" /* See: [Note: Video playlist and preview] */;++const RemoteFileData = z.object({+ /**+ * The ID of the {@link EnteFile} with which this file data is associated.+ */+ fileID: z.number(),+ /**+ * Base64 representation of the encrypted data. Its plaintext contents will+ * be specific to each file data type.+ */+ encryptedData: z.string(),+ /**+ * Base64 representation of the header that should be passed when decrypting+ * {@link encryptedData}. See the {@link decryptMetadata} function in the+ * crypto layer.+ */+ decryptionHeader: z.string(),+ /**+ * The epoch microseconds when this file data entry was last upserted.+ *+ * [Note: PUT "mldata" version check]+ *+ * When PUT-ting mldata onto remote, the client is expected to pass the+ * updated at of the existing {@link RemoteFileData} which it is updating+ * (this field), or 0 if the client is creating a new entity.+ *+ * This allows remote to detect and reject cases where the client is trying+ * to overwrite a version it hasn't yet pulled.+ *+ * About the optionality of this field: Newer museums are expected to always+ * provide the {@link updatedAt} in the response, but for ease of self+ * hosters we don't take a hard dependency on the latest museum and instead+ * allow this field to be optional. When it is not present, effectively+ * we'll pass 0 as {@link lastUpdatedAt} in the "mldata" PUT API call, but+ * since it's an old museum it'll anyway ignore it.+ *+ * > This note was added May 2025, and the optionality can be removed in a+ * > few months when museums should've updated (tag: Migration).+ */+ updatedAt: z.number().nullish().transform(nullToUndefined),+});++type RemoteFileData = z.infer<typeof RemoteFileData>;++/**+ * Fetch file data of a particular type for the given list of files.+ *+ * @param type The {@link FileDataType} which we want.+ *+ * @param fileIDs The ids of the files for which we want the file data.+ *+ * @returns a list of {@link RemoteFileData} items for the files which had file+ * data for the given type, and that remote was able to successfully retrieve.+ *+ * The order of this list is arbitrary, and the caller should use the+ * {@link fileID} present within the {@link RemoteFileData} to associate an item+ * in the result back to a file instead of relying on the order or count of+ * items in the result.+ *+ * In rare cases (issues with the upstream object storage), it is possible for+ * remote to not return entries for a particular file even though it has+ * associated data of that type. Such skipped entries are mentioned in the+ * payload, but we don't parse that information currently since the higher+ * levels of our code that use this function handle such rare skips gracefully.+ */+export const fetchFilesData = async (+ type: FileDataType,+ fileIDs: number[],+): Promise<RemoteFileData[]> => {+ const res = await fetch(await apiURL("/files/data/fetch"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ type, fileIDs }),+ });+ ensureOk(res);+ return z.object({ data: z.array(RemoteFileData) }).parse(await res.json())+ .data;+};++/**+ * A variant of {@link fetchFilesData} that fetches data for a single file.+ *+ * Unlike {@link fetchFilesData}, this uses a HTTP GET request.+ *+ * Returns `undefined` if no file data of the given type has been uploaded for+ * this file yet (e.g. if type was "vid_preview", this would indicate that a+ * video preview has been generated for this file yet).+ *+ * @param publicAlbumsCredentials Credentials to use when we are running in the+ * context of the public albums app. If these are not specified, then the+ * credentials of the logged in user are used.+ */+export const fetchFileData = async (+ type: FileDataType,+ fileID: number,+ publicAlbumsCredentials?: PublicAlbumsCredentials,+): Promise<RemoteFileData | undefined> => {+ const params = new URLSearchParams({+ type,+ fileID: fileID.toString(),+ // Ask museum to respond with 204 instead of 404 if no playlist exists+ // for the given file.+ preferNoContent: "true",+ });++ let res: Response;+ if (publicAlbumsCredentials) {+ const url = await apiURL("/public-collection/files/data/fetch");+ const headers = authenticatedPublicAlbumsRequestHeaders(+ publicAlbumsCredentials,+ );+ res = await fetch(`${url}?${params.toString()}`, { headers });+ } else {+ const url = await apiURL("/files/data/fetch");+ res = await fetch(`${url}?${params.toString()}`, {+ headers: await authenticatedRequestHeaders(),+ });+ }++ if (res.status == 204) return undefined;+ // We're passing `preferNoContent` so the expected response is 204, but this+ // might be a self hoster running an older museum that does not recognize+ // that flag, so retain the old behavior. This fallback can be removed in a+ // few months (tag: Migration, note added May 2025).+ if (res.status == 404) return undefined;+ ensureOk(res);+ return z.object({ data: RemoteFileData }).parse(await res.json()).data;+};++/**+ * An entry in the response to the `/files/data/status-diff`. The actual+ * structure has more fields, there are just the fields we are interested in.+ */+const RemoteFDStatus = z.object({+ /**+ * The ID of the file whose file data we're querying.+ */+ fileID: z.number(),+ /**+ * Expected to be one of {@link FileDataType}+ */+ type: z.string(),+ /**+ * `true` if the file data has been deleted.+ *+ * This can be true in the in-progress partial deletion case, which the file+ * data deletion has been processed but the file deletion has not yet been+ * processed.+ */+ isDeleted: z.boolean(),+ /**+ * The epoch microseconds when this file data entry was added or updated.+ */+ updatedAt: z.number(),+});++/**+ * A paginated part of the result set sent by remote during+ * {@link syncUpdatedFileDataFileIDs}.+ */+export interface UpdatedFileDataFileIDsPage {+ /**+ * The IDs of files for which a file data entry has been created or updated.+ */+ fileIDs: Set<number>;+ /**+ * The latest updatedAt (epoch microseconds) time obtained from remote in+ * this batch being fetched (from amongst all of the files in the batch, not+ * just those that were filtered to be part of {@link fileIDs}).+ */+ lastUpdatedAt: number;+}++/**+ * Fetch the IDs of files for which new file data entries of the given+ * {@link type} have been created or updated since the given {@link sinceTime}.+ *+ * The interaction with remote is paginated, with the {@link onPage} callback+ * being called as each page of new data is received.+ *+ * @param type The {@link FileDataType} for which we want to check for creation+ * or updates.+ *+ * @param lastUpdatedAt Epoch microseconds. This is used to ask remote to+ * provide us only entries whose {@link updatedAt} is more than the given value.+ * Set this to zero to start from the beginning.+ *+ * @param onPage A callback invoked for each page of results received from+ * remote. It is passed the fileIDs received in the batch under consideration,+ * and the largest of the updated time for all entries (irrespective of+ * {@link type}) in that batch.+ *+ * ----+ *+ * [Note: Pruning stale status-diff entries]+ *+ * Unlike other "diff" APIs, the diff API used here won't return tombstone+ * entries for deleted files. This is not a problem because there are no current+ * cases where existing playlists or ML indexes get deleted (unless the+ * underlying file is deleted). See: [Note: Caching HLS playlist data].+ *+ * Note that the "/files/data/status-diff" includes entries for files that are+ * in trash. This means that, while not a practical problem (because it's just+ * numeric ids), the number of fileIDs we store locally can grow unbounded as+ * files move to trash and then get deleted. So to prune them, we also add a+ * hook to the /trash/v2/diff processing, and prune any locally saved file IDs+ * which have been deleted from trash.+ */+export const syncUpdatedFileDataFileIDs = async (+ type: FileDataType,+ lastUpdatedAt: number,+ onPage: (page: UpdatedFileDataFileIDsPage) => Promise<void>,+): Promise<void> => {+ while (true) {+ const res = await fetch(await apiURL("/files/data/status-diff"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ lastUpdatedAt }),+ });+ ensureOk(res);+ const diff = z+ .object({ diff: RemoteFDStatus.array().nullish() })+ .parse(await res.json()).diff;+ if (diff?.length) {+ const fileIDs = new Set<number>();+ for (const fd of diff) {+ lastUpdatedAt = Math.max(lastUpdatedAt, fd.updatedAt);+ // While we could prune isDeleted entries here, we can also rely+ // on the pruning that happens when the trash gets synced. See:+ // [Note: Pruning stale status-diff entries]+ if (fd.type == type && !fd.isDeleted) {+ fileIDs.add(fd.fileID);+ }+ }+ await onPage({ fileIDs, lastUpdatedAt });+ } else {+ break;+ }+ }+};++/**+ * Upload file data associated with the given file to remote.+ *+ * This function will save or update the given data as the latest file data of+ * {@link type} associated with the given {@link file}. The data will be+ * end-to-end encrypted using the given {@link file}'s key before uploading.+ *+ * @param file {@link EnteFile} which this data is associated with.+ *+ * @param type The {@link FileDataType} which we are uploading.+ *+ * @param data The binary data to upload. The exact contents of the data are+ * {@link type} specific.+ *+ * @param lastUpdatedAt The {@link updatedAt} of the {@link RemoteFileData}+ * which we are updating, or 0 to indicate a new entity.+ */+export const putFileData = async (+ file: EnteFile,+ type: FileDataType,+ data: Uint8Array,+ lastUpdatedAt: number,+) => {+ const { encryptedData, decryptionHeader } = await encryptBlob(+ data,+ file.key,+ );++ const res = await fetch(await apiURL("/files/data"), {+ method: "PUT",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({+ fileID: file.id,+ type,+ encryptedData,+ decryptionHeader,+ lastUpdatedAt,+ }),+ });+ ensureOk(res);+};++/**+ * Fetch the preview file data the given file.+ *+ * @param type The {@link FileDataType} which we want.+ *+ * @param fileIDs The id of the files for which we want the file preview data.+ *+ * @param publicAlbumsCredentials Credentials to use when we are running in the+ * context of the public albums app. If these are not specified, then the+ * credentials of the logged in user are used.+ *+ * @returns the (pre-signed) URL to the preview data, or undefined if there is+ * not preview data of the given type for the given file yet.+ *+ * [Note: File data vs file preview data]+ *+ * In museum's ontology, there is a distinction between two concepts:+ *+ * S3 metadata (museum term, the APIs call it "file data") is data that museum+ * uploads on behalf of the client. e.g.,+ *+ * - ML data.+ *+ * - Preview video playlist.+ *+ * S3 file data (museum term, the APIs call it "file preview data") is data that+ * a client itself uploads. e.g.,+ *+ * - The preview video itself.+ *+ * - Additional preview images.+ *+ * [Note: Video playlist and preview]+ *+ * For a streaming video, both these concepts are needed:+ *+ * - The encrypted HLS playlist is stored as "file data" of type "vid_preview",+ *+ * - The encrypted video chunks that the playlist refers to are stored as "file+ * preview data" of type "vid_preview".+ */+export const fetchFilePreviewData = async (+ type: FileDataType,+ fileID: number,+ publicAlbumsCredentials?: PublicAlbumsCredentials,+): Promise<string | undefined> => {+ const params = new URLSearchParams({ type, fileID: fileID.toString() });++ let res: Response;+ if (publicAlbumsCredentials) {+ const headers = authenticatedPublicAlbumsRequestHeaders(+ publicAlbumsCredentials,+ );+ const url = await apiURL("/public-collection/files/data/preview");+ res = await fetch(`${url}?${params.toString()}`, { headers });+ } else {+ const url = await apiURL("/files/data/preview");+ res = await fetch(`${url}?${params.toString()}`, {+ headers: await authenticatedRequestHeaders(),+ });+ }++ if (res.status == 404) return undefined;+ ensureOk(res);+ return z.object({ url: z.string() }).parse(await res.json()).url;+};++/**+ * Update the video data associated with the given file to remote.+ *+ * Video data refers to two things:+ *+ * - The encrypted HLS playlist ("file data" of type "vid_preview").+ *+ * - The object ID of an (already uploaded) "file preview data" file containing+ * the video segments.+ *+ * This function is similar to {@link putFileData}, except it will save (or+ * update) both the playlist, and the reference to its associated segment file,+ * associated with the given {@link file}. The playlist data will be end-to-end+ * encrypted using the given {@link file}'s key before uploading.+ *+ * @param file {@link EnteFile} which this data is associated with.+ *+ * @param encryptedPlaylist The encrypted playlist data (along with the nonce+ * used during encryption).+ *+ * @param objectID Object ID of an already uploaded "file preview data" (see+ * {@link getFilePreviewDataUploadURL}).+ *+ * @param objectSize The size (in bytes) of the file corresponding to+ * {@link objectID}.+ */+export const putVideoData = async (+ file: EnteFile,+ encryptedPlaylist: EncryptedBlobB64,+ objectID: string,+ objectSize: number,+) =>+ retryEnsuringHTTPOk(+ async () =>+ fetch(await apiURL("/files/video-data"), {+ method: "PUT",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({+ fileID: file.id,+ objectID,+ objectSize,+ playlist: encryptedPlaylist.encryptedData,+ playlistHeader: encryptedPlaylist.decryptionHeader,+ }),+ }),+ { retryProfile: "background" },+ );diff --git a/web/apps/albums/vendor/ente-gallery/services/files-db.ts b/web/apps/albums/vendor/ente-gallery/services/files-db.tsnew file mode 100644index 0000000000..755863e7bb--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/files-db.ts@@ -0,0 +1,294 @@+/**+ * @file+ *+ * [Note: Files DB]+ *+ * Prior to us using idb for accessing IndexedDB, we used localForage (another+ * IndexedDB library) for that purpose (See `docs/storage.md` for more context).+ *+ * Our use of localForage was (and is) limited to:+ *+ * - A single IndexedDB database named "ente-files" containing+ *+ * - A single table named "files"+ *+ * It stored more than files though - files, collections, trash, their+ * corresponding sync times, and other bits and bobs related to them.+ *+ * > Note: File contents themselves are not stored in IndexedDB, only+ * > {@link EnteFile}s.+ *+ * Since we've now switched to idb as our preferred IndexedDB library, the data+ * stored in this files table could be considered legacy in a sense. But such+ * would be an incorrect characterization - this code has no issues, and it+ * stores core data for us (files and collections are as core as it gets).+ *+ * So this table is not legacy or deprecated, and there is currently no strong+ * reason to migrate this data to another IndexedDB table (it works fine as it+ * is, really). However we do want to avoid adding more items here, and maybe+ * gradually move some of the "bits and bobs" elsewhere (e.g. KV DB).+ *+ * ---+ *+ * This file contains the common code and types. Application layer code should+ * usually be accessing the app specific files DB by importing the functions+ * from the following modules:+ *+ * - Photos app: `photos-fdb.ts`+ * - Public albums app: `public-albums-fdb.ts`+ *+ * Note that even though both of them refer to the same conceptual "files DB",+ * the actual storage is distinct since both the apps run on separate domains+ * and so have their separate IndexedDB storage and thus separate files tables.+ *+ * Still, the key names are distinct to reduce chances of confusion: the public+ * albums app stores data in keys prefixed with "public-".+ */++import { haveWindow } from "ente-base/env";+import log from "ente-base/log";+import {+ CollectionPrivateMagicMetadataData,+ CollectionPublicMagicMetadataData,+ CollectionShareeMagicMetadataData,+ ignore,+ RemoteCollectionUser,+ RemotePublicURL,+} from "ente-media/collection";+import {+ RemoteFileInfo,+ RemoteFileObjectAttributes,+ transformDecryptedMetadataJSON,+ type EnteFile,+} from "ente-media/file";+import {+ FileMetadata,+ FilePrivateMagicMetadataData,+ FilePublicMagicMetadataData,+} from "ente-media/file-metadata";+import type { MagicMetadata } from "ente-media/magic-metadata";+import { nullishToEmpty, nullToUndefined } from "ente-utils/transform";+import localForage from "localforage";+import { z } from "zod";++if (haveWindow()) {+ localForage.config({+ name: "ente-files",+ version: 1.0,+ storeName: "files",+ });+}++/**+ * Reexport localForage for use by (and only by):+ * - photos-fdb.ts+ * - public-albums-fdb.ts+ * - migration.ts+ */+export { localForage };++/**+ * Return `true` if we can access IndexedDB.+ *+ * This is used as a pre-flight check, to notify the user if they're using a+ * browser or extension that is preventing the app from using IndexedDB (which+ * is necessary for local storage of collections and files metadata).+ */+export const canAccessIndexedDB = async () => {+ try {+ await localForage.ready();+ return true;+ } catch (e) {+ log.error("IndexDB is not accessible", e);+ return false;+ }+};++/**+ * Clear any data stored in files DB.+ *+ * This is meant to be called during the logout sequence.+ */+export const clearFilesDB = () => localForage.clear();++/**+ * Return a Zod schema suitable for being used with the various magic metadata+ * fields of a file or a collection.+ */+const createMagicMetadataSchema = <T extends z.ZodType>(dataSchema: T) =>+ z+ .object({ version: z.number(), count: z.number(), data: dataSchema })+ .nullish()+ .transform(nullToUndefined);++/**+ * Zod schema for a {@link Collection} stored in our local database.+ *+ * This is similar to {@link RemoteCollection}, but it differs in that it+ * contains the decrypted values instead of the encrypted data and nonce pairs.+ * There are also some other minor nullish transforms.+ */+const LocalCollection = z+ .looseObject({+ id: z.number(),+ owner: RemoteCollectionUser,+ key: z.string(),+ name: z.string(),+ type: z.string(),+ sharees: z+ .array(RemoteCollectionUser)+ .nullish()+ .transform(nullishToEmpty),+ publicURLs: z+ .array(RemotePublicURL)+ .nullish()+ .transform(nullishToEmpty),+ updationTime: z.number(),+ magicMetadata: createMagicMetadataSchema(+ CollectionPrivateMagicMetadataData,+ ),+ pubMagicMetadata: createMagicMetadataSchema(+ CollectionPublicMagicMetadataData,+ ),+ sharedMagicMetadata: createMagicMetadataSchema(+ CollectionShareeMagicMetadataData,+ ),+ })+ .transform((c) => {+ // Old data stored locally contained fields which are no longer needed.+ // Do some zod gymnastics to drop these when reading (so that they're+ // not written back the next time). This code was added June 2025,+ // 1.7.14-beta, and can be removed after a bit (tag: Migration).+ const {+ encryptedKey,+ keyDecryptionNonce,+ encryptedName,+ nameDecryptionNonce,+ attributes,+ isDeleted,+ ...rest+ } = c;+ ignore([+ encryptedKey,+ keyDecryptionNonce,+ encryptedName,+ nameDecryptionNonce,+ attributes,+ isDeleted,+ ]);+ return rest;+ });++export const LocalCollections = z.array(LocalCollection);++/**+ * Zod schema for a {@link EnteFile} stored in our local database.+ *+ * This is similar to {@link RemoteEnteFile}, but it differs in that it contains+ * the decrypted values instead of the encrypted data and nonce pairs.+ */+export const LocalEnteFile = z.looseObject({+ id: z.number(),+ collectionID: z.number(),+ ownerID: z.number(),+ key: z.string(),+ file: RemoteFileObjectAttributes,+ thumbnail: RemoteFileObjectAttributes,+ info: RemoteFileInfo.nullish().transform(nullToUndefined),+ updationTime: z.number(),+ metadata: FileMetadata,+ magicMetadata: createMagicMetadataSchema(FilePrivateMagicMetadataData),+ pubMagicMetadata: createMagicMetadataSchema(FilePublicMagicMetadataData),+});++export const LocalEnteFiles = z.array(LocalEnteFile);++/**+ * Apply transformations when reading files from the DB.+ *+ * There are two parts to it -+ *+ * 1. the required part (patching old entries that might be present in the local+ * database),+ * 2. the optional part (removing some unused fields).+ *+ * Part 1 ---+ *+ * Transform metadata in legacy files that might be present in the local+ * database. Note that this will not be needed for files that are fetched+ * afresh, since the corresponding transform is already done during+ * {@link decryptRemoteFile}; this is only for handling potentially items that+ * might've been already present locally.+ *+ * Part 2 ---+ *+ * Remove unused fields from the file objects when reading them.+ *+ * This is similar to the transformation we perform when reading collections+ * from the database, to discard fields that are no longer forwarded when we+ * parse the remote object, and thus will not be present in the local DB either+ * when going forward. They might be present for the existing entries in DB+ * though, which is why these functions are needed.+ *+ * However, since unlike collections, we don't route the files through Zod when+ * reading. So instead we do it using this function. Effectively, the end result+ * should be the same. In any case, doing this cleanup has no functional impact.+ *+ * Both parts added June 2025, 1.7.14-beta, prune eventually (tag: Migration).+ */+export const transformFilesIfNeeded = (files: EnteFile[]) =>+ isFilesTransformNeeded(files) ? files.map(transformFile) : files;++// Preflight check to turn the potentially non-trivial overhead (~50ms for 200k+// files if everything runs through transformFile) into an effective no-op+// (2-3ms) for the majority happy paths which don't need any transform.+const isFilesTransformNeeded = (+ files: (EnteFile & { isDeleted?: unknown })[],+) =>+ !!files.find(+ (file) =>+ "isDeleted" in file ||+ !file.metadata.modificationTime ||+ typeof file.metadata.fileType != "number",+ );++const transformFile = (file: EnteFile & { isDeleted?: unknown }) => {+ const {+ isDeleted,+ metadata: origMetadata,+ magicMetadata,+ pubMagicMetadata,+ ...rest+ } = file;+ ignore(isDeleted);+ // We live with the cast here since this migration code should eventually be+ // removed. The cast is needed because in the original context,+ // transformDecryptedMetadataJSON acts on arbitrary JSON objects that have+ // not yet been validated to be of type FileMetadata.+ const metadata = transformDecryptedMetadataJSON(+ file.id,+ origMetadata,+ ) as FileMetadata;+ if (magicMetadata) {+ delete (magicMetadata as MagicMetadata & { header?: unknown }).header;+ }+ if (pubMagicMetadata) {+ delete (pubMagicMetadata as MagicMetadata & { header?: unknown })+ .header;+ }+ return {+ ...rest,+ metadata,+ magicMetadata,+ pubMagicMetadata,+ } satisfies EnteFile;+};++/**+ * A convenience Zod schema for a nullish number, with `null`s being transformed+ * to `undefined`.+ *+ * This is convenient when parsing the various timestamps we keep corresponding+ * to top level keys in the files DB. Don't use elsewhere!+ */+export const LocalTimestamp = z.number().nullish().transform(nullToUndefined);diff --git a/web/apps/albums/vendor/ente-gallery/services/save.ts b/web/apps/albums/vendor/ente-gallery/services/save.tsnew file mode 100644index 0000000000..51f42ed3c0--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/save.ts@@ -0,0 +1,773 @@+import { assertionFailed } from "ente-base/assert";+import { suppressMainWindowBlurForTrustedPrompt } from "ente-base/electron";+import { joinPath, nameAndExtension } from "ente-base/file-name";+import log from "ente-base/log";+import { type Electron } from "ente-base/types/ipc";+import { saveAsFileAndRevokeObjectURL } from "ente-base/utils/web";+import { downloadManager } from "ente-gallery/services/download";+import { writeStream } from "ente-gallery/utils/native-stream";+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 {+ safeDirectoryName,+ safeFileName,+} from "ente-new/photos/utils/native-fs";+import JSZip from "jszip";+import type {+ AddSaveGroup,+ UpdateSaveGroup,+} from "../components/utils/save-groups";++/**+ * Download limits optimized for different devices and browsers.+ */+interface DownloadLimits {+ /** Number of concurrent file downloads. */+ concurrency: number;+ /** Maximum size of a ZIP batch in bytes. */+ maxZipSize: number;+}++let cachedLimits: DownloadLimits | undefined;++/**+ * Get download limits for the current device.+ *+ * - Mobile devices: 4 concurrent, 100MB max+ * - Desktop: 8 concurrent, 250MB max+ */+const getDownloadLimits = (): DownloadLimits => {+ if (cachedLimits) return cachedLimits;++ const ua = navigator.userAgent.toLowerCase();+ const isMobile =+ ua.includes("iphone") ||+ ua.includes("ipad") ||+ ua.includes("ipod") ||+ ua.includes("android") ||+ ua.includes("mobile") ||+ ua.includes("tablet") ||+ (ua.includes("macintosh") && navigator.maxTouchPoints > 1);++ cachedLimits = isMobile+ ? { concurrency: 4, maxZipSize: 100 * 1024 * 1024 } // 100MB+ : { concurrency: 8, maxZipSize: 250 * 1024 * 1024 }; // 250MB++ return cachedLimits;+};++const shouldIncludeZipNumber = (+ files: EnteFile[],+ maxZipSize: number,+): boolean => {+ let totalSize = 0;+ for (const file of files) {+ const size = file.info?.fileSize;+ if (size == null) {+ return true;+ }+ totalSize += size;+ if (totalSize > maxZipSize) {+ return true;+ }+ }+ return false;+};++/**+ * Save the given {@link files} to the user's device.+ *+ * If we're running in the context of the web app, the files will be saved to+ * the user's download folder. If we're running in the context of our desktop+ * app, the user will be prompted to select a directory on their file system and+ * the files will be saved therein.+ *+ * @param files The files to save.+ *+ * @param title A title to show in the UI notification that indicates the+ * progress of the save.+ *+ * @param onAddSaveGroup A function that can be used to create a save group+ * associated with the save. The newly added save group will correspond to a+ * notification shown in the UI, and the progress and status of the save can be+ * communicated by updating the save group's state using the updater function+ * obtained when adding the save group.+ */+export const downloadAndSaveFiles = (+ files: EnteFile[],+ title: string,+ onAddSaveGroup: AddSaveGroup,+) => downloadAndSave(files, title, onAddSaveGroup);++/**+ * Save all the files of a collection to the user's device.+ *+ * This is a variant of {@link downloadAndSaveFiles}, except instead of taking a+ * list of files to save, this variant is tailored for saving saves all the+ * files that belong to a collection. Otherwise, it broadly behaves similarly;+ * see that method's documentation for more details.+ *+ * When running in the context of the desktop app, instead of saving the files+ * in the directory selected by the user, files are saved in a directory with+ * the same name as the collection.+ *+ * @param isHiddenCollectionSummary `true` if the collection is associated with+ * a "hidden" collection or pseudo-collection in the app. Only relevant when+ * running in the context of the photos app, can be `undefined` otherwise.+ */+export const downloadAndSaveCollectionFiles = async (+ collectionSummaryName: string,+ collectionSummaryID: number,+ files: EnteFile[],+ isHiddenCollectionSummary: boolean | undefined,+ onAddSaveGroup: AddSaveGroup,+) =>+ downloadAndSave(+ files,+ collectionSummaryName,+ onAddSaveGroup,+ collectionSummaryName,+ collectionSummaryID,+ isHiddenCollectionSummary,+ );++/**+ * The lower level primitive that the public API of this module delegates to.+ */+const downloadAndSave = async (+ files: EnteFile[],+ title: string,+ onAddSaveGroup: AddSaveGroup,+ collectionSummaryName?: string,+ collectionSummaryID?: number,+ isHiddenCollectionSummary?: boolean,+) => {+ const electron = globalThis.electron;++ const total = files.length;+ if (!files.length) {+ // Nothing to download.+ assertionFailed();+ return;+ }++ let downloadDirPath: string | undefined;+ if (electron) {+ suppressMainWindowBlurForTrustedPrompt();+ downloadDirPath = await electron.selectDirectory();+ if (!downloadDirPath) {+ // The user cancelled on the directory selection dialog.+ return;+ }+ if (collectionSummaryName) {+ downloadDirPath = await mkdirCollectionDownloadFolder(+ electron,+ downloadDirPath,+ collectionSummaryName,+ );+ }+ }++ const shouldZipOnWeb =+ !electron &&+ (files.length > 1 ||+ (files.length === 1 &&+ files[0]?.metadata.fileType === FileType.livePhoto));+ const includeZipNumber =+ shouldZipOnWeb &&+ shouldIncludeZipNumber(files, getDownloadLimits().maxZipSize);++ const canceller = new AbortController();+ const failedFiles: EnteFile[] = [];+ let isDownloading = false;+ let updateSaveGroup: UpdateSaveGroup = () => undefined;+ // Track the next ZIP batch index across retries so part numbers continue+ // sequentially (e.g., if initial download creates Parts 1-5 and fails,+ // retry creates Part 6+ instead of starting over at Part 1).+ let nextZipBatchIndex = 1;++ const downloadFilesDesktop = async (+ filesToDownload: EnteFile[],+ resetFailedCount = false,+ ) => {+ if (!filesToDownload.length || isDownloading) return;+ if (!electron || !downloadDirPath) return;++ isDownloading = true;+ if (resetFailedCount) {+ updateSaveGroup((g) => ({ ...g, failed: 0 }));+ }+ failedFiles.length = 0;++ try {+ for (const file of filesToDownload) {+ if (canceller.signal.aborted) break;+ try {+ await saveFileDesktop(electron, file, downloadDirPath);+ updateSaveGroup((g) => ({ ...g, success: g.success + 1 }));+ } catch (e) {+ log.error("File download failed", e);+ failedFiles.push(file);+ updateSaveGroup((g) => ({ ...g, failed: g.failed + 1 }));+ }+ }++ if (!failedFiles.length) {+ updateSaveGroup((g) => ({ ...g, retry: undefined }));+ }+ } finally {+ isDownloading = false;+ }+ };++ const downloadFilesWeb = async (+ filesToDownload: EnteFile[],+ resetFailedCount = false,+ ) => {+ if (!filesToDownload.length || isDownloading) return;++ // Reset counts first if this is a retry, before any other logic+ if (resetFailedCount) {+ updateSaveGroup((g) => ({+ ...g,+ failed: 0,+ failureReason: undefined,+ }));+ failedFiles.length = 0;+ }++ // If already offline, mark all files as failed so retry is available+ if (!navigator.onLine) {+ log.info("Download skipped - network is offline");+ for (const file of filesToDownload) {+ failedFiles.push(file);+ }+ updateSaveGroup((g) => ({+ ...g,+ failed: filesToDownload.length,+ failureReason: "network_offline",+ }));+ return;+ }++ isDownloading = true;+ // Only clear on first download, not retry (already cleared above)+ if (!resetFailedCount) {+ failedFiles.length = 0;+ }++ try {+ // Single non-live-photo file: download directly without zipping+ const singleFile = filesToDownload[0];+ if (+ filesToDownload.length === 1 &&+ singleFile &&+ singleFile.metadata.fileType !== FileType.livePhoto+ ) {+ try {+ const fileBlob = await downloadManager.fileBlob(singleFile);+ const fileName = fileFileName(singleFile);+ const url = URL.createObjectURL(fileBlob);+ saveAsFileAndRevokeObjectURL(url, fileName);+ updateSaveGroup((g) => ({ ...g, success: g.success + 1 }));+ } catch (e) {+ log.error("File download failed", e);+ failedFiles.push(singleFile);+ updateSaveGroup((g) => ({ ...g, failed: g.failed + 1 }));+ }+ } else {+ // Multiple files or live photo: use ZIP+ nextZipBatchIndex = await saveAsZip(+ filesToDownload,+ title,+ () =>+ updateSaveGroup((g) => ({+ ...g,+ success: g.success + 1,+ })),+ (file) => {+ failedFiles.push(file);+ updateSaveGroup((g) => ({+ ...g,+ failed: g.failed + 1,+ }));+ },+ canceller,+ updateSaveGroup,+ nextZipBatchIndex,+ includeZipNumber,+ );+ }++ if (!failedFiles.length) {+ updateSaveGroup((g) => ({ ...g, retry: undefined }));+ }+ } finally {+ isDownloading = false;+ }+ };++ const downloadFiles = electron ? downloadFilesDesktop : downloadFilesWeb;++ const retry = () => {+ if (!failedFiles.length || isDownloading || canceller.signal.aborted)+ return;+ void downloadFiles([...failedFiles], true);+ };++ updateSaveGroup = onAddSaveGroup({+ title,+ collectionSummaryID,+ isHiddenCollectionSummary,+ downloadDirPath,+ total,+ includeZipNumber,+ canceller,+ retry,+ });++ await downloadFiles(files);+};++/**+ * A helper class to accumulate files into ZIP batches and download them when+ * the batch size limit is reached.+ */+class ZipBatcher {+ private zip = new JSZip();+ private currentBatchSize = 0;+ private currentFileCount = 0;+ private batchIndex: number;+ private usedNames = new Set<string>();+ private baseName: string;+ private maxZipSize: number;+ private includePartNumber: boolean;+ private onStateChange?: (+ isDownloading: boolean,+ partNumber: number,+ ) => void;++ constructor(+ baseName: string,+ maxZipSize: number,+ startingBatchIndex = 1,+ onStateChange?: (isDownloading: boolean, partNumber: number) => void,+ includePartNumber = false,+ ) {+ this.baseName = baseName;+ this.maxZipSize = maxZipSize;+ this.batchIndex = startingBatchIndex;+ this.onStateChange = onStateChange;+ this.includePartNumber = includePartNumber || startingBatchIndex > 1;+ }++ /**+ * Get the next batch index that would be used for the next ZIP file.+ * This is useful for tracking progress across retries.+ */+ getNextBatchIndex(): number {+ return this.batchIndex;+ }++ /**+ * Get the current batch index being processed.+ */+ getCurrentBatchIndex(): number {+ return this.batchIndex;+ }++ /**+ * Add file data to the current ZIP batch. If adding this file would exceed+ * the batch size limit, the current batch is downloaded first.+ */+ async addFile(data: Uint8Array | Blob, fileName: string): Promise<void> {+ const size = data instanceof Blob ? data.size : data.byteLength;++ // If adding this file would exceed the limit and we have files in the+ // batch, download the current batch first.+ if (+ this.currentBatchSize > 0 &&+ this.currentBatchSize + size > this.maxZipSize+ ) {+ this.includePartNumber = true;+ await this.downloadCurrentBatch();+ // Notify that we're now preparing a new part+ this.onStateChange?.(false, this.batchIndex);+ }++ // Ensure unique file names within the ZIP+ const uniqueName = this.getUniqueName(fileName);+ this.usedNames.add(uniqueName);+ this.zip.file(uniqueName, data);+ this.currentBatchSize += size;+ this.currentFileCount++;+ }++ /**+ * Download any remaining files in the current batch.+ */+ async flush(): Promise<void> {+ if (this.currentBatchSize > 0) {+ await this.downloadCurrentBatch();+ }+ }++ private async downloadCurrentBatch(): Promise<void> {+ this.onStateChange?.(true, this.batchIndex);+ try {+ const zipBlob = await this.zip.generateAsync({ type: "blob" });+ const fileLabel =+ this.currentFileCount === 1+ ? "1 file"+ : `${this.currentFileCount} files`;+ const baseName = this.baseName.trim();+ const nameBase = this.includePartNumber+ ? `${baseName} Part ${this.batchIndex}`+ : baseName;+ const zipName =+ baseName.toLowerCase() === fileLabel.toLowerCase()+ ? `${nameBase}.zip`+ : `${nameBase} - ${fileLabel}.zip`;++ const url = URL.createObjectURL(zipBlob);+ saveAsFileAndRevokeObjectURL(url, zipName);+ } finally {+ this.onStateChange?.(false, this.batchIndex);+ }++ // Reset for next batch+ this.zip = new JSZip();+ this.currentBatchSize = 0;+ this.currentFileCount = 0;+ this.usedNames.clear();+ this.batchIndex++;+ }++ /**+ * Generate a unique file name within the ZIP by appending a suffix if the+ * name already exists.+ */+ private getUniqueName(fileName: string): string {+ if (!this.usedNames.has(fileName)) {+ return fileName;+ }++ const [name, ext] = nameAndExtension(fileName);+ let counter = 1;+ let uniqueName: string;+ do {+ uniqueName = ext+ ? `${name}(${counter}).${ext}`+ : `${name}(${counter})`;+ counter++;+ } while (this.usedNames.has(uniqueName));++ return uniqueName;+ }+}++/** Result of downloading and processing a single file for ZIP inclusion. */+type DownloadedFileData =+ | { type: "regular"; fileName: string; data: Uint8Array }+ | {+ type: "livePhoto";+ imageFileName: string;+ imageData: Uint8Array;+ videoFileName: string;+ videoData: Uint8Array;+ };++/**+ * Download and process a single file, returning the data ready for ZIP.+ */+const downloadFileForZip = async (+ file: EnteFile,+): Promise<DownloadedFileData> => {+ const fileBlob = await downloadManager.fileBlob(file);+ const fileName = fileFileName(file);++ if (file.metadata.fileType == FileType.livePhoto) {+ const { imageFileName, imageData, videoFileName, videoData } =+ await decodeLivePhoto(fileName, fileBlob);+ return {+ type: "livePhoto",+ imageFileName,+ imageData,+ videoFileName,+ videoData,+ };+ } else {+ const data = new Uint8Array(await fileBlob.arrayBuffer());+ return { type: "regular", fileName, data };+ }+};++/**+ * Save multiple files as ZIP archives to the user's download folder.+ *+ * Files are batched into ZIPs of up to 100MB each. If the total exceeds 100MB,+ * multiple ZIP files will be downloaded. Downloads are performed concurrently+ * (up to {@link CONCURRENT_DOWNLOADS} at a time) for better performance.+ *+ * @param files The files to download and add to the ZIP.+ * @param baseName The base name for the ZIP file(s).+ * @param onSuccess Callback invoked after each file is successfully added.+ * @param onError Callback invoked when a file fails to download.+ * @param canceller An AbortController to check for cancellation.+ * @param startingBatchIndex The batch index to start from (for retries).+ * @returns The next batch index to use for subsequent ZIPs (useful for retries).+ */+const saveAsZip = async (+ files: EnteFile[],+ baseName: string,+ onSuccess: () => void,+ onError: (file: EnteFile, error: unknown) => void,+ canceller: AbortController,+ updateSaveGroup: UpdateSaveGroup,+ startingBatchIndex = 1,+ includePartNumber = false,+): Promise<number> => {+ const { concurrency, maxZipSize } = getDownloadLimits();+ const batcher = new ZipBatcher(+ baseName,+ maxZipSize,+ startingBatchIndex,+ (isDownloading, partNumber) =>+ updateSaveGroup((g) => ({+ ...g,+ isDownloadingZip: isDownloading,+ currentPart: partNumber,+ })),+ includePartNumber,+ );++ // Set initial part number+ updateSaveGroup((g) => ({ ...g, currentPart: startingBatchIndex }));++ // Queue of files to process+ let fileIndex = 0;++ // Track if we've gone offline to stop processing immediately.+ // Using an object so the value can be mutated by event handlers and+ // checked synchronously by the async workers.+ const networkState = { isOffline: !navigator.onLine };+ const handleOffline = () => {+ networkState.isOffline = true;+ };+ const handleOnline = () => {+ networkState.isOffline = false;+ };+ window.addEventListener("offline", handleOffline);+ window.addEventListener("online", handleOnline);++ // Mutex for serializing ZIP additions (download is concurrent, but adding+ // to the ZIP must be serialized to avoid race conditions with batching)+ let zipMutex: Promise<void> = Promise.resolve();+ const withZipLock = async <T>(fn: () => Promise<T>): Promise<T> => {+ const prev = zipMutex;+ let resolve: () => void;+ zipMutex = new Promise((r) => (resolve = r));+ await prev;+ try {+ return await fn();+ } finally {+ resolve!();+ }+ };++ // Process a single file: download, then add to ZIP+ const processFile = async (): Promise<boolean> => {+ // Stop immediately if offline or cancelled+ if (networkState.isOffline || canceller.signal.aborted) {+ return false;+ }++ // Get next file to process+ const currentIndex = fileIndex++;+ if (currentIndex >= files.length) {+ return false;+ }++ const file = files[currentIndex]!;+ try {+ // Check again before starting download (value can change via event handler)+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition+ if (networkState.isOffline) {+ // Put this file back for retry+ onError(file, new Error("Network offline"));+ return false;+ }++ // Download happens concurrently+ const downloadedData = await downloadFileForZip(file);++ // Adding to ZIP is serialized via mutex+ await withZipLock(async () => {+ if (downloadedData.type === "livePhoto") {+ await batcher.addFile(+ downloadedData.imageData,+ downloadedData.imageFileName,+ );+ await batcher.addFile(+ downloadedData.videoData,+ downloadedData.videoFileName,+ );+ } else {+ await batcher.addFile(+ downloadedData.data,+ downloadedData.fileName,+ );+ }+ });+ onSuccess();+ } catch (e) {+ // Individual file failed - mark it for retry but continue with others+ // Only log non-network errors to avoid log spam when offline+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition+ if (!networkState.isOffline) {+ log.error(`Failed to download file ${file.id}, skipping`, e);+ }+ onError(file, e);++ // Only stop all processing if we went offline (not for individual failures)+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition+ if (networkState.isOffline) {+ updateSaveGroup((g) => ({+ ...g,+ failureReason: "network_offline",+ }));+ return false;+ }+ // Mark as file error for individual failures+ updateSaveGroup((g) => ({+ ...g,+ failureReason: g.failureReason ?? "file_error",+ }));+ // Continue processing remaining files even if this one failed+ }++ return true;+ };++ // Worker that continuously processes files until done+ const worker = async (): Promise<void> => {+ while (await processFile()) {+ // Continue processing+ }+ };++ try {+ // Start concurrent workers+ const workers = Array.from(+ { length: Math.min(concurrency, files.length) },+ () => worker(),+ );+ await Promise.all(workers);++ // If we went offline, mark remaining files as failed+ if (networkState.isOffline) {+ updateSaveGroup((g) => ({+ ...g,+ failureReason: "network_offline",+ }));+ while (fileIndex < files.length) {+ const file = files[fileIndex++];+ if (file) {+ onError(file, new Error("Network offline"));+ }+ }+ }++ // Flush whatever we have (even partial) unless cancelled+ if (!canceller.signal.aborted) {+ await batcher.flush();+ }++ return batcher.getNextBatchIndex();+ } finally {+ // Clean up event listeners+ window.removeEventListener("offline", handleOffline);+ window.removeEventListener("online", handleOnline);+ }+};++/**+ * Create a new directory on the user's file system with the same name as the+ * provided {@link collectionName} under the provided {@link downloadDirPath},+ * and return the full path to the created directory.+ *+ * This function can be used only when running in the context of our desktop+ * app, and so such requires an {@link Electron} instance as the witness.+ */+const mkdirCollectionDownloadFolder = async (+ { fs }: Electron,+ downloadDirPath: string,+ collectionName: string,+) => {+ const collectionDownloadName = await safeDirectoryName(+ downloadDirPath,+ collectionName,+ fs.exists,+ );+ const collectionDownloadPath = joinPath(+ downloadDirPath,+ collectionDownloadName,+ );+ await fs.mkdirIfNeeded(collectionDownloadPath);+ return collectionDownloadPath;+};++/**+ * Save a file to the given {@link directoryPath} using native filesystem APIs.+ *+ * This is a sibling of {@link saveAsFile} for use when we are running in the+ * context of our desktop app. Unlike the browser, the desktop app can use+ * native file system APIs to efficiently write the files on disk without+ * needing to prompt the user for each write.+ *+ * @param electron An {@link Electron} instance, a witness to the fact that+ * we're running in the desktop app.+ *+ * @param file The {@link EnteFile} whose contents we want to save to the user's+ * file system.+ *+ * @param directoryPath The file system directory in which to save the file.+ */+const saveFileDesktop = async (+ electron: Electron,+ file: EnteFile,+ directoryPath: string,+) => {+ const fs = electron.fs;++ const createExportName = (fileName: string) =>+ safeFileName(directoryPath, fileName, fs.exists);++ const writeStreamToFile = (+ exportName: string,+ stream: ReadableStream<Uint8Array> | null,+ ) => writeStream(electron, joinPath(directoryPath, exportName), stream);++ const stream = await downloadManager.fileStream(file);+ const fileName = fileFileName(file);++ if (file.metadata.fileType == FileType.livePhoto) {+ const { imageFileName, imageData, videoFileName, videoData } =+ await decodeLivePhoto(fileName, await new Response(stream).blob());+ const imageExportName = await createExportName(imageFileName);+ await writeStreamToFile(imageExportName, new Response(imageData).body);+ try {+ await writeStreamToFile(+ await createExportName(videoFileName),+ new Response(videoData).body,+ );+ } catch (e) {+ await fs.rm(joinPath(directoryPath, imageExportName));+ throw e;+ }+ } else {+ await writeStreamToFile(await createExportName(fileName), stream);+ }+};diff --git a/web/apps/albums/vendor/ente-gallery/services/share.ts b/web/apps/albums/vendor/ente-gallery/services/share.tsnew file mode 100644index 0000000000..3f37ff4bbd--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/share.ts@@ -0,0 +1,46 @@+import bs58 from "bs58";+import { fromB64, fromHex, toB64 } from "ente-base/crypto";++/**+ * Add the collection key as the hash to the given URL.+ *+ * The hash fragment is a client side component and is not accessible to remote+ * servers. The collection key is base-58 encoded and set as the hash in public+ * URLs of shared albums.+ *+ * Use {@link extractCollectionKeyFromShareURL} to get back the collection key.++ * @param url The base URL for the public album.++ * @param collectionKey The base-64 encoded string representation of the+ * collection key for the public album.+ *+ * @returns A URL that includes the base-58 encoded collection key as the hash+ * fragment.+ */+export const appendCollectionKeyToShareURL = async (+ url: string,+ collectionKey: string,+) => {+ const sharableURL = new URL(url);++ const bytes = await fromB64(collectionKey);+ sharableURL.hash = bs58.encode(bytes);+ return sharableURL.href;+};++/**+ * Extract the collection key from a public URL.+ *+ * This is the inverse of {@link appendCollectionKeyToShareURL}, returning the+ * base64 string representation of the collection key.+ *+ * collection key (bytes)+ * => appendCollectionKeytoShareURL (base 64 => base 58)+ * => URL hash => extractCollectionKeyBytesFromShareURL (base 58 => base 64)+ * => collection key (bytes).+ */+export const extractCollectionKeyFromShareURL = async (url: URL) => {+ const ck = url.hash.slice(1);+ return ck.length < 50 ? await toB64(bs58.decode(ck)) : await fromHex(ck);+};diff --git a/web/apps/albums/vendor/ente-gallery/services/upload/date.ts b/web/apps/albums/vendor/ente-gallery/services/upload/date.tsnew file mode 100644index 0000000000..3b200bf83c--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/upload/date.ts@@ -0,0 +1,231 @@+import { nameAndExtension } from "ente-base/file-name";+import log from "ente-base/log";++/**+ * Try to extract a date (as epoch microseconds) from a file name by matching it+ * against certain known patterns for media files.+ *+ * This uses all sorts of arbitrary heuristics gathered over time from feedback+ * by users. In particular, this is meant to capture the dates from screenshots+ * and chat app forwards.+ *+ * If the filename doesn't match a known pattern, or if there is some error+ * during the parsing, return `undefined`.+ */+export const tryParseEpochMicrosecondsFromFileName = (+ fileName: string,+): number | undefined => {+ try {+ return parseEpochMicrosecondsFromFileName(fileName);+ } catch (e) {+ log.error(`Could not extract date from file name ${fileName}`, e);+ return undefined;+ }+};++// Not sure why we have a try catch, but until there is a chance to validate+// that it doesn't indeed throw, keep this actual logic into this separate and+// more readable function.+const parseEpochMicrosecondsFromFileName = (fileName: string) => {+ let date: Date | undefined;++ fileName = fileName.trim();++ // Known patterns.+ if (fileName.startsWith("IMG-") || fileName.startsWith("VID-")) {+ // WhatsApp media files+ // - e.g. "IMG-20171218-WA0028.jpg"+ const p = fileName.split("-");+ const dateString = p[1];+ if (dateString) {+ date = parseDateFromFusedDateString(dateString);+ }+ } else if (fileName.startsWith("Screenshot_")) {+ // Screenshots on Android+ // - e.g. "Screenshot_20181227-152914.jpg"+ const dateString = fileName.replace("Screenshot_", "");+ date = parseDateFromFusedDateString(dateString);+ } else if (fileName.startsWith("signal-")) {+ // Signal images+ //+ // Signal Android uses "yyyy-MM-dd-HH-mm-ss-SSS"+ // https://github.com/signalapp/Signal-Android/commit/39e14e922bf3f5f11b796455355f69e2189d482f+ //+ // e.g. "signal-2024-08-17-21-58-10-982-1.jpg"+ //+ // Signal Desktop uses "YYYY-MM-DD-HHmmss"+ // https://github.com/signalapp/Signal-Desktop/blob/41216f1378899709d03507649e4a602cebb0d064/js/views/attachment_view.js#L97+ //+ // e.g. "signal-2018-08-21-100217.jpg"+ //+ const p = fileName.split("-");+ if (p.length > 5) {+ const dateString = `${p[1]}${p[2]}${p[3]}-${p[4]}${p[5]}${p[6]}`;+ date = parseDateFromFusedDateString(dateString);+ } else if (p.length > 1) {+ const dateString = `${p[1]}${p[2] ?? ""}${p[3] ?? ""}-${p[4] ?? ""}`;+ date = parseDateFromFusedDateString(dateString);+ }+ }++ if (!date) {+ const [name] = nameAndExtension(fileName);++ if (name.endsWith("_iOS")) {+ // Parse (some) iOS filenames.+ //+ // As reported by a customer, iOS sometimes (unknown exactly when)+ // does not retain the Exif date but instead puts it in the filename+ // in a format like `20230427_145116000_iOS.jpg`, and that Apple+ // Photos can parse it back from there.+ //+ // I couldn't find more official documentation from a quick look,+ // but there do seem to be other people on the internet+ // corraborating this:+ //+ // > iOS 11, (older versions do the same thing), when I take a photo+ // > or video, the filename consists of the following:+ // > 20170923_220934000_iOS ... file name is based on UTC/GMT time.+ // >+ // > https://discussions.apple.com/thread/8087977++ const p = name.split("_");+ if (p.length == 3) {+ const dateString = `${p[0]}-${p[1]}`;+ date = parseDateFromFusedDateString(dateString);+ }+ }+ }++ // Generic pattern.+ if (!date) {+ date = parseDateFromDigitGroups(fileName);+ }++ // Ignore invalid.+ if (!date || isNaN(date.getTime())) {+ return undefined;+ }++ // Convert to epoch microseconds.+ const unixTime = date.getTime() * 1000;+ if (unixTime === Date.UTC(0, 0, 0, 0, 0, 0, 0) || unixTime === 0) {+ // Ignore dateTimeStrings of the form "0000:00:00 00:00:00". We do+ // encounter such missing data in the wild.+ return undefined;+ } else if (unixTime > Date.now() * 1000) {+ // We shouldn't be ignoring future dates, but since this is a file name+ // parser, a future date usually indicates that we parsed some unrelated+ // number that shouldn't have been parsed.+ return undefined;+ } else {+ return unixTime;+ }+};++/**+ * An intermediate data structure we use for the functions in this file. It+ * stores the various components of a JavaScript date.+ *+ * In particular, the month is 0-indexed, as it is for the JavaScript Date's+ * `getMonth`.+ */+interface DateComponents {+ year: number;+ month: number;+ day: number;+ hour: number;+ minute: number;+ second: number;+}++/**+ * Parse a date from a string of the form "YYYYMMDD-HHMMSS". Any extra+ * characters at the end are ignored.+ */+const parseDateFromFusedDateString = (s: string) =>+ validateAndGetDateFromComponents({+ year: Number(s.slice(0, 4)),+ // JavaScript Date's month is 0-indexed.+ month: Number(s.slice(4, 6)) - 1,+ day: Number(s.slice(6, 8)),+ hour: Number(s.slice(9, 11)),+ minute: Number(s.slice(11, 13)),+ second: Number(s.slice(13, 15)),+ });++/**+ * Try to see if we can parse an date from a string with arbitrary separators.+ *+ * For example, consider a string like "2018-08-19 12:34:45". We see if it is+ * possible to extract six symbol separated digit groups from the string. If so,+ * we use them to form a date.+ */+export const parseDateFromDigitGroups = (s: string) => {+ const [year, month, day, hour, minute, second] = s.match(/\d+/g) ?? [];++ // If the filename has 8 consecutive and then 6 consecutive digits, then+ // there is a high possibility that it is a date of the form+ // "YYYYMMDD-HHMMSS".+ if (year?.length == 8 && month?.length == 6) {+ return parseDateFromFusedDateString(year + "-" + month);+ }++ return validateAndGetDateFromComponents({+ year: Number(year),+ // JavaScript Date's month is 0-indexed.+ month: Number(month) - 1,+ day: Number(day),+ hour: Number(hour),+ minute: Number(minute),+ second: Number(second),+ });+};++const validateAndGetDateFromComponents = (components: DateComponents) => {+ let date = dateFromComponents(components);+ if (hasTimeValues(components) && !isTimePartValid(date, components)) {+ // If the date has time values but they are not valid then remove them.+ date = dateFromComponents({+ ...components,+ hour: 0,+ minute: 0,+ second: 0,+ });+ }+ if (!isDatePartValid(date, components)) {+ return undefined;+ }+ if (+ date.getFullYear() < 1990 ||+ date.getFullYear() > new Date().getFullYear() + 1+ ) {+ return undefined;+ }+ return date;+};++const isDatePartValid = (date: Date, { year, month, day }: DateComponents) =>+ date.getFullYear() === year &&+ date.getMonth() === month &&+ date.getDate() === day;++const isTimePartValid = (+ date: Date,+ { hour, minute, second }: DateComponents,+) =>+ date.getHours() === hour &&+ date.getMinutes() === minute &&+ date.getSeconds() === second;++const dateFromComponents = (dateComponents: DateComponents) => {+ const { year, month, day, hour, minute, second } = dateComponents;+ if (hasTimeValues(dateComponents)) {+ return new Date(year, month, day, hour, minute, second);+ } else {+ return new Date(year, month, day);+ }+};++const hasTimeValues = ({ hour, minute, second }: DateComponents) =>+ !isNaN(hour) && !isNaN(minute) && !isNaN(second);diff --git a/web/apps/albums/vendor/ente-gallery/services/upload/index.ts b/web/apps/albums/vendor/ente-gallery/services/upload/index.tsnew file mode 100644index 0000000000..ba01db45ab--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/upload/index.ts@@ -0,0 +1,529 @@+import { basename, dirname } from "ente-base/file-name";+import log from "ente-base/log";+import { customAPIOrigin } from "ente-base/origins";+import type { ZipItem } from "ente-base/types/ipc";+import { exportMetadataDirectoryName } from "ente-gallery/export-dirs";+import type { Collection } from "ente-media/collection";+import type { EnteFile } from "ente-media/file";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";++/**+ * Internal in-memory state shared by the functions in this module.+ *+ * This entire object will be reset on logout.+ */+class UploadState {+ /**+ * `true` if the workers should be disabled for uploads.+ */+ shouldDisableCFUploadProxy = false;+ /**+ * `true` if uploads should include checksum metadata.+ */+ checksumProtectedUploadsEnabled = false;+}++/** State shared by the functions in this module. See {@link UploadState}. */+let _state = new UploadState();++/**+ * Reset any internal state maintained by the module.+ *+ * This is primarily meant as a way for stateful apps (e.g. photos) to clear any+ * user specific state on logout.+ */+export const resetUploadState = () => {+ _state = new UploadState();+};++/**+ * An item to upload is one of the following:+ *+ * 1. [web | desktop] A file drag-and-dropped or selected by the user when we+ * are running in a web browser. This is the {@link File} case. There is one+ * special case when this can also happen when running in the context of our+ * desktop app - when the user edits an existing image.+ *+ * 2. [desktop] A file drag-and-dropped or selected by the user when we are+ * running in the context of our desktop app. In such cases, we also have the+ * absolute path of the file in the user's local file system. This is the+ * {@link FileAndPath} case.+ *+ * 3. [desktop] A file path programmatically requested by the desktop app. For+ * example, we might be resuming a previously interrupted upload after an app+ * restart (thus we no longer have access to the {@link File} from case 2).+ * Or we could be uploading a file this is in one of the folders the user has+ * asked us to watch for changes. This is the `string` case.+ *+ * 4. [desktop] A file within a zip file on the user's local file system. This+ * too is only possible when we are running in the context of our desktop+ * app. The user might have drag-and-dropped or selected a zip file, or it+ * might be a zip file that they'd previously selected but we now are+ * resuming an interrupted upload of. Either ways, what we have is a tuple+ * containing the (path to zip file, and the name of an entry within that zip+ * file). This is the {@link ZipItem} case.+ *+ * Case 1 is possible both when we're running in the web app and desktop app+ * (that said, usually it only happens for the web app; it'll only happen in+ * desktop in the special case when editing an image).+ *+ * Case 2, 3 and 4 are only possible when we're running in the desktop app.+ *+ * Also see: [Note: Reading a UploadItem].+ */+export type UploadItem = File | FileAndPath | string | ZipItem;++/**+ * When we are running in the context of our desktop app, we have access to the+ * absolute path of {@link File} objects. This convenience type clubs these two+ * bits of information, saving us the need to query the path again and again+ * using the {@link getPathForFile} method of {@link Electron}.+ */+export interface FileAndPath {+ file: File;+ path: string;+}++/**+ * The cases of {@link UploadItem} that apply when we're running in the context+ * of our desktop app, and the item that was uploaded has an associated file on+ * the user's file system with a known path.+ *+ * See also {@link TimestampedFileSystemUploadItem}.+ */+export type FileSystemUploadItem = Exclude<UploadItem, File>;++/**+ * A {@link FileSystemUploadItem} augmented with the last modified time of the+ * corresponding file on disk.+ *+ * By keeping the last modified time, we can use it as a test of whether or not+ * the file on disk was modified since it was uploaded. Such an ability is+ * useful for tasks where there can be a arbitrary delay between when the file+ * was uploaded and when the file gets processed.+ *+ * See {@link toTimestampedDesktopUploadItem} for converting a+ * {@link FileSystemUploadItem} into a {@link TimestampedFileSystemUploadItem}+ * when running in the context of the desktop app.+ */+export interface TimestampedFileSystemUploadItem {+ /**+ * Information about the file system file which was uploaded to Ente.+ */+ fsUploadItem: FileSystemUploadItem;+ /**+ * The last modified time (epoch milliseconds) of the file system file.+ */+ lastModifiedMs: number;+}++/**+ * An "path prefix"-like opaque string which can be used to disambiguate+ * distinct source {@link UploadItem}s with the same name that are meant to be+ * uploaded to the same destination Ente album.+ *+ * Th documentation of {@link UploadItem} describes the four cases that an+ * {@link UploadItem} can be. For each of these, we augment an+ * {@link UploadItem} with a prefix ("dirname") derived from its best "path":+ *+ * - Relative path or name in the case of web {@link File}s.+ *+ * - Absolute path in the case of desktop {@link File} or path or+ * {@link FileAndPath}.+ *+ * - Path within the zip file for desktop {@link ZipItem}s.+ *+ * Thus, this path should not be treated as an address that can be used to+ * retrieve the upload item, but rather as extra context that can help us+ * distinguish between items by their relative or path prefix when their file+ * names are the same and they're being uploaded to the same album.+ *+ * Consider the following hierarchy:+ *+ * Foo/2017/Album1/1.png+ * Foo/2017/Album1/1.png.json+ *+ * Foo/2020/Album1/1.png+ * Foo/2020/Album1/1.png.json+ *+ * If user uploads `Foo`, irrespective of if they select the "root" or "parent"+ * option {@link CollectionMapping} option, when matching the takeout, only the+ * Ente album is considered. So it will be undefined which JSON will get used,+ * and both PNG files will get the same JSON, not their file system siblings.+ *+ * In such cases, the path prefix of the item being uploaded can act as extra+ * context that can help us disambiguate and pick the sibling. Note how we don't+ * need the path prefix to be absolute or relative or even addressable, we just+ * need it as extra context that can help us disambiguate two items with+ * otherwise the same name and that are destined for the same Ente album.+ *+ * So for our example, the path prefixes will be+ *+ * Foo/2017/Album1/1.png "Foo/2017/Album1"+ * Foo/2017/Album1/1.png.json "Foo/2017/Album1"+ *+ * Foo/2020/Album1/1.png "Foo/2020/Album1"+ * Foo/2020/Album1/1.png.json "Foo/2020/Album1"+ *+ * And can thus be used to associate the correct metadata JSON with the+ * corresponding {@link UploadItem}.+ *+ * As a special case, "/metadata" at the end of the path prefix is discarded.+ * This allows the metadata JSON written by export to be read back in during+ * uploads. See: [Note: Fold "metadata" directory into parent folder].+ */+export type UploadPathPrefix = string;++/**+ * Return the {@link UploadPathPrefix} for the given {@link pathOrName} of an+ * item being uploaded.+ */+export const uploadPathPrefix = (pathOrName: string) => {+ const folderPath = dirname(pathOrName);+ if (basename(folderPath) == exportMetadataDirectoryName) {+ return dirname(folderPath);+ }+ return folderPath;+};++export type UploadItemAndPath = [UploadItem, string];++/**+ * Group files that are that have the same parent folder into collections.+ *+ * This is used to segregate the list of {@link UploadItemAndPath}s that we+ * obtain when an upload is initiated into per-collection groups when the user+ * chooses the "parent" {@link CollectionMapping} option.+ *+ * For example, if the user selects files have a directory structure like:+ *+ * a+ * / | \+ * b j c+ * /|\ / \+ * e f g h i+ *+ * The files will grouped into 3 collections:+ *+ * [+ * a => [j],+ * b => [e, f, g],+ * c => [h, i]+ * ]+ *+ * @param defaultFolderName Optional collection name to use for any rooted files+ * that do not have a parent folder. The function will throw if a default is not+ * provided and we encounter any such files without a parent.+ */+export const groupItemsBasedOnParentFolder = (+ uploadItemAndPaths: UploadItemAndPath[],+ defaultFolderName: string | undefined,+) => {+ const result = new Map<string, UploadItemAndPath[]>();+ for (const [uploadItem, pathOrName] of uploadItemAndPaths) {+ const folderPath = dirname(pathOrName);+ let folderName = basename(folderPath);+ // [Note: Fold "metadata" directory into parent folder]+ //+ // If the parent folder of a file is "metadata" (the directory in which+ // the exported JSON files are written), then we consider it to be part+ // of the parent folder.+ //+ // e.g. for the file list+ //+ // [a/x.png, a/metadata/x.png.json]+ //+ // we want both to be grouped into the collection "a". This is so that+ // we can cluster the metadata JSON files in the same collection as the+ // file it is for.+ if (folderName == exportMetadataDirectoryName) {+ folderName = basename(dirname(folderPath));+ }+ if (!folderName) {+ if (!defaultFolderName)+ throw Error(`Leaf file (without default): ${pathOrName}`);+ folderName = defaultFolderName;+ }+ if (!result.has(folderName)) result.set(folderName, []);+ result.get(folderName)!.push([uploadItem, pathOrName]);+ }+ return result;+};++export interface LivePhotoAssets {+ image: UploadItem;+ video: UploadItem;+}++/**+ * An upload item with both parts of a live photo clubbed together.+ *+ * See: [Note: Intermediate file types during upload].+ */+export interface ClusteredUploadItem {+ localID: number;+ collectionID: number;+ fileName: string;+ isLivePhoto: boolean;+ uploadItem?: UploadItem;+ pathPrefix: UploadPathPrefix | undefined;+ // TODO: Tie this to the isLivePhoto flag using a discriminated union.+ livePhotoAssets?: LivePhotoAssets;+}++/**+ * The file that we hand off to the uploader. Essentially+ * {@link ClusteredUploadItem} with the {@link collection} attached to it.+ *+ * See: [Note: Intermediate file types during upload].+ */+export type UploadableUploadItem = ClusteredUploadItem & {+ collection: Collection;+};++/**+ * Result of {@link markUploadedAndObtainProcessableItem}; see the documentation+ * of that function for the meaning and cases of this type.+ */+export type ProcessableUploadItem = File | TimestampedFileSystemUploadItem;++/**+ * As the long name suggests, this function does a rather specific thing:+ *+ * - If we're running in the context of the web app, it will return the+ * {@link File} object that best represents the newly uploaded item. For+ * images and videos, this'll be the newly uploaded file itself. For live+ * photos, this will be the {@link File} object for the image component of the+ * live photo.+ *+ * - If we're running in the context of the desktop app, it will first mark the+ * item as having been uploaded in the persistent pending upload list that the+ * desktop app keeps (so that they can be resumed on restarts). After this,+ * it'll try to convert the item to a {@link TimestampedFileSystemUploadItem}+ * if possible, otherwise will return the web {@link File}. As with the web+ * case, in case of live photos the image component will be used in these+ * transformations.+ *+ * @param item An {@link ClusteredUploadItem} that was recently uploaded.+ */+export const markUploadedAndObtainProcessableItem = async (+ item: ClusteredUploadItem,+): Promise<ProcessableUploadItem> => {+ const electron = globalThis.electron;+ if (!electron) {+ const resultItem = item.isLivePhoto+ ? item.livePhotoAssets!.image+ : item.uploadItem;+ if (resultItem instanceof File) {+ return resultItem;+ } else {+ throw new Error(+ `Unexpected upload item of type "${typeof resultItem}"`,+ );+ }+ }++ const timestamped = async (+ item: FileSystemUploadItem,+ t: Promise<number>,+ ): Promise<TimestampedFileSystemUploadItem> => ({+ fsUploadItem: item,+ lastModifiedMs: await t,+ });++ if (item.isLivePhoto) {+ const [p0, p1] = [+ item.livePhotoAssets!.image,+ item.livePhotoAssets!.video,+ ];+ if (Array.isArray(p0) && Array.isArray(p1)) {+ return timestamped(p0, electron.markUploadedZipItem(p0, p1));+ } else if (typeof p0 == "string" && typeof p1 == "string") {+ return timestamped(p0, electron.markUploadedFile(p0, p1));+ } else if (+ typeof p0 == "object" &&+ "path" in p0 &&+ typeof p1 == "object" &&+ "path" in p1+ ) {+ return timestamped(p0, electron.markUploadedFile(p0.path, p1.path));+ } else {+ throw new Error(+ "Attempting to mark upload completion of unexpected desktop upload items",+ );+ }+ } else {+ const p = item.uploadItem!;+ if (Array.isArray(p)) {+ return timestamped(p, electron.markUploadedZipItem(p));+ } else if (typeof p == "string") {+ return timestamped(p, electron.markUploadedFile(p));+ } else if (typeof p == "object" && "path" in p) {+ return timestamped(p, electron.markUploadedFile(p.path));+ } else {+ return p;+ }+ }+};++/**+ * Convert an {@link TimestampedFileSystemUploadItem} item back into a+ * {@link FileSystemUploadItem} if the underlying file hasn't changed.+ *+ * While this functionality is not directly related to upload, this function is+ * kept here since it is in some sense the inverse of+ * {@link markUploadedAndObtainProcessableItem}.+ *+ * @param item A {@link TimestampedFileSystemUploadItem}.+ *+ * @param fsStatMtime A function that can be used to perform IPC and obtain the+ * last modified time from the node side.+ *+ * @returns If the last modified time of the file system file pointed to by the+ * given {@link item} is the same as what is recorded within the structure, then+ * return the wrapped {@link FileSystemUploadItem}, otherwise return+ * `undefined`.+ *+ * In case of any errors, also return `undefined`. This is because errors are+ * expected if the underlying file system file was, e.g. renamed or removed+ * between the time the file was uploaded and we got around to processing it.+ */+export const fileSystemUploadItemIfUnchanged = async (+ { fsUploadItem, lastModifiedMs }: TimestampedFileSystemUploadItem,+ fsStatMtime: (path: string) => Promise<number>,+): Promise<FileSystemUploadItem | undefined> => {+ let path: string;+ if (typeof fsUploadItem == "string") {+ path = fsUploadItem;+ } else if (Array.isArray(fsUploadItem)) {+ // The last modified time we recorded was of the zip file that contains+ // the entry.+ path = fsUploadItem[0];+ } else {+ path = fsUploadItem.path;+ }++ try {+ const mtimeMs = await fsStatMtime(path);+ if (mtimeMs != lastModifiedMs) {+ log.info(+ `Not using upload item for path '${path}' since modified times have changed`,+ );+ return undefined;+ }+ return fsUploadItem;+ } catch (e) {+ log.warn(`Could not determine modified time for path '${path}'`, e);+ return undefined;+ }+};++/**+ * For each of cases of {@link UploadItem} that apply when we're running in the+ * context of our desktop app, return a value that can be passed to+ * {@link Electron} functions over IPC.+ */+export const toPathOrZipEntry = (fsUploadItem: FileSystemUploadItem) =>+ typeof fsUploadItem == "string" || Array.isArray(fsUploadItem)+ ? fsUploadItem+ : fsUploadItem.path;++export type UploadPhase =+ | "preparing"+ | "readingMetadata"+ | "uploading"+ | "cancelling"+ | "done";++export type UploadResult =+ | { type: "unsupported" }+ | { type: "zeroSize" }+ | { type: "tooLarge" }+ | { type: "largerThanAvailableStorage" }+ | { type: "blocked" }+ | { type: "failed" }+ | { type: "alreadyUploaded"; file: EnteFile }+ | { type: "addedSymlink"; file: EnteFile }+ | { type: "uploadedWithStaticThumbnail"; file: EnteFile }+ | { type: "uploaded"; file: EnteFile };++/**+ * Return true to disable the upload of files via Cloudflare Workers.+ *+ * [Note: Faster uploads via workers]+ *+ * These workers were introduced as a way of make file uploads faster:+ * https://ente.io/blog/tech/making-uploads-faster/+ *+ * By default, that's the route we take. However, there are multiple reasons why+ * this might be disabled.+ *+ * 1. During development and when self-hosting it we disable them to directly+ * upload to the S3-compatible URLs returned by the ente API.+ *+ * 2. In rare cases, the user might have trouble reaching Cloudflare's network+ * from their ISP. In such cases, the user can locally turn this off via+ * settings.+ *+ * 3. There is also the original global toggle that was added when this feature+ * was introduced.+ *+ * This function returns the in-memory value. It is updated when #2 changes (if+ * we're running in a context where that makes sense). The #3 remote status is+ * obtained once, on app start.+ */+export const shouldDisableCFUploadProxy = () =>+ _state.shouldDisableCFUploadProxy;++/**+ * Update the in-memory value of {@link shouldDisableCFUploadProxy}.+ *+ * @param savedPreference An optional user preference that the user has+ * expressed to disable the proxy.+ */+export const updateShouldDisableCFUploadProxy = async (+ savedPreference?: boolean,+) => {+ _state.shouldDisableCFUploadProxy =+ savedPreference || (await computeShouldDisableCFUploadProxy());+};++/**+ * Return `true` if uploads should include checksum metadata.+ */+export const areChecksumProtectedUploadsEnabled = () =>+ _state.checksumProtectedUploadsEnabled;++/**+ * Update the in-memory value controlling checksum protected uploads.+ */+export const updateChecksumProtectedUploadsEnabled = (enabled: boolean) => {+ _state.checksumProtectedUploadsEnabled = enabled;+};++const computeShouldDisableCFUploadProxy = async () => {+ // If a custom origin is set, that means we're not running a production+ // deployment (maybe we're running locally, or being self-hosted).+ //+ // In such cases, disable the Cloudflare upload proxy (which won't work for+ // self-hosters), and instead just directly use the upload URLs that museum+ // gives us.+ if (await customAPIOrigin()) return true;++ // See if the global flag to disable this is set.+ try {+ const res = await fetch("https://static.ente.io/feature_flags.json");+ return (+ StaticFeatureFlags.parse(await res.json()).disableCFUploadProxy ??+ false+ );+ } catch (e) {+ log.warn("Ignoring error when getting feature_flags.json", e);+ return false;+ }+};++const StaticFeatureFlags = z.object({+ disableCFUploadProxy: z.boolean().nullish().transform(nullToUndefined),+});diff --git a/web/apps/albums/vendor/ente-gallery/services/upload/md5.ts b/web/apps/albums/vendor/ente-gallery/services/upload/md5.tsnew file mode 100644index 0000000000..4e4770b6e1--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/upload/md5.ts@@ -0,0 +1,118 @@+/**+ * Minimal MD5 implementation tailored for computing a base64 encoded checksum+ * of Uint8Array inputs.+ *+ * The implementation follows RFC 1321.+ */++const shifts = new Uint8Array([+ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5,+ 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11,+ 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10,+ 15, 21,+]);++const constants = (() => {+ const k = new Uint32Array(64);+ for (let i = 0; i < 64; i++) {+ k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32);+ }+ return k;+})();++const leftRotate = (value: number, amount: number) =>+ (value << amount) | (value >>> (32 - amount));++const toUint8ArrayLE = (word: number) => {+ const bytes = new Uint8Array(4);+ bytes[0] = word & 0xff;+ bytes[1] = (word >>> 8) & 0xff;+ bytes[2] = (word >>> 16) & 0xff;+ bytes[3] = (word >>> 24) & 0xff;+ return bytes;+};++const bytesToBase64 = (bytes: Uint8Array) => {+ if (typeof Buffer != "undefined") {+ return Buffer.from(bytes).toString("base64");+ }+ let binary = "";+ for (const byte of bytes) {+ binary += String.fromCharCode(byte);+ }+ return btoa(binary);+};++export const computeMd5Base64 = (data: Uint8Array): string => {+ const originalLengthBits = data.length * 8;+ const paddedLength =+ (((data.length + 8) >>> 6) << 4) ++ 16; /* (n + 64) rounded up to multiple of 64 bytes, expressed in 32-bit words */+ const words = new Uint32Array(paddedLength);++ for (const [i, value] of data.entries()) {+ const wordIndex = i >> 2;+ const existing = words[wordIndex] ?? 0;+ words[wordIndex] = existing | (value << ((i % 4) * 8));+ }++ const paddingIndex = data.length >> 2;+ const paddingExisting = words[paddingIndex] ?? 0;+ words[paddingIndex] = paddingExisting | (0x80 << ((data.length % 4) * 8));+ words[paddedLength - 2] = originalLengthBits & 0xffffffff;+ words[paddedLength - 1] = (originalLengthBits / 0x100000000) | 0;++ let a = 0x67452301;+ let b = 0xefcdab89;+ let c = 0x98badcfe;+ let d = 0x10325476;++ for (let i = 0; i < words.length; i += 16) {+ let A = a;+ let B = b;+ let C = c;+ let D = d;++ for (let j = 0; j < 64; j++) {+ let f: number;+ let g: number;++ if (j < 16) {+ f = (B & C) | (~B & D);+ g = j;+ } else if (j < 32) {+ f = (D & B) | (~D & C);+ g = (5 * j + 1) % 16;+ } else if (j < 48) {+ f = B ^ C ^ D;+ g = (3 * j + 5) % 16;+ } else {+ f = C ^ (B | ~D);+ g = (7 * j) % 16;+ }++ const temp = D;+ D = C;+ C = B;+ const word = words[i + g] ?? 0;+ const constant = constants[j] ?? 0;+ const shift = shifts[j] ?? 0;+ const sum = (A + f + constant + word) >>> 0;+ B = (B + leftRotate(sum, shift)) >>> 0;+ A = temp;+ }++ a = (a + A) >>> 0;+ b = (b + B) >>> 0;+ c = (c + C) >>> 0;+ d = (d + D) >>> 0;+ }++ const digest = new Uint8Array(16);+ digest.set(toUint8ArrayLE(a), 0);+ digest.set(toUint8ArrayLE(b), 4);+ digest.set(toUint8ArrayLE(c), 8);+ digest.set(toUint8ArrayLE(d), 12);++ return bytesToBase64(digest);+};diff --git a/web/apps/albums/vendor/ente-gallery/services/upload/metadata-json.ts b/web/apps/albums/vendor/ente-gallery/services/upload/metadata-json.tsnew file mode 100644index 0000000000..e54cb19d9c--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/upload/metadata-json.ts@@ -0,0 +1,302 @@+/** @file Dealing with the JSON metadata sidecar files */++import { ensureElectron } from "ente-base/electron";+import { nameAndExtension } from "ente-base/file-name";+import log from "ente-base/log";+import { type Location } from "ente-base/types";+import type {+ UploadItem,+ UploadPathPrefix,+} from "ente-gallery/services/upload";+import { readStream } from "ente-gallery/utils/native-stream";++/**+ * The data we read from the JSON metadata sidecar files.+ *+ * The metadata JSON file format is similar to the JSON metadata sidecar format+ * produced by Google Takeout. This is so that the user can import their Google+ * Takeouts while preserving the metadata.+ *+ * During export the Ente app also writes out its own metadata in a similar and+ * compatible format so that the user can easily round trip (i.e. export their+ * data out of Ente, and import it back again). This also allows users to reuse+ * existing third party tools for working with the takeout format.+ */+export interface ParsedMetadataJSON {+ creationTime?: number;+ modificationTime?: number;+ location?: Location;+ description?: string;+}++/**+ * Derive a key for the given {@link jsonFileName} that should be used to index+ * into the {@link ParsedMetadataJSON} JSON map.+ *+ * @param pathPrefix The {@link UploadPathPrefix}, if available.+ *+ * @param collectionID The collection to which we're uploading.+ *+ * @param jsonFileName The file name for the JSON file.+ *+ * @returns A key suitable for indexing into the metadata JSON map.+ *+ * @see also {@link matchJSONMetadata}.+ */+export const metadataJSONMapKeyForJSON = (+ pathPrefix: UploadPathPrefix | undefined,+ collectionID: number,+ jsonFileName: string,+) =>+ makeKey3(+ pathPrefix,+ collectionID,+ jsonFileName.slice(0, -1 * ".json".length),+ );++const makeKey3 = (+ pathPrefix: UploadPathPrefix | undefined,+ collectionID: number,+ fileName: string,+) => `${pathPrefix ?? ""}-${collectionID}-${fileName}`;++/**+ * Return the matching entry, if any, from {@link parsedMetadataJSONMap} for the+ * {@link pathPrefix}, {@link collectionID} and {@link fileName} combination.+ *+ * This is the sibling of {@link metadataJSONMapKeyForJSON}, except for deriving+ * the filename key we might have to try a bunch of different variations, so+ * this does not return a single key but instead tries the combinations until it+ * finds an entry in the map, and returns the found entry instead of the key.+ *+ * In brief,+ *+ * - When inserting the metadata entry into {@link parsedMetadataJSONMap}, we+ * use {@link metadataJSONMapKeyForJSON}.+ *+ * - When reading back the metadata entry from {@link parsedMetadataJSONMap}, we+ * use {@link matchJSONMetadata}+ */+export const matchJSONMetadata = (+ pathPrefix: UploadPathPrefix | undefined,+ collectionID: number,+ fileName: string,+ parsedMetadataJSONMap: Map<string, ParsedMetadataJSON>,+) => {+ // Break the fileName down into its components.+ let [name, extension] = nameAndExtension(fileName);+ if (extension) {+ extension = "." + extension;+ }++ // Save the original name before any modifications for fallback lookups.+ const originalName = name;++ // Trim off a suffix like "(1)" from the name, remembering what we trimmed+ // since we need to add it back later.+ //+ // It needs to be handled separately because of the clipping (see below).+ // The numbered suffix (if present) is not clipped. It is added at the end+ // of the clipped ".supplemental-metadata" portion, instead of after the+ // original filename.+ //+ // For example, "IMG_1234(1).jpg" would have a metadata filename of either+ // "IMG_1234.jpg(1).json" or "IMG_1234.jpg.supplemental-metadata(1).json".+ // And if the filename is too long, it gets turned into something like+ // "IMG_1234.jpg.suppl(1).json".++ let numberedSuffix = "";+ const endsWithNumberedSuffixWithBrackets = /\(\d+\)$/.exec(name);+ if (endsWithNumberedSuffixWithBrackets) {+ name = name.slice(0, -1 * endsWithNumberedSuffixWithBrackets[0].length);+ numberedSuffix = endsWithNumberedSuffixWithBrackets[0];+ }++ // Removes the "-edited" suffix, if present, so that the edited file can be+ // associated to the original file's metadataJSON file as edited files don't+ // have their own metadata files.++ const editedFileSuffix = "-edited";+ if (name.endsWith(editedFileSuffix)) {+ name = name.slice(0, -1 * editedFileSuffix.length);+ }++ // Convenience function to vary only the file name component when+ // constructing a key. Delegates to `makeKey3`.+ const makeKey = (fn: string) => makeKey3(pathPrefix, collectionID, fn);++ // Derive a key from the collection name, file name and the suffix if any.+ let baseFileName = `${name}${extension}`;+ let key = makeKey(`${baseFileName}${numberedSuffix}`);++ let takeoutMetadata = parsedMetadataJSONMap.get(key);+ if (takeoutMetadata) return takeoutMetadata;++ // If the file name is greater than 46 characters, then Google Photos, with+ // its infinite storage, clips the file name. In such cases we need to use+ // the clipped file name to get the key.++ const maxGoogleFileNameLength = 46;+ key = makeKey(+ `${baseFileName.slice(0, maxGoogleFileNameLength)}${numberedSuffix}`,+ );++ takeoutMetadata = parsedMetadataJSONMap.get(key);+ if (takeoutMetadata) return takeoutMetadata;++ // Newer Takeout exports are attaching a ".supplemental-metadata" suffix to+ // the file name of the metadataJSON file, you know, just to cause havoc,+ // and then clipping the file name if it's too long (ending up with+ // filenames "very_long_file_name.jpg.supple.json").+ //+ // Note that If the original filename is longer than 46 characters, then the+ // ".supplemental-metadata" suffix gets completely removed during the+ // clipping, along with a portion of the original filename (as before).+ //+ // For example, if the original filename is 45 characters long, then+ // everything except for the "." from ".supplemental-metadata" will get+ // clipped. So the metadata file ends up with a filename like+ // "filename_that_is_45_chars_long.jpg..json".++ const supplSuffix = ".supplemental-metadata";+ baseFileName = `${name}${extension}${supplSuffix}`;+ key = makeKey(+ `${baseFileName.slice(0, maxGoogleFileNameLength)}${numberedSuffix}`,+ );++ takeoutMetadata = parsedMetadataJSONMap.get(key);+ if (takeoutMetadata) return takeoutMetadata;++ // Some Google Takeout exports keep the numbered suffix in its original+ // position instead of moving it to the end. For example, "skytree (2).jpg"+ // may have metadata in "skytree (2).jpg.supplemental-metadata.json" instead+ // of "skytree.jpg.supplemental-metadata(2).json". Try that pattern too.+ if (numberedSuffix) {+ const originalBaseFileName = `${originalName}${extension}${supplSuffix}`;+ key = makeKey(originalBaseFileName.slice(0, maxGoogleFileNameLength));+ takeoutMetadata = parsedMetadataJSONMap.get(key);+ }++ return takeoutMetadata;+};++/**+ * Try to parse the contents of a metadata JSON file from a Google Takeout.+ */+export const tryParseTakeoutMetadataJSON = async (+ uploadItem: UploadItem,+): Promise<ParsedMetadataJSON | undefined> => {+ try {+ return parseMetadataJSONText(await uploadItemText(uploadItem));+ } catch (e) {+ log.error("Failed to parse takeout metadata JSON", e);+ return undefined;+ }+};++const uploadItemText = async (uploadItem: UploadItem) => {+ if (uploadItem instanceof File) {+ return await uploadItem.text();+ } else if (typeof uploadItem == "string") {+ return await ensureElectron().fs.readTextFile(uploadItem);+ } else if (Array.isArray(uploadItem)) {+ const { response } = await readStream(ensureElectron(), uploadItem);+ return await response.text();+ } else {+ return await uploadItem.file.text();+ }+};++const parseMetadataJSONText = (text: string) => {+ const metadataJSON_ = JSON.parse(text) as unknown;+ // Ignore non objects.+ if (typeof metadataJSON_ != "object") return undefined;+ // Ignore null.+ if (!metadataJSON_) return undefined;+ // Ignore arrays.+ if (Array.isArray(metadataJSON_)) return undefined;++ // At this point, `metadataJSON_` is an `object`, but TypeScript won't let+ // me index it. The following is the simplest (but unsafe) way I could think+ // of for convincing TypeScript to allow me to index `metadataJSON` with+ // `string`s.+ const metadataJSON = metadataJSON_ as Record<string, unknown>;++ const parsedMetadataJSON: ParsedMetadataJSON = {};++ parsedMetadataJSON.creationTime =+ parseGTTimestamp(metadataJSON.photoTakenTime) ??+ parseGTTimestamp(metadataJSON.creationTime);++ parsedMetadataJSON.modificationTime = parseGTTimestamp(+ metadataJSON.modificationTime,+ );++ parsedMetadataJSON.location =+ parseGTLocation(metadataJSON.geoData) ??+ parseGTLocation(metadataJSON.geoDataExif);++ parsedMetadataJSON.description = parseGTNonEmptyString(+ metadataJSON.description,+ );++ return parsedMetadataJSON;+};++/**+ * Parse a nullish epoch seconds timestamp string from a field in a Google+ * Takeout JSON, converting it into epoch microseconds if it is found.+ *+ * Note that the metadata provided by Google does not include the time zone+ * where the photo was taken, it only has an epoch seconds value. There is an+ * associated formatted date value (e.g. "17 Feb 2021, 03:22:16 UTC") but that+ * seems to be in UTC and doesn't have the time zone either.+ */+const parseGTTimestamp = (o: unknown): number | undefined => {+ if (o && typeof o == "object" && "timestamp" in o) {+ const ot = o.timestamp;+ let timestamp: number | undefined;+ if (typeof ot == "string") {+ timestamp = parseInt(ot, 10);+ } else if (typeof ot == "number") {+ // Ente desktop 1.7.11 and earlier used to write out a number, which+ // is the correct datatype, but that makes it inconsistent with the+ // numbers-as-string that Google takeout writes.+ //+ // So now we write out strings, and read either.+ timestamp = Math.floor(ot);+ }+ if (timestamp && !Number.isNaN(timestamp)) {+ return timestamp * 1e6;+ }+ }+ return undefined;+};++/**+ * Parse a (latitude, longitude) location pair field in a Google Takeout JSON.+ *+ * Apparently Google puts in (0, 0) to indicate missing data, so this function+ * only returns a parsed result if both components are present and non-zero.+ */+const parseGTLocation = (o: unknown): Location | undefined => {+ if (+ o &&+ typeof o == "object" &&+ "latitude" in o &&+ typeof o.latitude == "number" &&+ "longitude" in o &&+ typeof o.longitude == "number"+ ) {+ const { latitude, longitude } = o;+ if (latitude !== 0 || longitude !== 0) return { latitude, longitude };+ }+ return undefined;+};++/**+ * Parse a string from a field in a Google Takeout JSON, treating empty strings+ * as undefined.+ */+const parseGTNonEmptyString = (o: unknown): string | undefined =>+ o && typeof o == "string" ? o : undefined;diff --git a/web/apps/albums/vendor/ente-gallery/services/upload/remote.ts b/web/apps/albums/vendor/ente-gallery/services/upload/remote.tsnew file mode 100644index 0000000000..c211f8f59f--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/upload/remote.ts@@ -0,0 +1,641 @@+import {+ authenticatedPublicAlbumsRequestHeaders,+ authenticatedRequestHeaders,+ ensureOk,+ publicRequestHeaders,+ type HTTPRequestRetrier,+ type PublicAlbumsCredentials,+} from "ente-base/http";+import { apiURL, uploaderOrigin } from "ente-base/origins";+import { RemoteEnteFile, type RemoteFileMetadata } from "ente-media/file";+import type { RemoteMagicMetadata } from "ente-media/magic-metadata";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";++/**+ * A pre-signed URL alongwith the associated object key that is later used to+ * refer to file contents (the "object") that were uploaded to this URL.+ */+const ObjectUploadURL = z.object({+ /**+ * The objectKey with which remote (both museum and the S3 bucket) will+ * refer to this object once it has been uploaded.+ */+ objectKey: z.string(),+ /**+ * A pre-signed URL that can be used to upload data to an S3-compatible+ * remote.+ */+ url: z.string(),+});++export type ObjectUploadURL = z.infer<typeof ObjectUploadURL>;++const ObjectUploadURLResponse = z.object({ urls: ObjectUploadURL.array() });++/**+ * Fetch a fresh list of URLs from remote that can be used to upload objects.+ *+ * @param countHint An approximate number of objects that we're expecting to+ * upload.+ *+ * @returns A list of pre-signed object URLs that can be used to upload data to+ * the S3 bucket. Each URL also has an associated "object key" with which remote+ * will refer to the uploaded object after it has been uploaded.+ */+export const fetchUploadURLs = async (countHint: number) => {+ const count = Math.min(50, countHint * 2);+ const res = await fetch(+ await apiURL("/files/upload-urls", { count, ts: Date.now() }),+ { headers: await authenticatedRequestHeaders() },+ );+ ensureOk(res);+ return ObjectUploadURLResponse.parse(await res.json()).urls;+};++export const fetchUploadURLWithMetadata = async ({+ contentLength,+ contentMd5,+}: {+ contentLength: number;+ contentMd5: string;+}) => {+ const headers = new Headers(await authenticatedRequestHeaders());+ headers.set("Content-Type", "application/json");+ const res = await fetch(+ await apiURL("/files/upload-url", { ts: Date.now() }),+ {+ method: "POST",+ headers,+ body: JSON.stringify({ contentLength, contentMD5: contentMd5 }),+ },+ );+ ensureOk(res);+ return ObjectUploadURL.parse(await res.json());+};++/**+ * Sibling of {@link fetchUploadURLWithMetadata} for public albums.+ */+export const fetchPublicAlbumsUploadURLWithMetadata = async (+ {+ contentLength,+ contentMd5,+ }: { contentLength: number; contentMd5: string },+ credentials: PublicAlbumsCredentials,+) => {+ const headers = new Headers(+ authenticatedPublicAlbumsRequestHeaders(credentials),+ );+ headers.set("Content-Type", "application/json");+ const res = await fetch(+ await apiURL("/public-collection/upload-url", { ts: Date.now() }),+ {+ method: "POST",+ headers,+ body: JSON.stringify({ contentLength, contentMD5: contentMd5 }),+ },+ );+ ensureOk(res);+ return ObjectUploadURL.parse(await res.json());+};++export const fetchMultipartUploadURLsWithMetadata = async ({+ contentLength,+ partLength,+ partMd5s,+}: {+ contentLength: number;+ partLength: number;+ partMd5s: string[];+}) => {+ const headers = new Headers(await authenticatedRequestHeaders());+ headers.set("Content-Type", "application/json");+ const res = await fetch(+ await apiURL("/files/multipart-upload-url", { ts: Date.now() }),+ {+ method: "POST",+ headers,+ body: JSON.stringify({ contentLength, partLength, partMd5s }),+ },+ );+ ensureOk(res);+ return MultipartUploadURLs.parse(await res.json());+};++/**+ * Sibling of {@link fetchMultipartUploadURLsWithMetadata} for public albums.+ */+export const fetchPublicAlbumsMultipartUploadURLsWithMetadata = async (+ {+ contentLength,+ partLength,+ partMd5s,+ }: { contentLength: number; partLength: number; partMd5s: string[] },+ credentials: PublicAlbumsCredentials,+) => {+ const headers = new Headers(+ authenticatedPublicAlbumsRequestHeaders(credentials),+ );+ headers.set("Content-Type", "application/json");+ const res = await fetch(+ await apiURL("/public-collection/multipart-upload-url", {+ ts: Date.now(),+ }),+ {+ method: "POST",+ headers,+ body: JSON.stringify({ contentLength, partLength, partMd5s }),+ },+ );+ ensureOk(res);+ return MultipartUploadURLs.parse(await res.json());+};++/**+ * Sibling of {@link fetchUploadURLs} for public albums.+ */+export const fetchPublicAlbumsUploadURLs = async (+ countHint: number,+ credentials: PublicAlbumsCredentials,+) => {+ const count = Math.min(50, countHint * 2);+ const res = await fetch(+ await apiURL("/public-collection/upload-urls", {+ count,+ ts: Date.now(),+ }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ return ObjectUploadURLResponse.parse(await res.json()).urls;+};++/**+ * A list of URLs to use for multipart uploads.+ *+ * This is a list of pre-signed URLs (one for each part), a URL to indicate+ * completion, and an associated object key that is later used to refer to the+ * combined object from the parts there were uploaded to the part URLs.+ */+const MultipartUploadURLs = z.object({+ /**+ * The objectKey with which remote (museum and the S3 bucket) will refer to+ * this object once it has been uploaded.+ */+ objectKey: z.string(),+ /**+ * A list of pre-signed URLs that can be used to upload the parts of the+ * entire file's data to an S3-compatible remote.+ */+ partURLs: z.string().array(),+ /**+ * A pre-signed URL that can be used to finalize the multipart upload into a+ * single object on remote by providing the list of parts that were uploaded+ * (and their sequence) to the S3-compatible remote.+ */+ completeURL: z.string(),+});++export type MultipartUploadURLs = z.infer<typeof MultipartUploadURLs>;++const MultipartUploadURLsResponse = z.object({ urls: MultipartUploadURLs });++/**+ * Fetch a {@link MultipartUploadURLs} structure from remote that can be used to+ * upload a large object by splitting it into {@link uploadPartCount} parts.+ *+ * See: [Note: Multipart uploads].+ *+ * @param uploadPartCount The number of parts in which we want to upload the+ * object.+ *+ * @returns A structure ({@link MultipartUploadURLs}) containing pre-signed URLs+ * for uploading each part, a completion URL, and the final object key.+ */+export const fetchMultipartUploadURLs = async (uploadPartCount: number) => {+ const count = uploadPartCount;+ const res = await fetch(+ await apiURL("/files/multipart-upload-urls", { count, ts: Date.now() }),+ { headers: await authenticatedRequestHeaders() },+ );+ ensureOk(res);+ return MultipartUploadURLsResponse.parse(await res.json()).urls;+};++/**+ * Sibling of {@link fetchMultipartUploadURLs} for public albums.+ */+export const fetchPublicAlbumsMultipartUploadURLs = async (+ uploadPartCount: number,+ credentials: PublicAlbumsCredentials,+) => {+ const count = uploadPartCount;+ const res = await fetch(+ await apiURL("/public-collection/multipart-upload-urls", {+ count,+ ts: Date.now(),+ }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ return MultipartUploadURLsResponse.parse(await res.json()).urls;+};++/**+ * Upload a file using a pre-signed URL.+ *+ * @param fileUploadURL A pre-signed URL that can be used to upload data to the+ * remote S3-compatible storage.+ *+ * @param fileData The data to upload.+ *+ * @param retrier A function to wrap the request in retries if needed.+ */+interface PutFileOptions {+ contentMd5?: string;+}++interface PutPartOptions {+ contentMd5?: string;+}++export const putFile = async (+ fileUploadURL: string,+ fileData: Uint8Array,+ retrier: HTTPRequestRetrier,+ options?: PutFileOptions,+) =>+ retrier(() =>+ fetch(fileUploadURL, {+ method: "PUT",+ headers: {+ ...publicRequestHeaders(),+ ...(options?.contentMd5 && {+ "Content-MD5": options.contentMd5,+ }),+ },+ body: fileData,+ }),+ );++/**+ * Variant of {@link putFile} that uses a CF worker.+ */+export const putFileViaWorker = async (+ fileUploadURL: string,+ fileData: Uint8Array,+ retrier: HTTPRequestRetrier,+ options?: PutFileOptions,+) =>+ retrier(async () =>+ fetch(`${await uploaderOrigin()}/file-upload`, {+ method: "PUT",+ headers: {+ ...publicRequestHeaders(),+ "UPLOAD-URL": fileUploadURL,+ ...(options?.contentMd5 && {+ "CONTENT-MD5": options.contentMd5,+ }),+ },+ body: fileData,+ }),+ );++/**+ * Upload a part of a multipart upload using a pre-signed URL.+ *+ * See: [Note: Multipart uploads].+ *+ * @param partUploadURL A pre-signed URL that can be used to upload data to the+ * remote S3-compatible storage.+ *+ * @param partData The part bytes to upload.+ *+ * @param retrier A function to wrap the request in retries if needed.+ *+ * @returns the value of the "ETag" header in the remote response, or+ * `undefined` if the ETag was not present in the response (this is not expected+ * from remote in case of a successful response, but it can happen in case the+ * user has some misconfigured browser extension which is blocking the ETag+ * header from being parsed).+ */+export const putFilePart = async (+ partUploadURL: string,+ partData: Uint8Array,+ retrier: HTTPRequestRetrier,+ options?: PutPartOptions,+) => {+ const res = await retrier(() =>+ fetch(partUploadURL, {+ method: "PUT",+ headers: {+ ...publicRequestHeaders(),+ ...(options?.contentMd5 && {+ "Content-MD5": options.contentMd5,+ }),+ },+ body: partData,+ }),+ );+ return nullToUndefined(res.headers.get("etag"));+};++/**+ * Variant of {@link putFilePart} that uses a CF worker.+ */+export const putFilePartViaWorker = async (+ partUploadURL: string,+ partData: Uint8Array,+ retrier: HTTPRequestRetrier,+ options?: PutPartOptions,+) => {+ const origin = await uploaderOrigin();+ const res = await retrier(() =>+ fetch(`${origin}/multipart-upload`, {+ method: "PUT",+ headers: {+ ...publicRequestHeaders(),+ "UPLOAD-URL": partUploadURL,+ ...(options?.contentMd5 && {+ "CONTENT-MD5": options.contentMd5,+ }),+ },+ body: partData,+ }),+ );+ return z.object({ etag: z.string() }).parse(await res.json()).etag;+};++/**+ * Information about an individual part of a multipart upload that has been+ * uploaded to the remote (S3 or proxy).+ *+ * See: [Note: Multipart uploads].+ */+export interface MultipartCompletedPart {+ /**+ * The part number (1-indexed).+ *+ * The part number indicates the sequential ordering where this part belongs+ * in the overall file's data.+ */+ partNumber: number;+ /**+ * The part "ETag".+ *+ * This is the Entity tag (retrieved as the "ETag" response header) returned+ * by remote when the part was uploaded.+ */+ eTag: string;+}++/**+ * Construct an XML string of the format expected as the request body for+ * {@link _completeMultipartUpload} or+ * {@link _completeMultipartUploadViaWorker}.+ *+ * @param parts Information about the parts that were uploaded.+ */+const createMultipartUploadRequestBody = (+ parts: MultipartCompletedPart[],+): string => {+ // To avoid introducing a dependency on a XML library, we construct the+ // requisite XML by hand.+ //+ // Example:+ //+ // <CompleteMultipartUpload>+ // <Part>+ // <PartNumber>1</PartNumber>+ // <ETag>"1b3e6cdb1270c0b664076f109a7137c1"</ETag>+ // </Part>+ // <Part>+ // <PartNumber>2</PartNumber>+ // <ETag>"6049d6384a9e65694c833a3aca6584fd"</ETag>+ // </Part>+ // <Part>+ // <PartNumber>3</PartNumber>+ // <ETag>"331747eae8068f03b844e6f28cc0ed23"</ETag>+ // </Part>+ // </CompleteMultipartUpload>+ //+ //+ // Spec:+ // https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html+ //+ // <CompleteMultipartUpload>+ // <Part>+ // <PartNumber>integer</PartNumber>+ // <ETag>string</ETag>+ // </Part>+ // ...+ // </CompleteMultipartUpload>+ //+ // Note that in the example given on the spec page, the etag strings are quoted:+ //+ // <CompleteMultipartUpload>+ // <Part>+ // <PartNumber>1</PartNumber>+ // <ETag>"a54357aff0632cce46d942af68356b38"</ETag>+ // </Part>+ // ...+ // </CompleteMultipartUpload>+ //+ // No extra quotes need to be added, the etag values we get from remote+ // already quoted, we just need to pass them verbatim.++ const resultParts = parts.map(+ (part) =>+ `<Part><PartNumber>${part.partNumber}</PartNumber><ETag>${part.eTag}</ETag></Part>`,+ );+ return `<CompleteMultipartUpload>\n${resultParts.join("\n")}\n</CompleteMultipartUpload>`;+};++/**+ * Complete a multipart upload by reporting information about all the uploaded+ * parts to the provided {@link completionURL}.+ *+ * @param completionURL A pre-signed URL to which the final status of the+ * uploaded parts should be reported to.+ *+ * @param completedParts Information about all the parts of the file that have+ * been uploaded. The part numbers must start at 1 and must be consecutive.+ *+ * @param retrier A function to wrap the request in retries if needed.+ *+ * [Note: Multipart uploads]+ *+ * Multipart uploads are a mechanism to upload large files onto an remote+ * storage bucket by breaking it into smaller chunks / "parts", uploading each+ * part separately, and then reporting the consolidated information of all the+ * uploaded parts to a URL that marks the upload as complete on remote.+ *+ * This allows greater resilience since uploads of individual parts can be+ * retried independently without failing the entire upload on transient network+ * issues. This also helps self hosters, since often cloud providers have limits+ * to the size of single requests that they'll allow through (e.g. the+ * Cloudflare free plan currently has a 100 MB request size limit).+ *+ * The flow is implemented in two ways:+ *+ * a. The normal way, where each requests is made to a remote S3 bucket directly+ * using the pre-signed URL.+ *+ * b. Using workers, where the requests are proxied via a worker near to the+ * user's network to speed the requests up.+ *+ * See [Note: Faster uploads via workers] for more details on the worker flow.+ *+ * In both cases, the overall flow is roughly like the following:+ *+ * 1. Obtain multiple pre-signed URLs from remote (museum). The specific API+ * call will be different (because of the different authentication+ * mechanisms) when we're running in the context of the photos app+ * ({@link fetchMultipartUploadURLs}) and when we're running in the context+ * of the public albums app ({@link fetchPublicAlbumsMultipartUploadURLs}).+ *+ * 2. Break the file to be uploaded into parts, and upload each part using a PUT+ * request to one of the pre-signed URLs we got in step 1. There are two+ * variants of this - one where we directly upload to the remote (S3)+ * ({@link putFilePart}), and one where we go via a worker+ * ({@link putFilePartViaWorker}).+ *+ * 3. Once all the parts have been uploaded, send a consolidated report of all+ * the uploaded parts (the step 2's) to remote via another pre-signed+ * "completion URL" that we also got in step 1. Like step 2, there are 2+ * variants of this - one where we directly tell the remote (S3)+ * ({@link completeMultipartUpload}), and one where we report via a worker+ * ({@link completeMultipartUploadViaWorker}).+ */+export const completeMultipartUpload = (+ completionURL: string,+ completedParts: MultipartCompletedPart[],+ retrier: HTTPRequestRetrier,+) =>+ retrier(() =>+ fetch(completionURL, {+ method: "POST",+ headers: { ...publicRequestHeaders(), "Content-Type": "text/xml" },+ body: createMultipartUploadRequestBody(completedParts),+ }),+ );++/**+ * Variant of {@link completeMultipartUpload} that uses a CF worker.+ */+export const completeMultipartUploadViaWorker = async (+ completionURL: string,+ completedParts: MultipartCompletedPart[],+ retrier: HTTPRequestRetrier,+) =>+ retrier(async () =>+ fetch(`${await uploaderOrigin()}/multipart-complete`, {+ method: "POST",+ headers: {+ ...publicRequestHeaders(),+ "Content-Type": "text/xml",+ "UPLOAD-URL": completionURL,+ },+ body: createMultipartUploadRequestBody(completedParts),+ }),+ );++export interface PostEnteFileRequest {+ collectionID: number;+ encryptedKey: string;+ keyDecryptionNonce: string;+ file: UploadedFileObjectAttributes;+ thumbnail: UploadedFileObjectAttributes;+ metadata: RemoteFileMetadata;+ pubMagicMetadata?: RemoteMagicMetadata;+}++/**+ * Attributes about an object uploaded to S3.+ *+ * This is similar to the {@link FileObjectAttributes} that we get back in the+ * {@link EnteFile} we get from remote, however it contains more fields.+ *+ * - When we're finalizing the upload of {@link EnteFile}, we have at our+ * disposal the {@link objectKey}, {@link decryptionHeader} and {@link size}+ * attributes that we need to set in the POST "/files" request.+ *+ * - Later when we get back the file from remote as an {@link EnteFile}, it will+ * only have the {@link decryptionHeader}. This is all we need for obtaining+ * the decrypted file: the contents of the file get fetched (on demand) using+ * a presigned URL, and the file's key is the decryption key, so armed with+ * this decryption header we are good to go.+ */+export interface UploadedFileObjectAttributes {+ /**+ * The "key" (unique ID) of the S3 object that was uploaded.+ *+ * This is not related to encryption, it is the "objectKey" that uniquely+ * identifies the S3 object that was uploaded. We get these as part of the+ * {@link ObjectUploadURL} we get from remote. We upload the contents of the+ * object (e.g. file, thumbnail) to the corresponding URL, and then report+ * back the "objectKey" in the upload finalization request.+ */+ objectKey: string;+ /**+ * The decryption header that was used when encrypting the objects's+ * contents (with the file's key) before uploading them to S3 remote.+ *+ * The {@link decryptionHeader} is both required when finalizing the upload,+ * and is also returned as part of the {@link EnteFile} that clients get+ * back from remote since it is needed (along with the file's key) to+ * decrypt the object that the client would download from S3 remote.+ */+ decryptionHeader: string;+ /**+ * The size of the uploaded object, in bytes.+ *+ * For both file and thumbnails, the client also sends the size of the+ * encrypted file (as per the client) while creating a new object on remote.+ * This allows the server to validate that the size of the objects is same+ * as what client is reporting.+ *+ * This should be present during upload, but is not returned back from+ * remote in the /diff response.+ */+ size: number;+}++/**+ * Create a new {@link EnteFile} on remote by providing remote with information+ * about the file's contents (objects) that were uploaded, and other metadata+ * about the file.+ *+ * Remote only, does not modify local state.+ *+ * @returns the newly created {@link EnteFile}.+ */+export const postEnteFile = async (+ postFileRequest: PostEnteFileRequest,+): Promise<RemoteEnteFile> => {+ const res = await fetch(await apiURL("/files"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(postFileRequest),+ });+ ensureOk(res);+ return RemoteEnteFile.parse(await res.json());+};++/**+ * Sibling of {@link postEnteFile} for public albums.+ */+export const postPublicAlbumsEnteFile = async (+ postFileRequest: PostEnteFileRequest,++ credentials: PublicAlbumsCredentials,+): Promise<RemoteEnteFile> => {+ const res = await fetch(await apiURL("/public-collection/file"), {+ method: "POST",+ headers: authenticatedPublicAlbumsRequestHeaders(credentials),+ body: JSON.stringify(postFileRequest),+ });+ ensureOk(res);+ return RemoteEnteFile.parse(await res.json());+};diff --git a/web/apps/albums/vendor/ente-gallery/services/upload/thumbnail.ts b/web/apps/albums/vendor/ente-gallery/services/upload/thumbnail.tsnew file mode 100644index 0000000000..c7c645bb36--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/upload/thumbnail.ts@@ -0,0 +1,239 @@+import log from "ente-base/log";+import { type Electron } from "ente-base/types/ipc";+import * as ffmpeg from "ente-gallery/services/ffmpeg";+import {+ toPathOrZipEntry,+ type FileSystemUploadItem,+} from "ente-gallery/services/upload";+import { FileType, type FileTypeInfo } from "ente-media/file-type";+import { isHEICExtension } from "ente-media/formats";+import { heicToJPEG } from "ente-media/heic-convert";+import { scaledImageDimensions } from "ente-media/image";+import { withTimeout } from "ente-utils/promise";++/** Maximum width or height of the generated thumbnail */+const maxThumbnailDimension = 720;+/** Maximum size (in bytes) of the generated thumbnail */+const maxThumbnailSize = 100 * 1024; // 100 KB++/**+ * Timeout (ms) to wait before giving up on canvas thumbnail generation.+ *+ * [Note: Rendering arbitrary file types to the canvas needs a timeout]+ *+ * When generating thumbnails on the web (or as a fallback on the desktop app),+ * we use an HTML canvas. We take the file's content, a blob, and load it on the+ * canvas by creating an image URL for this blob (using `createObjectURL`).+ *+ * In case when the browser knows how to render images of this type, this works+ * great. Later we can read off the thumbnail from the (resized) canvas.+ *+ * However, if this in not a file format that the browser can understand, then+ * this process just hangs. There isn't a trivial way of knowing beforehand+ * which browser will support which file type, so we need to add a timeout.+ */+const canvasThumbnailGenerationTimeout = 30 * 1000;++/**+ * Generate a JPEG thumbnail for the given image or video blob.+ *+ * The thumbnail has a smaller file size so that is quick to load. But more+ * importantly, it uses a universal file format (JPEG in our case) so that the+ * thumbnail itself can be opened in all clients, even those like the web client+ * itself that might not yet have support for more exotic formats.+ *+ * @param blob The image or video blob whose thumbnail we want to generate.+ *+ * @param fileTypeInfo The type information for the file this blob came from.+ *+ * @return The JPEG data of the generated thumbnail.+ */+export const generateThumbnailWeb = async (+ blob: Blob,+ fileTypeInfo: FileTypeInfo,+): Promise<Uint8Array> =>+ fileTypeInfo.fileType == FileType.image+ ? await generateImageThumbnailWeb(blob, fileTypeInfo)+ : await generateVideoThumbnailWeb(blob);++const generateImageThumbnailWeb = async (+ blob: Blob,+ { extension }: FileTypeInfo,+) => {+ if (isHEICExtension(extension)) {+ log.debug(() => `Pre-converting HEIC to JPEG for thumbnail generation`);+ blob = await heicToJPEG(blob);+ }++ return generateImageThumbnailUsingCanvas(blob);+};++const generateImageThumbnailUsingCanvas = async (blob: Blob) => {+ const canvas = document.createElement("canvas");+ const canvasCtx = canvas.getContext("2d")!;++ const imageURL = URL.createObjectURL(blob);+ await withTimeout(+ new Promise((resolve, reject) => {+ const image = new Image();+ image.setAttribute("src", imageURL);+ image.onload = () => {+ try {+ URL.revokeObjectURL(imageURL);+ const { width, height } = scaledImageDimensions(+ image.width,+ image.height,+ maxThumbnailDimension,+ );+ canvas.width = width;+ canvas.height = height;+ canvasCtx.drawImage(image, 0, 0, width, height);+ resolve(undefined);+ } catch (e: unknown) {+ // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors+ reject(e);+ }+ };+ }),+ canvasThumbnailGenerationTimeout,+ );++ return await compressedJPEGData(canvas);+};++const compressedJPEGData = async (canvas: HTMLCanvasElement) => {+ let blob: Blob | undefined | null;+ let prevSize = Number.MAX_SAFE_INTEGER;+ let quality = 0.7;++ do {+ if (blob) prevSize = blob.size;+ blob = await new Promise((resolve) => {+ canvas.toBlob((blob) => resolve(blob), "image/jpeg", quality);+ });+ quality -= 0.1;+ } while (+ quality >= 0.5 &&+ blob &&+ blob.size > maxThumbnailSize &&+ percentageSizeDiff(blob.size, prevSize) >= 10+ );++ return new Uint8Array(await blob!.arrayBuffer());+};++const percentageSizeDiff = (+ newThumbnailSize: number,+ oldThumbnailSize: number,+) => ((oldThumbnailSize - newThumbnailSize) * 100) / oldThumbnailSize;++const generateVideoThumbnailWeb = async (blob: Blob) => {+ try {+ return await ffmpeg.generateVideoThumbnailWeb(blob);+ } catch (e) {+ log.error(+ `Failed to generate video thumbnail using the Wasm FFmpeg web worker, will fallback to canvas`,+ e,+ );+ return generateVideoThumbnailUsingCanvas(blob);+ }+};++export const generateVideoThumbnailUsingCanvas = async (blob: Blob) => {+ const canvas = document.createElement("canvas");+ const canvasCtx = canvas.getContext("2d")!;++ const videoURL = URL.createObjectURL(blob);+ await withTimeout(+ new Promise((resolve, reject) => {+ const video = document.createElement("video");+ video.preload = "metadata";+ video.src = videoURL;+ video.addEventListener("loadeddata", () => {+ try {+ URL.revokeObjectURL(videoURL);+ const { width, height } = scaledImageDimensions(+ video.videoWidth,+ video.videoHeight,+ maxThumbnailDimension,+ );+ canvas.width = width;+ canvas.height = height;+ canvasCtx.drawImage(video, 0, 0, width, height);+ resolve(undefined);+ } catch (e) {+ // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors+ reject(e);+ }+ });+ }),+ canvasThumbnailGenerationTimeout,+ );++ return await compressedJPEGData(canvas);+};++/**+ * Generate a JPEG thumbnail for the given file or path using native tools.+ *+ * This function only works when we're running in the context of our desktop+ * app, and this dependency is enforced by the need to pass the {@link electron}+ * object which we use to perform IPC with the Node.js side of our desktop app.+ *+ * @param fsUploadItem The image or video file on the user's file system whose+ * thumbnail we want to generate.+ *+ * @param fileTypeInfo The type information for {@link fsUploadItem}.+ *+ * @return The JPEG data of the generated thumbnail.+ *+ * See also {@link generateThumbnailWeb}.+ */+export const generateThumbnailNative = async (+ electron: Electron,+ fsUploadItem: FileSystemUploadItem,+ fileTypeInfo: FileTypeInfo,+): Promise<Uint8Array> =>+ fileTypeInfo.fileType == FileType.image+ ? await electron.generateImageThumbnail(+ toPathOrZipEntry(fsUploadItem),+ maxThumbnailDimension,+ maxThumbnailSize,+ )+ : ffmpeg.generateVideoThumbnailNative(electron, fsUploadItem);++/**+ * A fallback, black, thumbnail for use in cases where thumbnail generation+ * fails.+ */+export const fallbackThumbnail = () =>+ Uint8Array.from(atob(blackThumbnailB64), (c) => c.charCodeAt(0));++const blackThumbnailB64 =+ "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEB" ++ "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQ" ++ "EBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARC" ++ "ACWASwDAREAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF" ++ "BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk" ++ "6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztL" ++ "W2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAA" ++ "AAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVY" ++ "nLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImK" ++ "kpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oAD" ++ "AMBAAIRAxEAPwD/AD/6ACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA" ++ "CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg" ++ "AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKAC" ++ "gAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo" ++ "AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg" ++ "AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg" ++ "AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA" ++ "CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA" ++ "CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoA" ++ "KACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACg" ++ "AoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo" ++ "AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKA" ++ "CgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAK" ++ "ACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoA" ++ "KACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo" ++ "AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAo" ++ "AKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgAoAKACgD/9k=";diff --git a/web/apps/albums/vendor/ente-gallery/services/upload/upload-service.ts b/web/apps/albums/vendor/ente-gallery/services/upload/upload-service.tsnew file mode 100644index 0000000000..bdada5d2ae--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/upload/upload-service.ts@@ -0,0 +1,2119 @@+// TODO: Audit this file+/* eslint-disable @typescript-eslint/ban-ts-comment */++import type { BytesOrB64 } from "ente-base/crypto/types";+import { streamEncryptionChunkSize } from "ente-base/crypto/types";+import { type CryptoWorker } from "ente-base/crypto/worker";+import { ensureElectron } from "ente-base/electron";+import { basename, nameAndExtension } from "ente-base/file-name";+import {+ ensureOk,+ HTTPError,+ retryAsyncOperation,+ type HTTPRequestRetrier,+ type PublicAlbumsCredentials,+} from "ente-base/http";+import log from "ente-base/log";+import { extractExif } from "ente-gallery/services/exif";+import {+ determineVideoDuration,+ extractVideoMetadata,+} from "ente-gallery/services/ffmpeg";+import {+ detectFileTypeInfoFromChunk,+ isFileTypeNotSupportedError,+} from "ente-gallery/utils/detect-type";+import { readStream } from "ente-gallery/utils/native-stream";+import { decryptRemoteFile, type EnteFile } from "ente-media/file";+import {+ fileFileName,+ metadataHash,+ type FileMetadata,+ type FilePublicMagicMetadataData,+ type ParsedMetadata,+} from "ente-media/file-metadata";+import { FileType, type FileTypeInfo } from "ente-media/file-type";+import { encodeLivePhoto } from "ente-media/live-photo";+import {+ createMagicMetadata,+ encryptMagicMetadata,+ type RemoteMagicMetadata,+} from "ente-media/magic-metadata";+import { addToCollection } from "ente-new/photos/services/collection";+import { mergeUint8Arrays } from "ente-utils/array";+import { ensureInteger, ensureNumber } from "ente-utils/ensure";+import {+ areChecksumProtectedUploadsEnabled,+ type LivePhotoAssets,+ type UploadableUploadItem,+ type UploadItem,+ type UploadPathPrefix,+ type UploadResult,+} from ".";+import { tryParseEpochMicrosecondsFromFileName } from "./date";+import { computeMd5Base64 } from "./md5";+import { matchJSONMetadata, type ParsedMetadataJSON } from "./metadata-json";+import {+ completeMultipartUpload,+ completeMultipartUploadViaWorker,+ fetchMultipartUploadURLs,+ fetchMultipartUploadURLsWithMetadata,+ fetchPublicAlbumsMultipartUploadURLsWithMetadata,+ fetchPublicAlbumsUploadURLWithMetadata,+ fetchUploadURLs,+ fetchUploadURLWithMetadata,+ postEnteFile,+ postPublicAlbumsEnteFile,+ putFile,+ putFilePart,+ putFilePartViaWorker,+ putFileViaWorker,+ type MultipartCompletedPart,+ type ObjectUploadURL,+ type PostEnteFileRequest,+} from "./remote";+import {+ fallbackThumbnail,+ generateThumbnailNative,+ generateThumbnailWeb,+} from "./thumbnail";++const bitFlipErrorPrefix = "BitFlipDetected";++/**+ * A readable stream for a file, and its associated size and last modified time.+ *+ * This is the in-memory representation of the {@link UploadItem} type that we+ * usually pass around. See: [Note: Reading a UploadItem]+ */+interface FileStream {+ /**+ * A stream of the file's contents+ *+ * This stream is guaranteed to emit data in+ * {@link streamEncryptionChunkSize} sized chunks (except the last chunk+ * which can be smaller since a file would rarely align exactly to a+ * {@link streamEncryptionChunkSize} multiple).+ *+ * Note: A stream can only be read once!+ */+ stream: ReadableStream<Uint8Array>;+ /**+ * Number of chunks {@link stream} will emit, each+ * {@link streamEncryptionChunkSize} sized (except the last one).+ */+ chunkCount: number;+ /**+ * The size in bytes of the underlying file.+ */+ fileSize: number;+ /**+ * The modification time of the file, in epoch milliseconds.+ */+ lastModifiedMs: number;+ /**+ * Set to the underlying {@link File} when we also have access to it.+ */+ file?: File;+}++/**+ * If the stream we have is more than 5 {@link streamEncryptionChunkSize}+ * chunks, then use multipart uploads for it, with each multipart-part+ * containing 5 chunks.+ *+ * {@link streamEncryptionChunkSize} is 4 MB, and the number of chunks in a+ * single upload part is 5, so each part is (up to) 20 MB.+ */+const multipartChunksPerPart = 5;++/** Upload files to cloud storage */+class UploadService {+ private uploadURLs: ObjectUploadURL[] = [];+ private pendingUploadCount = 0;+ private publicAlbumsCredentials: PublicAlbumsCredentials | undefined;+ private activeUploadURLRefill: Promise<void> | undefined;++ init(publicAlbumsCredentials: PublicAlbumsCredentials | undefined) {+ this.publicAlbumsCredentials = publicAlbumsCredentials;+ }++ logout() {+ this.uploadURLs = [];+ this.pendingUploadCount = 0;+ this.publicAlbumsCredentials = undefined;+ this.activeUploadURLRefill = undefined;+ }++ async setFileCount(fileCount: number) {+ this.pendingUploadCount = fileCount;+ if (+ areChecksumProtectedUploadsEnabled() ||+ this.publicAlbumsCredentials+ ) {+ this.uploadURLs = [];+ return;+ }+ await this.refillUploadURLs(); /* prefetch */+ }++ reducePendingUploadCount() {+ this.pendingUploadCount--;+ }++ async getUploadURL(metadata?: {+ contentLength: number;+ contentMd5: string;+ }) {+ if (this.publicAlbumsCredentials) {+ if (+ metadata &&+ metadata.contentLength >= 0 &&+ metadata.contentMd5+ ) {+ return fetchPublicAlbumsUploadURLWithMetadata(+ metadata,+ this.publicAlbumsCredentials,+ );+ }+ throw new Error("Public uploads require content metadata");+ }+ if (+ areChecksumProtectedUploadsEnabled() &&+ metadata &&+ metadata.contentLength >= 0 &&+ metadata.contentMd5+ ) {+ return fetchUploadURLWithMetadata(metadata);+ }+ if (this.uploadURLs.length == 0 && this.pendingUploadCount) {+ await this.refillUploadURLs();+ }+ const url = this.uploadURLs.pop();+ if (!url) throw new Error("Failed to obtain upload URL");+ return url;+ }++ private async refillUploadURLs() {+ try {+ if (!this.activeUploadURLRefill) {+ this.activeUploadURLRefill = this._refillUploadURLs();+ }+ await this.activeUploadURLRefill;+ } finally {+ this.activeUploadURLRefill = undefined;+ }++ // Ensure that the upload URLs we have are unique.+ //+ // Sanity check added when this was a new implementation. Have kept it+ // around, but it can be removed too.+ if (+ this.uploadURLs.length !=+ new Set(this.uploadURLs.map((u) => u.url)).size+ ) {+ throw new Error("Duplicate upload URLs detected");+ }+ }++ private async _refillUploadURLs() {+ if (this.publicAlbumsCredentials) {+ throw new Error(+ "Public uploads should request metadata upload URLs",+ );+ }+ let urls: ObjectUploadURL[];+ try {+ urls = await fetchUploadURLs(this.pendingUploadCount);+ } catch (e) {+ throw translateURLFetchErrorIfNeeded(e);+ }+ urls.forEach((u) => this.uploadURLs.push(u));+ }++ async fetchMultipartUploadURLs(+ uploadPartCount: number,+ metadata?: {+ contentLength: number;+ partLength: number;+ partMd5s: string[];+ },+ ) {+ if (this.publicAlbumsCredentials) {+ if (+ metadata &&+ metadata.contentLength > 0 &&+ metadata.partLength > 0 &&+ metadata.partMd5s.length > 0+ ) {+ return fetchPublicAlbumsMultipartUploadURLsWithMetadata(+ metadata,+ this.publicAlbumsCredentials,+ );+ }+ throw new Error(+ "Public multipart uploads require content metadata",+ );+ }+ if (+ metadata &&+ areChecksumProtectedUploadsEnabled() &&+ metadata.contentLength > 0 &&+ metadata.partLength > 0 &&+ metadata.partMd5s.length > 0+ ) {+ return fetchMultipartUploadURLsWithMetadata(metadata).catch(+ (e: unknown) => {+ throw translateURLFetchErrorIfNeeded(e);+ },+ );+ }+ return fetchMultipartUploadURLs(uploadPartCount).catch((e: unknown) => {+ throw translateURLFetchErrorIfNeeded(e);+ });+ }+}++/** The singleton instance of {@link UploadService}. */+const uploadService = new UploadService();++export default uploadService;++/**+ * Return the file name for the given {@link uploadItem}.+ */+export const uploadItemFileName = (uploadItem: UploadItem) => {+ if (uploadItem instanceof File) return uploadItem.name;+ if (typeof uploadItem == "string") return basename(uploadItem);+ if (Array.isArray(uploadItem)) return basename(uploadItem[1]);+ return uploadItem.file.name;+};++/* -- Various intermediate types used during upload -- */++export type ExternalParsedMetadata = ParsedMetadata & {+ creationTime?: number | undefined;+};++export interface UploadAsset {+ /**+ * `true` if this is a live photo.+ */+ isLivePhoto?: boolean;+ /**+ * The two parts of the live photo being uploaded.+ *+ * Valid for live photos.+ */+ livePhotoAssets?: LivePhotoAssets;+ /**+ * The item being uploaded.+ *+ * Valid for non-live photos.+ */+ uploadItem?: UploadItem;+ /**+ * The path prefix of the uploadItem (if not a live photo), or of the image+ * component of the live photo (otherwise).+ *+ * The only expected scenario where this will not be present is when we're+ * uploading an edited file (edited in the in-app image editor).+ */+ pathPrefix: UploadPathPrefix | undefined;+ /**+ * Metadata we know about a file externally. Valid for non-live photos.+ *+ * This is metadata that is not present within the file, but we have+ * available from external sources. There is also a parsed metadata we+ * obtain from JSON files. So together with the metadata present within the+ * file itself, there are three places where the file's initial metadata can+ * be filled in from.+ *+ * This will not be present for live photos.+ */+ externalParsedMetadata?: ExternalParsedMetadata;+}++interface ThumbnailedFile {+ fileStreamOrData: FileStream | Uint8Array;+ /** The JPEG data of the generated thumbnail */+ thumbnail: Uint8Array;+ /**+ * `true` if this is a fallback (all black) thumbnail we're returning since+ * thumbnail generation failed for some reason.+ */+ hasStaticThumbnail: boolean;+}++interface FileWithMetadata extends Omit<ThumbnailedFile, "hasStaticThumbnail"> {+ localID: number;+ metadata: FileMetadata;+ publicMagicMetadata: FilePublicMagicMetadataData;+}++interface EncryptedFileStream {+ /**+ * A stream of the file's encrypted contents+ *+ * This stream is guaranteed to emit data in+ * {@link streamEncryptionChunkSize} chunks (except the last chunk which can+ * be smaller since a file would rarely align exactly to a+ * {@link streamEncryptionChunkSize} multiple).+ */+ stream: ReadableStream<Uint8Array>;+ /**+ * Number of chunks {@link stream} will emit, each+ * {@link streamEncryptionChunkSize} sized (except the last one).+ */+ chunkCount: number;+}++interface EncryptedFilePieces {+ /**+ * The encrypted contents of the file (as bytes or a stream of bytes), and+ * the decryption header that was used during encryption (base64 string).+ */+ file: {+ encryptedData: Uint8Array | EncryptedFileStream;+ decryptionHeader: string;+ };+ /**+ * The encrypted contents of the file's thumbnail (as bytes), and the+ * decryption header that was used during encryption (base64 string).+ */+ thumbnail: { encryptedData: Uint8Array; decryptionHeader: string };+ /**+ * The encrypted contents of the file's metadata (as a base64 string), and+ * the decryption header that was used during encryption (base64 string).+ */+ metadata: { encryptedData: string; decryptionHeader: string };+ pubMagicMetadata: RemoteMagicMetadata | undefined;+ localID: number;+}++export interface PotentialLivePhotoAsset {+ fileName: string;+ fileType: number /* FileType | -1 */;+ collectionID: number;+ uploadItem: UploadItem;+ pathPrefix: UploadPathPrefix | undefined;+}++/**+ * Check if the two given assets should be clubbed together as a live photo.+ */+export const areLivePhotoAssets = async (+ f: PotentialLivePhotoAsset,+ g: PotentialLivePhotoAsset,+ parsedMetadataJSONMap: Map<string, ParsedMetadataJSON>,+) => {+ if (f.collectionID != g.collectionID) return false;+ if (f.pathPrefix != g.pathPrefix) return false;++ const [fName, fExt] = nameAndExtension(f.fileName);+ const [gName, gExt] = nameAndExtension(g.fileName);++ let fPrunedName: string;+ let gPrunedName: string;+ if (f.fileType == FileType.image && g.fileType == FileType.video) {+ fPrunedName = removePotentialLivePhotoSuffix(+ fName,+ // A Google Live Photo image file can have video extension appended+ // as suffix, so we pass that to removePotentialLivePhotoSuffix to+ // remove it.+ //+ // Example: IMG_20210630_0001.mp4.jpg (Google Live Photo image file)+ gExt ? `.${gExt}` : undefined,+ );+ gPrunedName = removePotentialLivePhotoSuffix(gName);+ } else if (f.fileType == FileType.video && g.fileType == FileType.image) {+ fPrunedName = removePotentialLivePhotoSuffix(fName);+ gPrunedName = removePotentialLivePhotoSuffix(+ gName,+ fExt ? `.${fExt}` : undefined,+ );+ } else {+ return false;+ }++ if (fPrunedName != gPrunedName) return false;++ // Also check that the size of an individual Live Photo asset is less than+ // an (arbitrary) limit. This should be true in practice as the videos for a+ // live photo are a few seconds long. Further on, the zipping library that+ // we use doesn't support stream as a input.++ const maxAssetSize = 20 * 1024 * 1024; /* 20MB */+ const fSize = await uploadItemSize(f.uploadItem);+ const gSize = await uploadItemSize(g.uploadItem);+ if (fSize > maxAssetSize || gSize > maxAssetSize) {+ log.info(+ `Not classifying files with too large sizes (${fSize} and ${gSize} bytes) as a live photo`,+ );+ return false;+ }++ // Finally, ensure that the creation times of the image and video are within+ // some epsilon of each other. This is to avoid clubbing together unrelated+ // items that coincidentally have the same name (this is not uncommon since,+ // e.g. many cameras use a deterministic numbering scheme).++ const fParsedMetadataJSON = matchJSONMetadata(+ f.pathPrefix,+ f.collectionID,+ f.fileName,+ parsedMetadataJSONMap,+ );+ const gParsedMetadataJSON = matchJSONMetadata(+ g.pathPrefix,+ g.collectionID,+ g.fileName,+ parsedMetadataJSONMap,+ );++ const fDate = await uploadItemCreationDate(+ f.uploadItem,+ f.fileType,+ fParsedMetadataJSON,+ );+ const gDate = await uploadItemCreationDate(+ g.uploadItem,+ g.fileType,+ gParsedMetadataJSON,+ );++ // The exact threshold to use is hard to decide. The times should be usually+ // exact to minute, but it is possible that one of the items is missing the+ // timezone while the other has it. Their dates (as shown by the app) would+ // both be correct, just the UTC epochs will vary.+ //+ // Using a threshold of 1 day makes the app more robust to such timezone+ // discrepancies while only marginally increasing the risk of false+ // positives. But this is a heuristic that might not always be correct.+ const thresholdSeconds = 24 * 60 * 60; /* 1 day */+ const haveSameishDate =+ fDate && gDate && Math.abs(fDate - gDate) / 1e6 < thresholdSeconds;++ if (!haveSameishDate) {+ // Google does not include the metadata JSON for the video part of the+ // live photo in the Takeout, causing this date check to fail.+ //+ // So only incorporate this check if either neither file has a metadata+ // JSON, or both have it.+ if (+ (!fParsedMetadataJSON && !gParsedMetadataJSON) ||+ (fParsedMetadataJSON && gParsedMetadataJSON)+ ) {+ return false;+ }+ }++ // All checks pass. Club these two as a live photo.+ return true;+};++const removePotentialLivePhotoSuffix = (name: string, suffix?: string) => {+ const suffix_3 = "_3";++ // The icloud-photos-downloader library appends _HVEC to the end of the+ // filename in case of live photos.+ //+ // https://github.com/icloud-photos-downloader/icloud_photos_downloader+ const suffix_hvec = "_HVEC";++ let foundSuffix: string | undefined;+ if (name.endsWith(suffix_3)) {+ foundSuffix = suffix_3;+ } else if (+ name.endsWith(suffix_hvec) ||+ name.endsWith(suffix_hvec.toLowerCase())+ ) {+ foundSuffix = suffix_hvec;+ } else if (suffix) {+ if (name.endsWith(suffix) || name.endsWith(suffix.toLowerCase())) {+ foundSuffix = suffix;+ }+ }++ return foundSuffix ? name.slice(0, foundSuffix.length * -1) : name;+};++/**+ * Return the size of the given {@link uploadItem}.+ */+const uploadItemSize = async (uploadItem: UploadItem): Promise<number> => {+ if (uploadItem instanceof File) return uploadItem.size;+ if (typeof uploadItem == "string")+ return ensureElectron().pathOrZipItemSize(uploadItem);+ if (Array.isArray(uploadItem))+ return ensureElectron().pathOrZipItemSize(uploadItem);+ return uploadItem.file.size;+};++/**+ * Return the creation date for the given {@link uploadItem}.+ *+ * [Note: Duplicate retrieval of creation date for live photo clubbing]+ *+ * This function duplicates some logic of {@link extractImageOrVideoMetadata}.+ * This duplication, while not good, is currently unavoidable with the way the+ * code is structured since the live photo clubbing happens at an earlier time+ * in the pipeline when we don't have the Exif data, but the Exif data is needed+ * to determine the file's creation time (to ensure that we only club photos and+ * videos with close by creation times, instead of just relying on file names).+ *+ * Note that unlike {@link extractImageOrVideoMetadata}, we don't try to+ * fallback to the file's modification time. This is because for the purpose of+ * live photo clubbing, we wish to use the creation date only in cases where we+ * have it.+ */+const uploadItemCreationDate = async (+ uploadItem: UploadItem,+ fileType: number /* FileType */,+ parsedMetadataJSON: ParsedMetadataJSON | undefined,+) => {+ if (parsedMetadataJSON?.creationTime)+ return parsedMetadataJSON.creationTime;++ let parsedMetadata: ParsedMetadata | undefined;+ if (fileType == FileType.image) {+ parsedMetadata = await tryExtractImageMetadata(uploadItem, undefined);+ } else if (fileType == FileType.video) {+ parsedMetadata = await tryExtractVideoMetadata(uploadItem);+ } else {+ throw new Error(+ `Unexpected file type ${fileType} for ${uploadItemFileName(uploadItem)}`,+ );+ }++ return parsedMetadata?.creationDate?.timestamp;+};++/**+ * The message of the {@link Error} that is thrown when the user cancels an+ * upload.+ *+ * As a convenience, the {@link isUploadCancelledError} matcher can be used to+ * match such errors.+ *+ * [Note: Upload cancellation]+ *+ * 1. User cancels the upload by pressing the cancel button on the upload+ * progress indicator in the UI.+ *+ * 2. This sets the {@link shouldUploadBeCancelled} flag on+ * {@link UploadManager}.+ *+ * 3. Periodically the code that is performing the upload calls the+ * {@link abortIfCancelled} flag. This function is a no-op normally, but if+ * the {@link shouldUploadBeCancelled} is set then it throws an {@link Error}+ * with the message set to {@link uploadCancelledErrorMessage}.+ *+ * 4. The intermediate per-file try catch handlers do not intercept this error,+ * and it bubbles all the way to the top of the call stack, ending the upload.+ */+export const uploadCancelledErrorMessage = "Upload cancelled";++/**+ * A convenience function to check if the provided value is an {@link Error}+ * with message {@link uploadCancelledErrorMessage}.+ */+export const isUploadCancelledError = (e: unknown) =>+ e instanceof Error && e.message == uploadCancelledErrorMessage;++/**+ * The message of the {@link Error} that is thrown when the upload fails because+ * the user's current session has expired (e.g. maybe they logged this client+ * out from another session), and that they need to login again.+ */+export const sessionExpiredErrorMessage = "Session expired";++/**+ * The message of the {@link Error} that is thrown when the upload fails because+ * the user's subscription has expired.+ */+export const subscriptionExpiredErrorMessage = "Subscription expired";++/**+ * The message of the {@link Error} that is thrown when the upload fails because+ * the user's storage space has been exhausted.+ */+export const storageLimitExceededErrorMessage = "Storage limit exceeded";++/**+ * The message of the {@link Error} that is thrown when the PUT request for the+ * upload of a part of file (as part of an overall multipart upload) fails+ * because the response did not have the etag error.+ *+ * This usually happens because some browser extension is blocking access to the+ * ETag header (even when it is present in the remote S3 response). In self+ * hosted scenarios, this can also happen if the remote S3 bucket does not have+ * the appropriate CORS rules to allow access to the etag header.+ */+const eTagMissingErrorMessage = "ETag header not present in response";++/**+ * The message of the {@link Error} that is thrown when the size of the file+ * being uploaded exceeds the maximum allowed file size.+ *+ * The client already checks for the size of the file being uploaded, and aborts+ * the request if the client side limit is exceeded. An error with this message+ * is thrown if we remote side validation fails.+ *+ * The UI outcome is the same in both cases.+ */+const fileTooLargeErrorMessage = "File too large";++/**+ * Some state and callbacks used during upload that are not tied to a specific+ * file being uploaded.+ */+interface UploadContext {+ /**+ * If `true`, then the upload does not go via the worker.+ *+ * See {@link shouldDisableCFUploadProxy} for more details.+ */+ isCFUploadProxyDisabled: boolean;+ /**+ * If present, then the upload is happening in the context of the public+ * albums app and these are the credentials that should be used for+ * performing API requests (instead of trying to obtain and use the+ * credentials for the logged in user, as happens when we're running in the+ * context of the photos app).+ */+ publicAlbumsCredentials: PublicAlbumsCredentials | undefined;+ /**+ * A function that the upload sequence should use to periodically check in+ * and see if the upload has been cancelled by the user.+ *+ * If the upload has been cancelled, it will throw an exception with the+ * message set to {@link uploadCancelledErrorMessage}.+ *+ * See: [Note: Upload cancellation]+ */+ abortIfCancelled: () => void;+ /**+ * A function that gets called update the progress shown in the UI for a+ * particular file as the parts of that file get uploaded.+ *+ * @param {fileLocalID} The local ID of the file whose progress we want to+ * update.+ *+ * @param {percentage} The upload completion percentage, as a value between+ * 0 and 100 (inclusive).+ */+ updateUploadProgress: (fileLocalID: number, percentage: number) => void;+}++/**+ * Upload the given {@link UploadableUploadItem}+ *+ * This is lower layer implementation of the upload. It is invoked by+ * {@link UploadManager} after it has assembled all the relevant bits we need to+ * go forth and upload.+ *+ * @param uploadContext Some general state and callbacks for the entire set of+ * files being uploaded.+ */+export const upload = async (+ { collection, localID, fileName, ...uploadAsset }: UploadableUploadItem,+ uploaderName: string | undefined,+ existingFiles: EnteFile[],+ parsedMetadataJSONMap: Map<string, ParsedMetadataJSON>,+ worker: CryptoWorker,+ uploadContext: UploadContext,+): Promise<UploadResult> => {+ const { abortIfCancelled } = uploadContext;++ log.info(`Upload ${fileName} | start`);+ try {+ /*+ * We read the file four times:+ * 1. To determine its MIME type (only needs first few KBs).+ * 2. To extract its metadata.+ * 3. To calculate its hash.+ * 4. To encrypt it.+ *+ * When we already have a File object the multiple reads are fine.+ *+ * When we're in the context of our desktop app and have a path, it+ * might be possible to optimize further by using `ReadableStream.tee`+ * to perform these steps simultaneously. However, that'll require+ * restructuring the code so that these steps run in a parallel manner+ * (tee will not work for strictly sequential reads of large streams).+ */++ let assetDetails: ReadAssetDetailsResult;++ try {+ assetDetails = await readAssetDetails(uploadAsset);+ } catch (e) {+ if (isFileTypeNotSupportedError(e)) {+ log.error(`Not uploading ${fileName}`, e);+ return { type: "unsupported" };+ }+ throw e;+ }++ const { fileTypeInfo, fileSize, lastModifiedMs } = assetDetails;++ if (fileSize === 0) return { type: "zeroSize" };++ const maxFileSize = 10 * 1024 * 1024 * 1024; /* 10 GB */+ if (fileSize >= maxFileSize) return { type: "tooLarge" };++ abortIfCancelled();++ const { metadata, publicMagicMetadata } = await extractAssetMetadata(+ uploadAsset,+ fileTypeInfo.fileType,+ lastModifiedMs,+ collection.id,+ parsedMetadataJSONMap,+ worker,+ );++ const matches = existingFiles.filter((file) =>+ areFilesSame(file, metadata),+ );++ const anyMatch = matches.length > 0 ? matches[0] : undefined;++ if (anyMatch) {+ const matchInSameCollection = matches.find(+ (f) => f.collectionID == collection.id,+ );+ if (matchInSameCollection) {+ return { type: "alreadyUploaded", file: matchInSameCollection };+ } else {+ // Any of the matching files can be used to add a symlink.+ const symlink = Object.assign({}, anyMatch);+ symlink.collectionID = collection.id;+ await addToCollection(collection, [symlink]);+ return { type: "addedSymlink", file: symlink };+ }+ }++ abortIfCancelled();++ const { fileStreamOrData, thumbnail, hasStaticThumbnail } =+ await readAsset(fileTypeInfo, uploadAsset);++ if (hasStaticThumbnail) metadata.hasStaticThumbnail = true;++ abortIfCancelled();++ const fileWithMetadata: FileWithMetadata = {+ localID,+ fileStreamOrData,+ thumbnail,+ metadata,+ publicMagicMetadata: {+ ...publicMagicMetadata,+ ...(uploaderName && { uploaderName }),+ },+ };++ const { encryptedFilePieces, encryptedFileKey } = await encryptFile(+ fileWithMetadata,+ collection.key,+ worker,+ );++ abortIfCancelled();++ const backupedFile = await uploadToBucket(+ encryptedFilePieces,+ uploadContext,+ );++ abortIfCancelled();++ const newFileRequest = {+ collectionID: collection.id,+ encryptedKey: encryptedFileKey.encryptedData,+ keyDecryptionNonce: encryptedFileKey.nonce,+ ...backupedFile,+ };++ const uploadedFile = await createRemoteFile(+ newFileRequest,+ uploadContext,+ );++ return {+ type: metadata.hasStaticThumbnail+ ? "uploadedWithStaticThumbnail"+ : "uploaded",+ file: await decryptRemoteFile(uploadedFile, collection.key),+ };+ } catch (e) {+ if (isUploadCancelledError(e)) {+ /* stop the upload */+ throw e;+ }++ log.error(`Upload failed for ${fileName}`, e);+ switch (e instanceof Error && e.message) {+ /* stop the upload */+ case sessionExpiredErrorMessage:+ case subscriptionExpiredErrorMessage:+ case storageLimitExceededErrorMessage:+ throw e;++ /* file specific */+ case eTagMissingErrorMessage:+ return { type: "blocked" };+ case fileTooLargeErrorMessage:+ return { type: "largerThanAvailableStorage" };+ default:+ return { type: "failed" };+ }+ }+};++/**+ * Convert specific HTTP errors during an API call to remote endpoints for+ * fetching new upload URLs into error with known messages (if applicable).+ *+ * Can be used with the following functions:+ *+ * - {@link fetchUploadURLs}+ * - {@link fetchMultipartUploadURLs}+ *+ */+const translateURLFetchErrorIfNeeded = (e: unknown) => {+ if (e instanceof HTTPError) {+ switch (e.res.status) {+ case 401:+ return new Error(sessionExpiredErrorMessage);+ case 402:+ return new Error(subscriptionExpiredErrorMessage);+ case 426:+ return new Error(storageLimitExceededErrorMessage);+ }+ }+ return e;+};++/**+ * Read the given file or path or zip item into an in-memory representation.+ *+ * [Note: Reading a UploadItem]+ *+ * The file can be either a web+ * [File](https://developer.mozilla.org/en-US/docs/Web/API/File), the absolute+ * path to a file on desk, a combination of these two, or a entry in a zip file+ * on the user's local file system.+ *+ * tl;dr; There are four cases:+ *+ * 1. web / File+ * 2. desktop / File (+ path)+ * 3. desktop / path+ * 4. desktop / ZipItem+ *+ * For the when and why, read on.+ *+ * The code that accesses files (e.g. uplaads) gets invoked in two contexts:+ *+ * 1. web: the normal mode, when we're running in as a web app in the browser.+ *+ * 2. desktop: when we're running inside our desktop app.+ *+ * In the web context, we'll always get a File, since within the browser we+ * cannot programmatically construct paths to or arbitrarily access files on the+ * user's file system.+ *+ * > Note that even if we were to somehow have an absolute path at hand, we+ * cannot programmatically create such File objects to arbitrary absolute+ * paths on user's local file system for security reasons.+ *+ * So in the web context, this will always be a File we get as a result of an+ * explicit user interaction (e.g. drag and drop or using a file selector).+ *+ * In the desktop context, this can be either a File (+ path), or a path, or an+ * entry within a zip file.+ *+ * 2. If the user provided us this file via some user interaction (say a drag+ * and a drop), this'll still be a File. But unlike in the web context, we+ * also have access to the full path of this file.+ *+ * 3. In addition, when running in the desktop app we have the ability to+ * initiate programmatic access absolute paths on the user's file system. For+ * example, if the user asks us to watch certain folders on their disk for+ * changes, we'll be able to pick up new images being added, and in such+ * cases, the parameter here will be a path. Another example is when resuming+ * an previously interrupted upload - we'll only have the path at hand in+ * such cases, not the original File object since the app subsequently+ * restarted.+ *+ * 4. The user might've also initiated an upload of a zip file (or we might be+ * resuming one). In such cases we will get a tuple (path to the zip file on+ * the local file system, and the name of the entry within that zip file).+ *+ * Case 3 and 4, when we're provided a path, are simple. We don't have a choice,+ * since we cannot still programmatically construct a File object (we can+ * construct it on the Node.js layer, but it can't then be transferred over the+ * IPC boundary). So all our operations use the path itself.+ *+ * Case 2 involves a choice on a use-case basis. Neither File nor the path is a+ * better choice for all use cases.+ *+ * > The advantage of the File object is that the browser has already read it+ * into memory for us. The disadvantage comes in the case where we need to+ * communicate with the native Node.js layer of our desktop app. Since this+ * communication happens over IPC, the File's contents need to be serialized+ * and copied, which is a bummer for large videos etc.+ */+const readUploadItem = async (uploadItem: UploadItem): Promise<FileStream> => {+ let underlyingStream: ReadableStream;+ let file: File | undefined;+ let fileSize: number;+ let lastModifiedMs: number;++ if (typeof uploadItem == "string" || Array.isArray(uploadItem)) {+ const {+ response,+ size,+ lastModifiedMs: lm,+ } = await readStream(ensureElectron(), uploadItem);+ underlyingStream = response.body!;+ fileSize = size;+ lastModifiedMs = lm;+ } else {+ if (uploadItem instanceof File) {+ file = uploadItem;+ } else {+ file = uploadItem.file;+ }+ underlyingStream = file.stream();+ fileSize = file.size;+ lastModifiedMs = file.lastModified;+ }++ const N = streamEncryptionChunkSize;+ const chunkCount = Math.ceil(fileSize / streamEncryptionChunkSize);++ // Pipe the underlying stream through a transformer that emits+ // streamEncryptionChunkSize-ed chunks (except the last one, which can be+ // smaller).+ let pending: Uint8Array | undefined;+ const transformer = new TransformStream<Uint8Array, Uint8Array>({+ transform(+ chunk: Uint8Array,+ controller: TransformStreamDefaultController,+ ) {+ let next: Uint8Array;+ if (pending) {+ next = new Uint8Array(pending.length + chunk.length);+ next.set(pending);+ next.set(chunk, pending.length);+ pending = undefined;+ } else {+ next = chunk;+ }+ while (next.length >= N) {+ controller.enqueue(next.slice(0, N));+ next = next.slice(N);+ }+ if (next.length) pending = next;+ },+ flush(controller: TransformStreamDefaultController) {+ if (pending) controller.enqueue(pending);+ },+ });++ const stream = underlyingStream.pipeThrough(transformer);++ return { stream, chunkCount, fileSize, lastModifiedMs, file };+};++interface ReadAssetDetailsResult {+ fileTypeInfo: FileTypeInfo;+ fileSize: number;+ lastModifiedMs: number;+}++/**+ * Read the associated file(s) to determine the type, size and last modified+ * time of the given {@link asset}.+ */+const readAssetDetails = async ({+ isLivePhoto,+ livePhotoAssets,+ uploadItem,+}: UploadAsset): Promise<ReadAssetDetailsResult> =>+ isLivePhoto+ ? // @ts-ignore+ readLivePhotoDetails(livePhotoAssets)+ : // @ts-ignore+ readImageOrVideoDetails(uploadItem);++const readLivePhotoDetails = async ({ image, video }: LivePhotoAssets) => {+ const img = await readImageOrVideoDetails(image);+ const vid = await readImageOrVideoDetails(video);++ return {+ fileTypeInfo: {+ fileType: FileType.livePhoto,+ // Use the extension of the image component as the extension of the+ // live photo.+ extension: img.fileTypeInfo.extension,+ },+ fileSize: img.fileSize + vid.fileSize,+ lastModifiedMs: img.lastModifiedMs,+ };+};++/**+ * Read the beginning of the given file (or its path), or use its filename as a+ * fallback, to determine its MIME type. From that, construct and return a+ * {@link FileTypeInfo}.+ *+ * While we're at it, also return the size of the file, and its last modified+ * time (expressed as epoch milliseconds).+ *+ * @param uploadItem See: [Note: Reading a UploadItem]+ */+const readImageOrVideoDetails = async (uploadItem: UploadItem) => {+ const { stream, fileSize, lastModifiedMs } =+ await readUploadItem(uploadItem);++ // @ts-ignore+ const fileTypeInfo = await detectFileTypeInfoFromChunk(async () => {+ const reader = stream.getReader();+ const chunk = (await reader.read()).value;+ await reader.cancel();+ return chunk;+ }, uploadItemFileName(uploadItem));++ return { fileTypeInfo, fileSize, lastModifiedMs };+};++/**+ * Read the entirety of a readable stream.+ *+ * It is not recommended to use this for large (say, multi-hundred MB) files. It+ * is provided as a syntactic shortcut for cases where we already know that the+ * size of the stream will be reasonable enough to be read in its entirety+ * without us running out of memory.+ */+const readEntireStream = async (stream: ReadableStream) =>+ new Uint8Array(await new Response(stream).arrayBuffer());++interface ExtractAssetMetadataResult {+ metadata: FileMetadata;+ publicMagicMetadata: FilePublicMagicMetadataData;+}++/**+ * Compute the hash, extract Exif or other metadata, and merge in data from the+ * {@link parsedMetadataJSONMap} for the assets. Return the resultant metadatum.+ */+const extractAssetMetadata = async (+ {+ isLivePhoto,+ uploadItem,+ livePhotoAssets,+ pathPrefix,+ externalParsedMetadata,+ }: UploadAsset,+ fileType: FileType,+ lastModifiedMs: number,+ collectionID: number,+ parsedMetadataJSONMap: Map<string, ParsedMetadataJSON>,+ worker: CryptoWorker,+): Promise<ExtractAssetMetadataResult> =>+ isLivePhoto+ ? await extractLivePhotoMetadata(+ // @ts-ignore+ livePhotoAssets,+ pathPrefix,+ lastModifiedMs,+ collectionID,+ parsedMetadataJSONMap,+ worker,+ )+ : await extractImageOrVideoMetadata(+ // @ts-ignore+ uploadItem,+ pathPrefix,+ externalParsedMetadata,+ fileType,+ lastModifiedMs,+ collectionID,+ parsedMetadataJSONMap,+ worker,+ );++const extractLivePhotoMetadata = async (+ livePhotoAssets: LivePhotoAssets,+ pathPrefix: UploadPathPrefix | undefined,+ lastModifiedMs: number,+ collectionID: number,+ parsedMetadataJSONMap: Map<string, ParsedMetadataJSON>,+ worker: CryptoWorker,+) => {+ const { metadata: imageMetadata, publicMagicMetadata } =+ await extractImageOrVideoMetadata(+ livePhotoAssets.image,+ pathPrefix,+ undefined,+ FileType.image,+ lastModifiedMs,+ collectionID,+ parsedMetadataJSONMap,+ worker,+ );++ const imageHash = imageMetadata.hash;+ const videoHash = await computeHash(livePhotoAssets.video, worker);++ const hash = `${imageHash}:${videoHash}`;++ return {+ metadata: {+ ...imageMetadata,+ title: uploadItemFileName(livePhotoAssets.image),+ fileType: FileType.livePhoto,+ hash,+ },+ publicMagicMetadata,+ };+};++const extractImageOrVideoMetadata = async (+ uploadItem: UploadItem,+ pathPrefix: UploadPathPrefix | undefined,+ externalParsedMetadata: ExternalParsedMetadata | undefined,+ fileType: FileType,+ lastModifiedMs: number,+ collectionID: number,+ parsedMetadataJSONMap: Map<string, ParsedMetadataJSON>,+ worker: CryptoWorker,+) => {+ const fileName = uploadItemFileName(uploadItem);++ let parsedMetadata: (ParsedMetadata & ExternalParsedMetadata) | undefined;+ if (fileType == FileType.image) {+ parsedMetadata = await tryExtractImageMetadata(+ uploadItem,+ lastModifiedMs,+ );+ } else if (fileType == FileType.video) {+ parsedMetadata = await tryExtractVideoMetadata(uploadItem);+ } else {+ throw new Error(+ `Unexpected file type ${fileType} for ${uploadItemFileName(uploadItem)}`,+ );+ }++ // The `UploadAsset` itself might have metadata associated with a-priori, if+ // so, merge the data we read from the file's contents into it.+ if (externalParsedMetadata) {+ parsedMetadata = { ...externalParsedMetadata, ...parsedMetadata };+ }++ const hash = await computeHash(uploadItem, worker);++ // Some of this logic is duplicated in `uploadItemCreationDate`.+ //+ // See: [Note: Duplicate retrieval of creation date for live photo clubbing]++ const parsedMetadataJSON = matchJSONMetadata(+ pathPrefix,+ collectionID,+ fileName,+ parsedMetadataJSONMap,+ );++ const publicMagicMetadata: FilePublicMagicMetadataData = {};++ const modificationTime =+ parsedMetadataJSON?.modificationTime ?? lastModifiedMs * 1000;++ let creationTime: number;+ if (parsedMetadataJSON?.creationTime) {+ creationTime = parsedMetadataJSON.creationTime;+ } else if (parsedMetadata?.creationDate) {+ const { dateTime, offset, timestamp } = parsedMetadata.creationDate;+ creationTime = timestamp;+ publicMagicMetadata.dateTime = dateTime;+ if (offset) publicMagicMetadata.offsetTime = offset;+ } else if (parsedMetadata?.creationTime) {+ creationTime = parsedMetadata.creationTime;+ } else {+ creationTime =+ tryParseEpochMicrosecondsFromFileName(fileName) ?? modificationTime;+ }++ // Video duration+ let duration: number | undefined;+ if (fileType == FileType.video) {+ duration = await tryDetermineVideoDuration(uploadItem);+ }++ // To avoid introducing malformed data into the metadata fields (which the+ // other clients might not expect and handle), we have extra "ensure" checks+ // here that act as a safety valve if somehow the TypeScript type is lying.+ //+ // There is no deterministic sample we found that necessitated adding these+ // extra checks, but we did get one user with a list in the width field of+ // the metadata (it should've been an integer). The most probable theory is+ // that somehow it made its way in through malformed Exif.++ const metadata: FileMetadata = {+ fileType,+ title: fileName,+ creationTime: ensureInteger(creationTime),+ modificationTime: ensureInteger(modificationTime),+ hash,+ };++ if (duration) {+ metadata.duration = ensureInteger(Math.ceil(duration));+ }++ const location = parsedMetadataJSON?.location ?? parsedMetadata?.location;+ if (location) {+ metadata.latitude = ensureNumber(location.latitude);+ metadata.longitude = ensureNumber(location.longitude);+ }++ if (parsedMetadata) {+ const { width: w, height: h } = parsedMetadata;+ if (w) publicMagicMetadata.w = ensureInteger(w);+ if (h) publicMagicMetadata.h = ensureInteger(h);+ }++ const caption =+ parsedMetadataJSON?.description ?? parsedMetadata?.description;+ if (+ caption != null &&+ (typeof caption == "string" || typeof caption == "number")+ ) {+ publicMagicMetadata.caption = String(caption);+ }++ if (parsedMetadata?.cameraMake) {+ publicMagicMetadata.cameraMake = parsedMetadata.cameraMake;+ }+ if (parsedMetadata?.cameraModel) {+ publicMagicMetadata.cameraModel = parsedMetadata.cameraModel;+ }++ return { metadata, publicMagicMetadata };+};++const tryExtractImageMetadata = async (+ uploadItem: UploadItem,+ lastModifiedMs: number | undefined,+): Promise<ParsedMetadata | undefined> => {+ let file: File;+ if (typeof uploadItem == "string" || Array.isArray(uploadItem)) {+ // The library we use for extracting Exif from images, ExifReader,+ // doesn't support streams. But unlike videos, for images it is+ // reasonable to read the entire stream into memory here.+ const { response } = await readStream(ensureElectron(), uploadItem);+ const path = typeof uploadItem == "string" ? uploadItem : uploadItem[1];+ const opts = lastModifiedMs ? { lastModified: lastModifiedMs } : {};+ file = new File([await response.arrayBuffer()], basename(path), opts);+ } else if (uploadItem instanceof File) {+ file = uploadItem;+ } else {+ file = uploadItem.file;+ }++ try {+ return await extractExif(file);+ } catch (e) {+ const fileName = uploadItemFileName(uploadItem);+ log.error(`Failed to extract image metadata for ${fileName}`, e);+ return undefined;+ }+};++const tryExtractVideoMetadata = async (uploadItem: UploadItem) => {+ try {+ return await extractVideoMetadata(uploadItem);+ } catch (e) {+ const fileName = uploadItemFileName(uploadItem);+ log.error(`Failed to extract video metadata for ${fileName}`, e);+ return undefined;+ }+};++const tryDetermineVideoDuration = async (uploadItem: UploadItem) => {+ try {+ return await determineVideoDuration(uploadItem);+ } catch (e) {+ const fileName = uploadItemFileName(uploadItem);+ log.error(`Failed to extract video duration for ${fileName}`, e);+ return undefined;+ }+};++/**+ * Compute the hash of an item we're attempting to upload.+ *+ * The hash is retained in the file metadata, and is also used to detect+ * duplicates during upload.+ *+ * This process can take a noticable amount of time. As an extreme case, for a+ * 10 GB upload item, this can take a 2-3 minutes.+ *+ * @param uploadItem The {@link UploadItem} we're attempting to upload.+ *+ * @param worker A {@link CryptoWorker} to use for computing the hash.+ */+const computeHash = async (uploadItem: UploadItem, worker: CryptoWorker) => {+ const { stream, chunkCount } = await readUploadItem(uploadItem);+ const hashState = await worker.chunkHashInit();++ const streamReader = stream.getReader();+ for (let i = 0; i < chunkCount; i++) {+ const { done, value: chunk } = await streamReader.read();+ if (done) throw new Error("Less chunks than expected");+ await worker.chunkHashUpdate(hashState, Uint8Array.from(chunk));+ }++ const { done } = await streamReader.read();+ if (!done) throw new Error("More chunks than expected");+ return await worker.chunkHashFinal(hashState);+};++/**+ * Return true if the given file is the same as provided metadata.+ *+ * Note that the metadata includes the hash of the file's contents (when+ * available), so this also in effect compares the contents of the files, not+ * just the "meta" information about them.+ */+const areFilesSame = (fFile: EnteFile, gm: FileMetadata) => {+ const fm = fFile.metadata;++ // File name is different.+ if (fileFileName(fFile) != gm.title) return false;++ // File type is different.+ if (fm.fileType != gm.fileType) return false;++ // Name and type is same, compare hash.+ const fh = metadataHash(fm);+ const gh = metadataHash(gm);+ return fh && gh && fh == gh;+};++const readAsset = async (+ fileTypeInfo: FileTypeInfo,+ { isLivePhoto, uploadItem, livePhotoAssets }: UploadAsset,+): Promise<ThumbnailedFile> =>+ isLivePhoto+ ? // @ts-ignore+ await readLivePhoto(livePhotoAssets, fileTypeInfo)+ : // @ts-ignore+ await readImageOrVideo(uploadItem, fileTypeInfo);++const readLivePhoto = async (+ livePhotoAssets: LivePhotoAssets,+ fileTypeInfo: FileTypeInfo,+) => {+ const {+ fileStreamOrData: imageFileStreamOrData,+ thumbnail,+ hasStaticThumbnail,+ } = await augmentWithThumbnail(+ livePhotoAssets.image,+ // For live photos, the extension field in the file type info is the+ // extension of the image component of the live photo.+ { fileType: FileType.image, extension: fileTypeInfo.extension },+ await readUploadItem(livePhotoAssets.image),+ );+ const videoFileStreamOrData = await readUploadItem(livePhotoAssets.video);++ // The JS zip library that encodeLivePhoto uses does not support+ // ReadableStreams, so pass the file (blob) if we have one, otherwise read+ // the entire stream into memory and pass the resultant data.+ //+ // This is a reasonable behaviour since the videos corresponding to live+ // photos are only a couple of seconds long (we've already done a pre-flight+ // check during areLivePhotoAssets to ensure their size is small).+ const fileOrData = async (sd: FileStream | Uint8Array) => {+ const fos = async ({ file, stream }: FileStream) =>+ file ? file : await readEntireStream(stream);+ return sd instanceof Uint8Array ? sd : fos(sd);+ };++ return {+ fileStreamOrData: await encodeLivePhoto({+ imageFileName: uploadItemFileName(livePhotoAssets.image),+ imageFileOrData: await fileOrData(imageFileStreamOrData),+ videoFileName: uploadItemFileName(livePhotoAssets.video),+ videoFileOrData: await fileOrData(videoFileStreamOrData),+ }),+ thumbnail,+ hasStaticThumbnail,+ };+};++const readImageOrVideo = async (+ uploadItem: UploadItem,+ fileTypeInfo: FileTypeInfo,+) => {+ const fileStream = await readUploadItem(uploadItem);+ return augmentWithThumbnail(uploadItem, fileTypeInfo, fileStream);+};++/**+ * Augment the given {@link dataOrStream} with thumbnail information.+ *+ * This is a companion method for {@link readUploadItem}, and can be used to+ * convert the result of {@link readUploadItem} into an {@link ThumbnailedFile}.+ *+ * @param uploadItem The {@link UploadItem} where the given {@link fileStream}+ * came from.+ *+ * Note: The `fileStream` in the returned {@link ThumbnailedFile} may be+ * different from the one passed to the function.+ */+const augmentWithThumbnail = async (+ uploadItem: UploadItem,+ fileTypeInfo: FileTypeInfo,+ fileStream: FileStream,+): Promise<ThumbnailedFile> => {+ let fileData: Uint8Array | undefined;+ let thumbnail: Uint8Array | undefined;+ let hasStaticThumbnail = false;++ const electron = globalThis.electron;++ // 1. Native thumbnail generation using items's (effective) path.+ if (electron && !(uploadItem instanceof File)) {+ try {+ thumbnail = await generateThumbnailNative(+ electron,+ uploadItem,+ fileTypeInfo,+ );+ } catch (e) {+ log.error("Native thumbnail generation failed", e);+ }+ }++ if (!thumbnail) {+ let blob: Blob | undefined;+ if (uploadItem instanceof File) {+ // 2. Browser based thumbnail generation for File (blobs).+ blob = uploadItem;+ } else {+ // 3. Browser based thumbnail generation for paths.+ //+ // We can only get here when we're running in our desktop app (since+ // only that works with non-File uploadItems), and the thumbnail+ // generation failed.+ //+ // There are no expected scenarios when this should happen.+ //+ // The fallback in this case involves reading the entire stream into+ // memory, and passing that data across the IPC boundary in a single+ // go (i.e. not in a streaming manner). This is risky for videos of+ // unbounded sizes, and since anyways we are not expected to come+ // here for videos, so we only apply this fallback for images.++ if (fileTypeInfo.fileType == FileType.image) {+ const data = await readEntireStream(fileStream.stream);+ blob = new Blob([data]);++ // The Readable stream cannot be read twice, so use the data+ // directly for subsequent steps.+ fileData = data;+ } else {+ const fileName = uploadItemFileName(uploadItem);+ log.warn(+ `Not using browser based thumbnail generation fallback for video at path ${fileName}`,+ );+ }+ }++ try {+ if (blob)+ thumbnail = await generateThumbnailWeb(blob, fileTypeInfo);+ } catch (e) {+ log.error("Web thumbnail creation failed", e);+ }+ }++ if (!thumbnail) {+ thumbnail = fallbackThumbnail();+ hasStaticThumbnail = true;+ }++ return {+ fileStreamOrData: fileData ?? fileStream,+ thumbnail,+ hasStaticThumbnail,+ };+};++const encryptFile = async (+ file: FileWithMetadata,+ collectionKey: string,+ worker: CryptoWorker,+) => {+ const fileKey = await worker.generateBlobOrStreamKey();++ const {+ fileStreamOrData,+ thumbnail,+ metadata,+ publicMagicMetadata,+ localID,+ } = file;++ const shouldVerify = areChecksumProtectedUploadsEnabled();+ const encryptedFiledata =+ fileStreamOrData instanceof Uint8Array+ ? await encryptBytesWithOptionalVerification(+ fileStreamOrData,+ fileKey,+ worker,+ shouldVerify,+ )+ : await encryptFileStream(+ fileStreamOrData,+ fileKey,+ worker,+ shouldVerify,+ );++ const {+ encryptedData: encryptedThumbnailData,+ decryptionHeader: thumbnailDecryptionHeaderBytes,+ } = await worker.encryptBlobBytes(thumbnail, fileKey);++ const encryptedThumbnail = {+ encryptedData: encryptedThumbnailData,+ decryptionHeader: await worker.toB64(thumbnailDecryptionHeaderBytes),+ };++ const encryptedMetadata = await worker.encryptMetadataJSON(+ metadata,+ fileKey,+ );++ let encryptedPubMagicMetadata: RemoteMagicMetadata | undefined;+ const pubMagicMetadata = createMagicMetadata(publicMagicMetadata);+ if (pubMagicMetadata.count) {+ encryptedPubMagicMetadata = await encryptMagicMetadata(+ pubMagicMetadata,+ fileKey,+ );+ }++ const encryptedFileKey = await worker.encryptBox(fileKey, collectionKey);++ return {+ encryptedFilePieces: {+ file: encryptedFiledata,+ thumbnail: encryptedThumbnail,+ metadata: encryptedMetadata,+ pubMagicMetadata: encryptedPubMagicMetadata,+ localID: localID,+ },+ encryptedFileKey,+ };+};++const encryptBytesWithOptionalVerification = async (+ data: Uint8Array,+ fileKey: BytesOrB64,+ worker: CryptoWorker,+ shouldVerify: boolean,+) => {+ const encrypted = await worker.encryptStreamBytes(data, fileKey);+ if (!shouldVerify) return encrypted;+ try {+ const decrypted = await worker.decryptStreamBytes(encrypted, fileKey);+ if (!areUint8ArraysEqual(decrypted, data)) {+ throw new Error(+ `${bitFlipErrorPrefix}: mismatch while verifying encrypted bytes`,+ );+ }+ } catch (error) {+ log.error("Encrypted bytes verification failed", error);+ throw error instanceof Error+ ? error+ : new Error(+ `${bitFlipErrorPrefix}: verification failed while encrypting bytes`,+ );+ }+ return encrypted;+};++const encryptFileStream = async (+ { stream, chunkCount }: FileStream,+ fileKey: BytesOrB64,+ worker: CryptoWorker,+ shouldVerify: boolean,+) => {+ const fileStreamReader = stream.getReader();+ const { decryptionHeader, pushState } =+ await worker.initChunkEncryption(fileKey);+ const verificationPullState = shouldVerify+ ? (await worker.initChunkDecryption(decryptionHeader, fileKey))+ .pullState+ : undefined;+ const ref = { pullCount: 1 };+ const encryptedFileStream = new ReadableStream({+ async pull(controller) {+ const { value, done } = await fileStreamReader.read();+ if (done) {+ // TransformStream in readUploadItem guarantees that we'll get+ // encryption sized `chunkCount` chunks. Below we close the+ // controller on the last chunk. So we shouldn't be getting a+ // `done` here.+ controller.close();+ throw new Error("Unexpected stream state");+ }+ const isFinalChunk = ref.pullCount === chunkCount;+ const encryptedFileChunk = await worker.encryptStreamChunk(+ value,+ pushState,+ isFinalChunk,+ );+ if (verificationPullState) {+ try {+ const decryptedChunk = await worker.decryptStreamChunk(+ encryptedFileChunk,+ verificationPullState,+ );+ if (!areUint8ArraysEqual(decryptedChunk, value)) {+ throw new Error(+ `${bitFlipErrorPrefix}: mismatch while verifying chunk ${ref.pullCount}`,+ );+ }+ } catch (error) {+ log.error(+ `Encrypted chunk verification failed (chunk ${ref.pullCount})`,+ error,+ );+ throw error instanceof Error+ ? error+ : new Error(+ `${bitFlipErrorPrefix}: verification failed for chunk ${ref.pullCount}`,+ );+ }+ }+ controller.enqueue(encryptedFileChunk);+ if (isFinalChunk) {+ controller.close();+ }+ ref.pullCount++;+ },+ });+ return {+ decryptionHeader,+ encryptedData: { stream: encryptedFileStream, chunkCount },+ };+};++const areUint8ArraysEqual = (a: Uint8Array, b: Uint8Array) => {+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) {+ if (a[i] !== b[i]) return false;+ }+ return true;+};++const uploadToBucket = async (+ encryptedFilePieces: EncryptedFilePieces,+ uploadContext: UploadContext,+): Promise<+ Pick<+ PostEnteFileRequest,+ "file" | "thumbnail" | "metadata" | "pubMagicMetadata"+ >+> => {+ const { isCFUploadProxyDisabled, abortIfCancelled, updateUploadProgress } =+ uploadContext;+ const checksumEnabled = areChecksumProtectedUploadsEnabled();+ const shouldSendContentChecksum =+ checksumEnabled || !!uploadContext.publicAlbumsCredentials;++ const { localID, file, thumbnail, metadata, pubMagicMetadata } =+ encryptedFilePieces;++ const requestRetrier = createAbortableRetryEnsuringHTTPOk(abortIfCancelled);++ // The bulk of the network time during upload is taken in uploading the+ // actual encrypted objects to remote S3, but after that there is another+ // API request we need to make to "finalize" the file (on museum). This+ // should be quick usually, but it's a different network route altogether+ // and we can't know for sure how long it'll take. So keep aside a small+ // approximate percentage for this last step.+ const maxPercent = Math.floor(95 + 5 * Math.random());++ let fileObjectKey: string;+ let fileSize: number;++ const encryptedData = file.encryptedData;+ if (+ !(encryptedData instanceof Uint8Array) &&+ encryptedData.chunkCount >= multipartChunksPerPart+ ) {+ // We have a stream, and it is more than multipartChunksPerPart+ // chunks long, so use a multipart upload to upload it.+ ({ objectKey: fileObjectKey, fileSize } =+ await uploadStreamUsingMultipart(+ localID,+ encryptedData,+ uploadContext,+ requestRetrier,+ maxPercent,+ checksumEnabled,+ ));+ } else {+ const data =+ encryptedData instanceof Uint8Array+ ? encryptedData+ : await readEntireStream(encryptedData.stream);+ fileSize = data.length;++ const fileMd5 = shouldSendContentChecksum+ ? computeMd5Base64(data)+ : undefined;+ const fileUploadURL = await uploadService.getUploadURL(+ shouldSendContentChecksum+ ? { contentLength: data.length, contentMd5: fileMd5! }+ : undefined,+ );+ fileObjectKey = fileUploadURL.objectKey;+ const shouldUseWorker = !isCFUploadProxyDisabled;+ if (shouldUseWorker) {+ await putFileViaWorker(fileUploadURL.url, data, requestRetrier, {+ contentMd5: fileMd5,+ });+ } else {+ await putFile(fileUploadURL.url, data, requestRetrier, {+ contentMd5: fileMd5,+ });+ }+ updateUploadProgress(localID, maxPercent);+ }++ const thumbnailMd5 = shouldSendContentChecksum+ ? computeMd5Base64(thumbnail.encryptedData)+ : undefined;+ const thumbnailUploadURL = await uploadService.getUploadURL(+ shouldSendContentChecksum+ ? {+ contentLength: thumbnail.encryptedData.length,+ contentMd5: thumbnailMd5!,+ }+ : undefined,+ );+ const shouldUseWorkerForThumbnail = !isCFUploadProxyDisabled;+ if (shouldUseWorkerForThumbnail) {+ await putFileViaWorker(+ thumbnailUploadURL.url,+ thumbnail.encryptedData,+ requestRetrier,+ { contentMd5: thumbnailMd5 },+ );+ } else {+ await putFile(+ thumbnailUploadURL.url,+ thumbnail.encryptedData,+ requestRetrier,+ { contentMd5: thumbnailMd5 },+ );+ }++ return {+ file: {+ decryptionHeader: file.decryptionHeader,+ objectKey: fileObjectKey,+ size: fileSize,+ },+ thumbnail: {+ decryptionHeader: thumbnail.decryptionHeader,+ objectKey: thumbnailUploadURL.objectKey,+ size: thumbnail.encryptedData.length,+ },+ metadata,+ pubMagicMetadata,+ };+};++/**+ * A factory method that returns a function which will act like variant of+ * {@link retryEnsuringHTTPOk} and also understands the cancellation mechanism+ * used by the upload subsystem.+ *+ * @param abortIfCancelled A function that aborts the operation by throwing a+ * error with the message set to {@link uploadCancelledErrorMessage} if the user+ * has cancelled the upload.+ *+ * @return A function of type {@link HTTPRequestRetrier} that can be used to+ * retry requests. This function will retry requests (obtained afresh each time+ * by calling the provided {@link request} function) in the same manner as+ * {@link retryEnsuringHTTPOk}. Additionally, it will call+ * {@link abortIfCancelled} before each attempt, and also bypass the retries+ * when the abort happens on such cancellations.+ */+const createAbortableRetryEnsuringHTTPOk =+ (abortIfCancelled: () => void): HTTPRequestRetrier =>+ (request, opts) =>+ retryAsyncOperation(+ async () => {+ abortIfCancelled();+ const r = await request();+ ensureOk(r);+ return r;+ },+ {+ ...opts,+ abortIfNeeded(e) {+ if (isUploadCancelledError(e)) throw e;+ },+ },+ );++const uploadStreamUsingMultipart = async (+ fileLocalID: number,+ dataStream: EncryptedFileStream,+ uploadContext: UploadContext,+ requestRetrier: HTTPRequestRetrier,+ maxPercent: number,+ checksumEnabled: boolean,+) => {+ const { isCFUploadProxyDisabled, abortIfCancelled, updateUploadProgress } =+ uploadContext;+ const shouldSendPartChecksums =+ checksumEnabled || !!uploadContext.publicAlbumsCredentials;++ const { stream } = dataStream;+ const streamReader = stream.getReader();++ let uploadPartCount = Math.ceil(+ dataStream.chunkCount / multipartChunksPerPart,+ );++ if (shouldSendPartChecksums) {+ const parts: Uint8Array[] = [];+ const partMd5s: string[] = [];+ let fileSize = 0;+ while (true) {+ abortIfCancelled();+ const partData = await nextMultipartUploadPart(streamReader);+ if (partData.length === 0) break;+ parts.push(partData);+ fileSize += partData.length;+ partMd5s.push(computeMd5Base64(partData));+ }+ const { done } = await streamReader.read();+ if (!done) throw new Error("More chunks than expected");++ uploadPartCount = parts.length;+ if (uploadPartCount == 0) {+ throw new Error("Multipart upload produced no parts");+ }+ const firstPartLength = parts[0]?.length ?? 0;+ if (firstPartLength == 0) {+ throw new Error("Multipart part length missing");+ }+ const partLength = firstPartLength;++ const multipartUploadURLs =+ await uploadService.fetchMultipartUploadURLs(uploadPartCount, {+ contentLength: fileSize,+ partLength,+ partMd5s,+ });++ const percentPerPart = maxPercent / uploadPartCount;+ const completedParts: MultipartCompletedPart[] = [];+ for (const [+ index,+ partUploadURL,+ ] of multipartUploadURLs.partURLs.entries()) {+ abortIfCancelled();++ const partNumber = index + 1;+ const partData = parts[index];+ const checksum = partMd5s[index];+ if (!partData || !checksum) {+ throw new Error("Multipart checksum part mismatch");+ }++ const eTag = !isCFUploadProxyDisabled+ ? await putFilePartViaWorker(+ partUploadURL,+ partData,+ requestRetrier,+ { contentMd5: checksum },+ )+ : await putFilePart(partUploadURL, partData, requestRetrier, {+ contentMd5: checksum,+ });+ if (!eTag) throw new Error(eTagMissingErrorMessage);++ updateUploadProgress(fileLocalID, percentPerPart * partNumber);+ completedParts.push({ partNumber, eTag });+ parts[index] = new Uint8Array(0); // release memory+ }++ const completionURL = multipartUploadURLs.completeURL;+ if (!isCFUploadProxyDisabled) {+ await completeMultipartUploadViaWorker(+ completionURL,+ completedParts,+ requestRetrier,+ );+ } else {+ await completeMultipartUpload(+ completionURL,+ completedParts,+ requestRetrier,+ );+ }++ return { objectKey: multipartUploadURLs.objectKey, fileSize };+ }++ const multipartUploadURLs =+ await uploadService.fetchMultipartUploadURLs(uploadPartCount);++ const percentPerPart = maxPercent / uploadPartCount;+ let fileSize = 0;+ const completedParts: MultipartCompletedPart[] = [];+ for (const [+ index,+ partUploadURL,+ ] of multipartUploadURLs.partURLs.entries()) {+ abortIfCancelled();++ const partNumber = index + 1;+ const partData = await nextMultipartUploadPart(streamReader);+ fileSize += partData.length;++ const eTag = !isCFUploadProxyDisabled+ ? await putFilePartViaWorker(+ partUploadURL,+ partData,+ requestRetrier,+ )+ : await putFilePart(partUploadURL, partData, requestRetrier);+ if (!eTag) throw new Error(eTagMissingErrorMessage);++ updateUploadProgress(fileLocalID, percentPerPart * partNumber);+ completedParts.push({ partNumber, eTag });+ }+ const { done } = await streamReader.read();+ if (!done) throw new Error("More chunks than expected");++ const completionURL = multipartUploadURLs.completeURL;+ if (!isCFUploadProxyDisabled) {+ await completeMultipartUploadViaWorker(+ completionURL,+ completedParts,+ requestRetrier,+ );+ } else {+ await completeMultipartUpload(+ completionURL,+ completedParts,+ requestRetrier,+ );+ }++ return { objectKey: multipartUploadURLs.objectKey, fileSize };+};++/**+ * Construct byte arrays, up to 20 MB each, containing the contents of (up to)+ * the next 5 {@link streamEncryptionChunkSize} chunks read from the given+ * {@link streamReader}.+ */+const nextMultipartUploadPart = async (+ streamReader: ReadableStreamDefaultReader<Uint8Array>,+) => {+ const chunks = [];+ for (let i = 0; i < multipartChunksPerPart; i++) {+ const { done, value: chunk } = await streamReader.read();+ if (done) break;+ chunks.push(chunk);+ }+ return mergeUint8Arrays(chunks);+};++/**+ * Finalize an upload by creating an {@link EnteFile} on remote.+ */+const createRemoteFile = async (+ newFileRequest: PostEnteFileRequest,+ uploadContext: UploadContext,+) => {+ const { publicAlbumsCredentials } = uploadContext;++ return publicAlbumsCredentials+ ? retriedPostPublicAlbumsEnteFile(+ newFileRequest,+ publicAlbumsCredentials,+ uploadContext,+ )+ : retriedPostEnteFile(newFileRequest, uploadContext);+};++const retriedPostPublicAlbumsEnteFile = async (+ newFileRequest: PostEnteFileRequest,+ credentials: PublicAlbumsCredentials,+ { abortIfCancelled }: UploadContext,+) =>+ retryAsyncOperation(+ () => {+ abortIfCancelled();+ return postPublicAlbumsEnteFile(newFileRequest, credentials);+ },+ {+ abortIfNeeded: (e) => {+ if (isUploadCancelledError(e)) throw e;+ if (e instanceof HTTPError) {+ switch (e.res.status) {+ case 413:+ throw new Error(fileTooLargeErrorMessage);+ }+ }+ },+ },+ );++const retriedPostEnteFile = async (+ newFileRequest: PostEnteFileRequest,+ { abortIfCancelled }: UploadContext,+) =>+ retryAsyncOperation(+ () => {+ abortIfCancelled();+ return postEnteFile(newFileRequest);+ },+ {+ abortIfNeeded: (e) => {+ if (isUploadCancelledError(e)) throw e;+ if (e instanceof HTTPError) {+ switch (e.res.status) {+ case 401:+ throw new Error(sessionExpiredErrorMessage);+ case 402:+ throw new Error(subscriptionExpiredErrorMessage);+ case 413:+ throw new Error(fileTooLargeErrorMessage);+ case 426:+ throw new Error(storageLimitExceededErrorMessage);+ }+ }+ },+ },+ );diff --git a/web/apps/albums/vendor/ente-gallery/services/video.ts b/web/apps/albums/vendor/ente-gallery/services/video.tsnew file mode 100644index 0000000000..9962f46516--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/services/video.ts@@ -0,0 +1,1067 @@+import { ensureLocalUser } from "ente-accounts/services/user";+import { isDesktop } from "ente-base/app";+import { assertionFailed } from "ente-base/assert";+import { decryptBlobBytes, encryptBlob } from "ente-base/crypto";+import type { EncryptedBlob } from "ente-base/crypto/types";+import { ensureElectron } from "ente-base/electron";+import { isHTTP4xxError, type PublicAlbumsCredentials } from "ente-base/http";+import { getKV, getKVB, getKVN, setKV } from "ente-base/kv";+import log from "ente-base/log";+import { apiURL } from "ente-base/origins";+import { ensureAuthToken } from "ente-base/token";+import { uniqueFilesByID } from "ente-gallery/utils/file";+import { fileLogID, type EnteFile } from "ente-media/file";+import { FileType } from "ente-media/file-type";+import { updateFilePublicMagicMetadata } from "ente-new/photos/services/file";+import { savedCollectionFiles } from "ente-new/photos/services/photos-fdb";+import { savedTrashItemFileIDs } from "ente-new/photos/services/trash";+import { gunzip, gzip } from "ente-new/photos/utils/gzip";+import { randomSample } from "ente-utils/array";+import { ensurePrecondition } from "ente-utils/ensure";+import { wait } from "ente-utils/promise";+import { z } from "zod";+import {+ initiateGenerateHLS,+ readVideoStream,+ videoStreamDone,+ type GenerateHLSResult,+} from "../utils/native-stream";+import { downloadManager, isNetworkDownloadError } from "./download";+import {+ fetchFileData,+ fetchFilePreviewData,+ putVideoData,+ syncUpdatedFileDataFileIDs,+} from "./file-data";+import {+ fileSystemUploadItemIfUnchanged,+ type FileSystemUploadItem,+ type ProcessableUploadItem,+ type TimestampedFileSystemUploadItem,+} from "./upload";++export type HLSGenerationEnabledStatus = "processing" | "idle";++export type HLSGenerationStatus =+ | { enabled: false }+ | { enabled: true; status?: HLSGenerationEnabledStatus };++interface VideoProcessingQueueItem {+ /**+ * The {@link EnteFile} (guaranteed to be of {@link FileType.video}) whose+ * video data needs processing.+ */+ file: EnteFile;+ /**+ * The {@link TimestampedFileSystemUploadItem} when available for the newly+ * uploaded {@link file}.+ *+ * It will be present when this queue item was enqueued during a upload from+ * the current client. If present, this serves as an optimization allowing+ * us to directly read the file off the user's file system.+ */+ timestampedUploadItem?: TimestampedFileSystemUploadItem;+}++const idleWaitInitial = 10 * 1000; /* 10 sec */+const idleWaitMax = idleWaitInitial * 2 ** 6; /* 640 sec */++/**+ * Internal in-memory state shared by the functions in this module.+ *+ * This entire object will be reset on logout.+ */+class VideoState {+ /**+ * `true` if the generation of HLS streams has been enabled on this client.+ */+ isHLSGenerationEnabled = false;+ /**+ * Subscriptions to {@link HLSGenerationStatus} updates attached using+ * {@link hlsGenerationStatusSubscribe}.+ */+ hlsGenerationStatusListeners: (() => void)[] = [];+ /**+ * Snapshot of the {@link HLSGenerationStatus} returned by the+ * {@link hlsGenerationStatusSnapshot} function.+ */+ hlsGenerationStatusSnapshot: HLSGenerationStatus | undefined;+ /**+ * Value of the {@link status} field in the last+ * {@link hlsGenerationStatusSnapshot}.+ */+ lastEnabledStatus: HLSGenerationEnabledStatus | undefined;+ /**+ * Queue of recently uploaded items waiting to be processed.+ */+ liveQueue: VideoProcessingQueueItem[] = [];+ /**+ * Active queue processor, if any.+ */+ queueProcessor: Promise<void> | undefined;+ /**+ * A promise that the main processing loop waits for in addition to the idle+ * timeout. Can be resolved using {@link resolveTick}.+ */+ tick: Promise<void> | undefined;+ /**+ * A function that can be called to resolve {@link tick}.+ *+ * See: [Note: Exiting idle wait of processing loop].+ */+ resolveTick: (() => void) | undefined;+ /**+ * The time to sleep if nothing is pending.+ *+ * Goes from {@link idleWaitInitial} to {@link idleWaitMax} in doublings.+ * Reset back to {@link idleWaitInitial} in case of any activity.+ */+ idleWait = idleWaitInitial;+ /**+ * `true` if we have synced at least once with remote.+ *+ * We use this to gate the processing of the backfill queue to avoid+ * unnecessarily picking up files that have already been indexed elsewhere+ * (we'll still check before processing them, but still that's unnecessary+ * work this flag can save us).+ */+ haveSyncedOnce = false;+}++/**+ * State shared by the functions in this module. See {@link VideoState}.+ */+let _state = new VideoState();++/**+ * Reset any internal state maintained by the module.+ *+ * This is primarily meant as a way for stateful apps (e.g. photos) to clear any+ * user specific state on logout.+ */+export const resetVideoState = () => {+ // Note: We rely on [Note: Full reload on logout] to abort any in-flight+ // requests.+ _state = new VideoState();+};++/**+ * A function that can be used to subscribe to updates in the HLS generation+ * settings and status.+ *+ * See: [Note: Snapshots and useSyncExternalStore].+ */+export const hlsGenerationStatusSubscribe = (+ onChange: () => void,+): (() => void) => {+ _state.hlsGenerationStatusListeners.push(onChange);+ return () => {+ _state.hlsGenerationStatusListeners =+ _state.hlsGenerationStatusListeners.filter((l) => l != onChange);+ };+};++/**+ * Return the last know, cached {@link HLSGenerationStatus}.+ *+ * See also {@link hlsGenerationStatusSubscribe}.+ *+ * This function can be safely called even if {@link isHLSGenerationSupported}+ * is `false` (in such cases, it will always return `undefined`). This is so+ * that it can be unconditionally called as part of a React hook.+ *+ * A return value of `undefined` indicates that the HLS generation subsystem has+ * not been initialized yet.+ */+export const hlsGenerationStatusSnapshot = () =>+ _state.hlsGenerationStatusSnapshot;++const setHLSGenerationStatusSnapshot = (snapshot: HLSGenerationStatus) => {+ _state.hlsGenerationStatusSnapshot = snapshot;+ _state.hlsGenerationStatusListeners.forEach((l) => l());+};++/**+ * A variant of {@link setHLSGenerationStatusSnapshot} that only triggers an+ * update of the snapshot if the enabled state is different from the last known+ * enabled state.+ */+const updateSnapshotIfNeeded = (+ status: HLSGenerationEnabledStatus | undefined,+) => {+ const enabled = _state.isHLSGenerationEnabled;+ if (enabled && status != _state.lastEnabledStatus) {+ _state.lastEnabledStatus = status;+ setHLSGenerationStatusSnapshot({ enabled, status });+ }+};++/**+ * Return `true` if this client is capable of generating HLS streams for+ * uploaded videos.+ */+export const isHLSGenerationSupported = isDesktop;++/**+ * Initialize the video processing subsystem unless the user has disabled HLS+ * generation in settings.+ */+export const initVideoProcessing = async () => {+ let enabled = false;+ if (await savedGenerateHLS()) enabled = true;++ _state.isHLSGenerationEnabled = enabled;++ // Update snapshot to reflect the enabled setting. The status will get+ // filled in when we tick.+ setHLSGenerationStatusSnapshot({ enabled });+};++/**+ * Return the persisted user preference for HLS generation.+ */+const savedGenerateHLS = async () => await getKVB("generateHLS");++/**+ * Update the persisted user preference for HLS generation.+ *+ * Use {@link savedGenerateHLS} to get the persisted value back.+ */+const saveGenerateHLS = (enabled: boolean) => setKV("generateHLS", enabled);++/**+ * Enable or disable (toggle) the HLS generation on this client.+ *+ * When HLS generation is enabled, this client will process videos to generate a+ * streamable variant of them.+ *+ * Precondition: {@link isHLSGenerationSupported} must be `true`.+ */+export const toggleHLSGeneration = async () => {+ if (!isHLSGenerationSupported) {+ assertionFailed();+ return;+ }++ const enabled = !_state.isHLSGenerationEnabled;++ // Clear transient fields.+ _state.lastEnabledStatus = undefined;++ // Update disk.+ await saveGenerateHLS(enabled);+ // Update in memory.+ _state.isHLSGenerationEnabled = enabled;++ // Update snapshot. Right now we only set the enabled setting. The status+ // will get filled in when we tick.+ setHLSGenerationStatusSnapshot({ enabled });++ // Wake up the processor if needed.+ if (enabled) tickNow();+};++export interface HLSPlaylistData {+ /** A data URL to a HLS playlist that streams the video. */+ playlistURL: string;+ /** The width of the video (px). */+ width: number;+ /** The height of the video (px). */+ height: number;+}++/**+ * See: [Note: Caching HLS playlist data] for the semantics of "skip".+ */+export type HLSPlaylistDataForFile = HLSPlaylistData | "skip" | undefined;++/**+ * Return a HLS playlist that can be used to stream playback of then given video+ * {@link file}.+ *+ * @param file An {@link EnteFile} of type video.+ *+ * @param publicAlbumsCredentials Credentials to use for fetching the HLS+ * playlist when we are running in the context of the public albums app. If+ * these are not specified, then the credentials of the logged in user are used.+ *+ * @returns The HLS playlist as a string (along with the dimensions of the video+ * it will play), or `undefined` if there is no video preview associated with+ * the given file.+ *+ * See: [Note: Video playlist and preview]+ *+ * ---+ *+ * [Note: Caching HLS playlist data]+ *+ * The playlist data can be cached in an asymmetric manner.+ *+ * - If a file has a corresponding HLS playlist, then currently there is no+ * scenario (apart from file deletion, where the playlist also gets deleted)+ * where the playlist is deleted after being created. There is a limit to the+ * validity of the pre-signed chunk URLs within the playlist we create (which+ * we do handle, see `createHLSPlaylistItemDataValidity`), but the original+ * playlist itself does not change. Updates are technically possible, but+ * apart from a misbehaving client, are not expected (and should be no-ops in+ * the rare cases they happen, since effectively same playlist should get+ * regenerated again). All in all, this means that a positive result ("this+ * file has a playlist") can be cached indefinitely.+ *+ * - If a file does not have a HLS playlist, it might be because it is not+ * eligible for being streamed (e.g. it is already small and in a compatible+ * codec). See [Note: Marking files which do not need video processing] for+ * more details of this case. In particular, we can cache this state in memory+ * indefinitely too, since there isn't a current case where either this+ * eligibility can change, or the client gain the ability to handle them+ * without restarting.+ *+ * - Finally, if a file does not have an HLS playlist but and it is eligible for+ * being streamed, then a client (this one, or a different one) can process it+ * at any arbitrary time. So the negative result ("this file does not have a+ * playlist") cannot be cached.+ *+ * So while we can easily cache the first case ("this file has a playlist") and+ * second case ("this file doesn't need a streaming variant"), we need to deal+ * with the third case ("this file does not have a playlist") by marking the+ * cached values as "transient" and always recheck for a playlist when opening+ * the slide.+ */+export const hlsPlaylistDataForFile = async (+ file: EnteFile,+ publicAlbumsCredentials?: PublicAlbumsCredentials,+): Promise<HLSPlaylistDataForFile> => {+ ensurePrecondition(file.metadata.fileType == FileType.video);++ if (file.pubMagicMetadata?.data.sv == 1) {+ return "skip";+ }++ const playlistFileData = await fetchFileData(+ "vid_preview",+ file.id,+ publicAlbumsCredentials,+ );+ if (!playlistFileData) return undefined;++ const {+ type,+ playlist: playlistTemplate,+ width,+ height,+ } = await decryptPlaylistJSON(playlistFileData, file);++ // A playlist format the current client does not understand.+ if (type != "hls_video") return undefined;++ const videoURL = await fetchFilePreviewData(+ "vid_preview",+ file.id,+ publicAlbumsCredentials,+ );+ if (!videoURL) return undefined;++ // [Note: HLS playlist format]+ //+ // The decrypted playlist is a regular HLS playlist for an encrypted media+ // stream, except that it uses a placeholder "output.ts" which needs to be+ // replaced with the URL of the actual encrypted video data. A single URL+ // pointing to the entire encrypted video data suffices; the individual+ // chunks are fetched by HTTP range requests.+ //+ // Here is an example of what the contents of the `playlist` variable might+ // look like at this point:+ //+ // #EXTM3U+ // #EXT-X-VERSION:4+ // #EXT-X-TARGETDURATION:8+ // #EXT-X-MEDIA-SEQUENCE:0+ // #EXT-X-KEY:METHOD=AES-128,URI="data:text/plain;base64,XjvG7qeRrsOpPUbJPh2Ikg==",IV=0x00000000000000000000000000000000+ // #EXTINF:8.333333,+ // #EXT-X-BYTERANGE:3046928@0+ // output.ts+ // #EXTINF:8.333333,+ // #EXT-X-BYTERANGE:3012704@3046928+ // output.ts+ // #EXTINF:2.200000,+ // #EXT-X-BYTERANGE:834736@6059632+ // output.ts+ // #EXT-X-ENDLIST+ //+ // The HLS playlist format is specified in RFC 8216:+ // https://datatracker.ietf.org/doc/html/rfc8216+ //+ // Some notes pertinent to us:+ //+ // - A URI line identifies a media segment.+ //+ // - The EXTINF tag specifies the duration of the media segment (applies+ // only to the next URI line that follows it in the playlist).+ //+ // - The EXT-X-BYTERANGE tag indicates that a media segment is a sub-range+ // of the resource identified by its URI (applies only to the next URI+ // line that follows it in the playlist). The value should be of the+ // format `<n>[@<o>]` where n is an integer indicating the length of the+ // sub-range in bytes, and if present, o is the integer indicating the+ // start of the sub-range as a byte offset from the beginning of the+ // resource. If o is not present, the sub-range begins at the next byte+ // following the sub-range of the previous media segment.+ //+ // - Media segments may be encrypted, and the EXT-X-KEY tag specifies how to+ // decrypt them. It applies to all subsequent media segment (until another+ // EXT-X-KEY). Value is an `<attribute-list>`, consisting of the METHOD+ // (AES-128 for us), URI and IV attributes. The URI attribute value is a+ // quoted string containing a URI that specifies how to obtain the key.++ const playlist = playlistTemplate.replaceAll(+ "\noutput.ts",+ `\n${videoURL}`,+ );++ // From the RFC+ //+ // > Each playlist file must be identifiable either by the path component of+ // > its URI (ending with either ".m3u8" or ".m3u") or by its HTTP+ // > Content-Type ("application/vnd.apple.mpegurl" or "audio/mpegurl").+ // > Clients should refuse to parse playlists that are not so identified.+ //+ // As of now (2025), there isn't a way to set the filename for a URL created+ // via createObjectURL, so instead we create a "data:" URL where the MIME+ // type can be specified.+ //+ // The generated data URL be of the form:+ //+ // data:application/vnd.apple.mpegurl;base64,<base64-string>++ const playlistURL = await blobToDataURL(+ new Blob([playlist], { type: "application/vnd.apple.mpegurl" }),+ );++ return { playlistURL, width, height };+};++const PlaylistJSON = z.object({+ /**+ * The type of the playlist.+ *+ * The only value we currently understand on this client is "hls_video", but+ * for future extensibility this might be other values too.+ */+ type: z.string(),+ /**+ * The HLS playlist, as a string.+ */+ playlist: z.string(),+ /**+ * The width of the video (px).+ */+ width: z.number(),+ /**+ * The height of the video (px).+ */+ height: z.number(),+ /**+ * The size (in bytes) of the corresponding file containing the video+ * segments that the playlist refers to.+ */+ size: z.number(),+});++type PlaylistJSON = z.infer<typeof PlaylistJSON>;++const decryptPlaylistJSON = async (+ encryptedPlaylist: EncryptedBlob,+ file: EnteFile,+) => {+ const decryptedBytes = await decryptBlobBytes(encryptedPlaylist, file.key);+ const jsonString = await gunzip(decryptedBytes);+ return PlaylistJSON.parse(JSON.parse(jsonString));+};++/**+ * Convert a blob to a `data:` URL.+ */+const blobToDataURL = (blob: Blob) =>+ new Promise<string>((resolve) => {+ const reader = new FileReader();+ // We need to cast to a string here. This should be safe since MDN says:+ //+ // > the result attribute contains the data as a data: URL representing+ // > the file's data as a base64 encoded string.+ // >+ // > https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL+ reader.onload = () => resolve(reader.result as string);+ reader.readAsDataURL(blob);+ });++/**+ * Return the (persistent) {@link Set} containing the ids of the files which+ * have already been processed for generating their streaming variant.+ *+ * {@link savedProcessedVideoFileIDs} and its sibling+ * {@link savedFailedVideoFileIDs} are mutually exclusive - that is, a file ID+ * will be present in only one of them at max. We maintain that invariant in the+ * higher level `mark*` functions when updating either of these persisted sets.+ *+ * The data is retrieved from persistent storage (KV DB), where it is stored as+ * an array.+ */+const savedProcessedVideoFileIDs = () =>+ // See: [Note: Avoiding Zod parsing for large DB arrays]+ getKV("videoPreviewProcessedFileIDs").then((v) => new Set(v as number[]));++/**+ * Return the (persistent) {@link Set} containing the ids of the files for which+ * an attempt to generate a streaming variant failed locally.+ *+ * @see also {@link savedProcessedVideoFileIDs}.+ */+const savedFailedVideoFileIDs = () =>+ // See: [Note: Avoiding Zod parsing for large DB arrays]+ getKV("videoPreviewFailedFileIDs").then((v) => new Set(v as number[]));++/**+ * Update the persisted set of IDs of files which have already been processed+ * and have a video preview generated (either on this client, or elsewhere).+ *+ * @see also {@link savedProcessedVideoFileIDs}.+ */+const saveProcessedVideoFileIDs = (videoFileIDs: Set<number>) =>+ setKV("videoPreviewProcessedFileIDs", Array.from(videoFileIDs));++/**+ * Update the persisted set of IDs of files for which attempt to generate a+ * video preview failed on this client.+ *+ * @see also {@link savedProcessedVideoFileIDs}.+ */+const saveFailedVideoFileIDs = (videoFileIDs: Set<number>) =>+ setKV("videoPreviewFailedFileIDs", Array.from(videoFileIDs));++/**+ * Mark the provided file ID as having been processed to generate a video+ * preview.+ *+ * The mark is persisted locally in IndexedDB (KV DB), so will persist across+ * app restarts (but not across logouts).+ *+ * @see also {@link savedProcessedVideoFileIDs}.+ */+const markProcessedVideoFileID = async (fileID: number) => {+ const savedIDs = await savedProcessedVideoFileIDs();+ const failedIDs = await savedFailedVideoFileIDs();+ savedIDs.add(fileID);+ if (failedIDs.delete(fileID)) await saveFailedVideoFileIDs(failedIDs);+ await saveProcessedVideoFileIDs(savedIDs);+};++/**+ * Mark multiple file IDs as processed. Plural variant of+ * {@link markProcessedVideoFileID}.+ */+const markProcessedVideoFileIDs = async (fileIDs: Set<number>) => {+ const savedIDs = await savedProcessedVideoFileIDs();+ const failedIDs = await savedFailedVideoFileIDs();+ await Promise.all([+ saveProcessedVideoFileIDs(savedIDs.union(fileIDs)),+ saveFailedVideoFileIDs(failedIDs.difference(fileIDs)),+ ]);+};++/**+ * Mark the provided file as having failed in a non-transient manner when we+ * tried processing it to generate a video preview on this client.+ *+ * Similar to [Note: Transient and permanent indexing failures], we attempt to+ * separate failures into two categories - transients, which leave no mark no+ * the DB so that the file eventually gets retried; and permanent, where we keep+ * a persistent record of failure so that this client does not go into a loop+ * reattempting preview generation for the specific unprocessable (to the best+ * of the current client's ability) item.+ *+ * The mark is local only, and will be reset on logout, or if another client+ * with a different able is able to process it.+ */+const markFailedVideoFile = async (file: EnteFile) => {+ log.info(`Generate HLS for ${fileLogID(file)} | failed`);+ const failedIDs = await savedFailedVideoFileIDs();+ failedIDs.add(file.id);+ await saveFailedVideoFileIDs(failedIDs);+};++/**+ * Return the persisted time when we last synced processed file IDs with remote.+ *+ * The returned value is an epoch millisecond value suitable to be passed to+ * {@link syncUpdatedFileDataFileIDs}.+ */+const savedSyncLastUpdatedAt = () => getKVN("videoPreviewSyncLastUpdatedAt");++/**+ * Update the persisted timestamp used for syncing processed file IDs with+ * remote.+ *+ * Use {@link savedSyncLastUpdatedAt} to get the persisted value back.+ */+const saveSyncLastUpdatedAt = (lastUpdatedAt: number) =>+ setKV("videoPreviewSyncLastUpdatedAt", lastUpdatedAt);++/**+ * Fetch IDs of files from remote that have been processed by other clients+ * since the last time we checked.+ */+const pullProcessedFileIDs = async () =>+ syncUpdatedFileDataFileIDs(+ "vid_preview",+ (await savedSyncLastUpdatedAt()) ?? 0,+ async ({ fileIDs, lastUpdatedAt }) => {+ await Promise.all([+ markProcessedVideoFileIDs(fileIDs),+ saveSyncLastUpdatedAt(lastUpdatedAt),+ ]);+ },+ );++/**+ * Remove any saved entries for file IDs which were previously in trash but now+ * have been permanently deleted.+ *+ * This is called when processing the trash diff. It gives us a hook to clear+ * these IDs from our video processing related local state.+ *+ * See: [Note: Pruning stale status-diff entries]+ *+ * It is a no-op when we're running in the context of the web app (since it+ * doesn't currently process videos, so doesn't need to keep any local state for+ * that purpose).+ */+export const videoPrunePermanentlyDeletedFileIDsIfNeeded = async (+ deletedFileIDs: Set<number>,+) => {+ if (!isHLSGenerationSupported) return;++ const existing = await savedProcessedVideoFileIDs();+ if (existing.size > 0) {+ const updated = existing.difference(deletedFileIDs);+ if (updated.size != existing.size) {+ await saveProcessedVideoFileIDs(updated);+ }+ }+};++/**+ * If video processing is enabled, trigger a pull from remote and then proceed+ * with any subsequent backfill queue processing of pending videos.+ *+ * This function is intended to be called during a full remote pull (See: [Note:+ * Remote pull]). It is a no-op if video processing is not enabled or eligible+ * on this device. Otherwise it pulls the list of already processed file IDs+ * with remote.+ *+ * At this point it also triggers processing of the backfill (if needed), but+ * doesn't wait for it to complete (which might take a time for big libraries).+ *+ * Calling it when a backfill has already been triggered by a previous sync is+ * also a no-op. However, a backfill does not start until at least one pull of+ * file IDs has been completed with remote, to avoid picking up work on file IDs+ * that have already been processed elsewhere.+ */+export const videoProcessingSyncIfNeeded = async () => {+ if (!isHLSGenerationSupported) return;++ // The `haveSyncedOnce` flag tracks whether or not a sync has happened for+ // the app, and is not specific to video processing. We always set it even+ // if HLS generation is currently disabled so that we can immediately start+ // processing the backfill if it gets video processing gets enabled during+ // the app's session, without waiting for the next sync to happen.+ _state.haveSyncedOnce = true;++ if (!isHLSGenerationEnabled()) return;++ await pullProcessedFileIDs();++ tickNow(); /* if not already ticking */+};++/**+ * Create a streamable HLS playlist for a video uploaded from this client.+ *+ * This function is called by the uploader when it uploads a new file from this+ * client, allowing us to create its streamable variant without needing to+ * redownload the video.+ *+ * It only does the processing if we're running in the context of the desktop+ * app as the video processing is resource intensive. In particular, processing+ * large videos with the Wasm ffmpeg implementation can cause the app to crash,+ * on mobile devices (see https://github.com/ffmpegwasm/ffmpeg.wasm/issues/851).+ * In contrast, the desktop app can us the efficient native FFmpeg integration.+ *+ * Note that this function is an optimization. Even if we don't process the+ * video at this time (e.g. if the video processor can't keep up with the+ * uploads), we will eventually process it later as part of a backfill.+ *+ * @param file The {@link EnteFile} that got uploaded (video or otherwise).+ *+ * @param processableUploadItem The item that was uploaded. This can be used to+ * read the contents of the file that got uploaded directly from disk instead of+ * needing to download it again.+ */+export const processVideoNewUpload = (+ file: EnteFile,+ processableUploadItem: ProcessableUploadItem,+) => {+ if (!isHLSGenerationSupported) return;+ if (!isHLSGenerationEnabled()) return;+ if (file.metadata.fileType != FileType.video) return;+ if (processableUploadItem instanceof File) {+ // While the types don't guarantee it, we really shouldn't be getting+ // here. The only time a processableUploadItem can be File when we're+ // running in the desktop app is when an edited image copy is being+ // saved. But we've already checked above that the file which was+ // uploaded was a video.+ assertionFailed();+ return;+ }++ // Enqueue the item.+ _state.liveQueue.push({+ file,+ timestampedUploadItem: processableUploadItem,+ });++ // Interrupt any idle timeouts if any, go go.+ tickNow();+};++/**+ * If {@link processQueue} is not already running, start it.+ *+ * If there is an existing {@link resolveTick} so that if perchance+ * {@link processQueue} was waiting on an idle timeout, it wakes up now.+ *+ * Also create a new {@link tick} and {@link resolveTick} pair for use by+ * subsequent calls to {@link tickNow}+ */+const tickNow = () => {+ // See: [Note: Exiting idle wait of processing loop] for what this function+ // is trying to do.++ // Resolve the existing tick (if any).+ if (_state.resolveTick) _state.resolveTick();++ // Create a new resolvable pair.+ _state.tick = new Promise((r) => (_state.resolveTick = r));++ // Start the processor if it isn't already running.+ _state.queueProcessor ??= processQueue();+};++export const isHLSGenerationEnabled = () => _state.isHLSGenerationEnabled;++/**+ * The video processing loop goes through videos one by one, preferring items in+ * the liveQueue, otherwise working for a backlog item. If there are no items to+ * process, it goes on an idle timeout. The {@link resolveTick} state property+ * can be used to tickle it out of sleep.+ *+ * [Note: Exiting idle wait of processing loop]+ *+ * The following toy example illustrates the overall mechanism:+ *+ * let resolveTick+ * let tick = new Promise((r) => (resolveTick = r));+ *+ * const tickNow = () => {+ * resolveTick();+ * tick = new Promise((r) => (resolveTick = r));+ * }+ *+ * const f = async () => {+ * for (let i of [1, 2, 3, 4, 5]) {+ * const wait = new Promise((r) => setTimeout(r, i * 1e3));+ * await Promise.race([wait, tick]);+ * }+ * }+ *+ * f()+ *+ * setTimeout(tickNow, 2500);+ * setTimeout(tickNow, 5000);+ * setTimeout(tickNow, 5500);+ *+ * The `Promise.race([wait, tick])` means that the loop will proceed to the next+ * item either if the timeout expires, or if tick resolves. Thus the same+ * function can handle both the internally determined processing of backfill+ * batches, and the externally triggered processing of live uploads.+ */+const processQueue = async () => {+ if (!isHLSGenerationSupported || !isHLSGenerationEnabled()) {+ assertionFailed(); /* we shouldn't have come here */+ return;+ }++ const userID = ensureLocalUser().id;++ // We mark failures in the local DB for in expected failure mode. As an+ // additional protection against loops in unforeseen scenarios, keep a+ // transient in-memory list of IDs which shouldn't be looped.+ const transientFailedFileIDs = new Set<number>();++ let bq: typeof _state.liveQueue | undefined;+ while (isHLSGenerationEnabled()) {+ let item = _state.liveQueue.shift();+ if (!item) {+ // Initialize or refill queue.+ if (!bq?.length) {+ if (_state.haveSyncedOnce) {+ bq = await backfillQueue(userID);+ } else {+ log.info("Not attempting backfill until first sync");+ }+ }+ // Take item if queue is not empty.+ if (bq?.length) item = bq.pop();+ }+ if (item && !transientFailedFileIDs.has(item.file.id)) {+ updateSnapshotIfNeeded("processing");++ try {+ await processQueueItem(item);+ await markProcessedVideoFileID(item.file.id);+ // Reset the idle wait on success.+ _state.idleWait = idleWaitInitial;+ } catch (e) {+ // This will get retried again at some point later.+ log.error(`Failed to process video ${fileLogID(item.file)}`, e);+ transientFailedFileIDs.add(item.file.id);+ }+ } else {+ // There are no more items in either the live queue or backlog.+ // Go to sleep (for increasingly longer durations, capped at a+ // maximum).+ updateSnapshotIfNeeded("idle");++ const idleWait = _state.idleWait;+ _state.idleWait = Math.min(idleWait * 2, idleWaitMax);++ // `tick` allows the sleep to be interrupted when there is+ // potential activity.+ if (!_state.tick) assertionFailed();+ const tick = _state.tick!;++ log.debug(() => ["gen-hls", { idleWait }]);+ await Promise.race([tick, wait(idleWait)]);+ }+ }++ updateSnapshotIfNeeded(undefined);++ _state.queueProcessor = undefined;+};++/**+ * Return the next batch of videos that need to be processed.+ *+ * If there is nothing pending, return an empty array.+ *+ * @param userID The ID of the currently logged in user. This is used to filter+ * the files to only include those that are owned by the user.+ */+const backfillQueue = async (+ userID: number,+): Promise<VideoProcessingQueueItem[]> => {+ const allCollectionFiles = await savedCollectionFiles();+ const localTrashFileIDs = await savedTrashItemFileIDs();+ const videoFiles = uniqueFilesByID(+ allCollectionFiles.filter(+ (f) =>+ // Only files the user owns.+ f.ownerID == userID &&+ // Only videos.+ f.metadata.fileType == FileType.video &&+ // Not in trash.+ !localTrashFileIDs.has(f.id) &&+ // See: [Note: Marking files which do not need video processing]+ f.pubMagicMetadata?.data.sv != 1,+ ),+ );++ const doneIDs = (await savedProcessedVideoFileIDs()).union(+ await savedFailedVideoFileIDs(),+ );+ const pendingVideoFiles = videoFiles.filter((f) => !doneIDs.has(f.id));++ const batch = randomSample(pendingVideoFiles, 50);+ return batch.map((file) => ({ file }));+};++/**+ * Generate and upload a streamable variant of the given {@link EnteFile}.+ *+ * [Note: Preview variant of videos]+ *+ * A preview variant of a video is created by transcoding it into a smaller,+ * streamable, and (more) widely supported format.+ *+ * 1. The video is transcoded into a format that is both smaller but is also+ * using a much more widely supported codec so that it can be played back+ * readily across browsers and OSes independent of the codec used by the+ * source video.+ *+ * 2. We use a format that can be streamed back by the client instead of needing+ * to download it all at once, and also generate an HLS playlist that refers+ * to the offsets in the generated video file.+ *+ * 3. Both the generated video and the HLS playlist are then uploaded, E2EE.+ */+const processQueueItem = async ({+ file,+ timestampedUploadItem,+}: VideoProcessingQueueItem) => {+ const electron = ensureElectron();++ log.debug(() => ["gen-hls", { file, timestampedUploadItem }]);++ const playlistFileData = await fetchFileData("vid_preview", file.id);+ if (playlistFileData) {+ // Since video processing for even an individual item can take+ // substantial time, it is possible that an item might've gotten+ // processed on a different client in the interval between us enqueuing+ // it and us getting here.+ //+ // Bail out early to avoid unnecessary duplicate work.+ log.info(`Generate HLS for ${fileLogID(file)} | already-processed`);+ return;+ }++ const uploadItem = timestampedUploadItem+ ? await fileSystemUploadItemIfUnchanged(+ timestampedUploadItem,+ electron.fs.statMtime,+ )+ : undefined;++ let sourceVideo: FileSystemUploadItem | ReadableStream | undefined =+ uploadItem;+ if (!sourceVideo) {+ try {+ sourceVideo = (await downloadManager.fileStream(file, {+ background: true,+ }))!;+ } catch (e) {+ if (!isNetworkDownloadError(e)) await markFailedVideoFile(file);+ throw e;+ }+ }++ // [Note: Upload HLS video segment from node side]+ //+ // The generated video can be huge (multi-GB), too large to read it into+ // memory as an arrayBuffer.+ //+ // One option was to chain the video stream response (from the node side)+ // directly into a fetch request to `objectUploadURL`, however that requires+ // HTTP/2 (our servers support it, but self hosters' might not). Also that+ // approach won't work with retries on transient failures unless we+ // duplicate the stream beforehand, which invalidates the point of+ // streaming.+ //+ // Another mid-way option was to do it partially here - obtain the pre-signed+ // upload URLs here (since we already have the rest of the scaffolding to+ // make API requests), and then provide this pre-signed URL to the node side+ // so that it can directly upload the generated video segments.+ //+ // However, that then gets into a issue for multipart uploads since we don't+ // know the size of the generated HLS video segment file beforehand. We can+ // try to estimate it, and that is indeed what we started off with, and that+ // approach worked fine too.+ //+ // However, estimates being estimates, it felt better to make things more+ // deterministic by moving the request for the pre-signed URLs also to the+ // desktop app side. This also sidesteps the issue of passing along too much+ // data (the multipart upload URLs) as request params to the desktop app.+ // There was no specific issue again, it just felt that doing everything in+ // the desktop app is more simple and straightforward (at the cost of+ // needing set up of some API request scaffolding on the desktop side).+ //+ // Below we prepare the things that we need to pass to the desktop app to+ // allow it to make the API request for obtaining pre-signed upload URLs.+ const fetchURL = await apiURL("/files/data/preview-upload-url");+ const authToken = await ensureAuthToken();++ log.info(`Generate HLS for ${fileLogID(file)} | start`);++ let res: GenerateHLSResult | undefined;+ try {+ res = await initiateGenerateHLS(+ electron,+ sourceVideo,+ file.id,+ fetchURL,+ authToken,+ );+ } catch (e) {+ // Failures during stream generation on the native side are expected to+ // happen in two cases:+ //+ // 1. There is something specific to this video that doesn't work with+ // the current HLS generation pipeline (the ffmpeg invocation).+ //+ // 2. The upload of the generated video fails.+ //+ // The native side code already retries failures for case 2 (except HTTP+ // 4xx errors). Thus, usually we should come here only for case 1, and+ // retrying the same video again will not work either.+ await markFailedVideoFile(file);+ throw e;+ }++ if (!res) {+ log.info(`Generate HLS for ${fileLogID(file)} | not-required`);+ // See: [Note: Marking files which do not need video processing]+ await updateFilePublicMagicMetadata(file, { sv: 1 });+ return;+ }++ const { playlistToken, dimensions, videoSize, videoObjectID } = res;+ try {+ const playlist = await readVideoStream(electron, playlistToken).then(+ (res) => res.text(),+ );++ const playlistData = await encodePlaylistJSON({+ type: "hls_video",+ playlist,+ ...dimensions,+ size: videoSize,+ });++ const encryptedPlaylist = await encryptBlob(playlistData, file.key);++ try {+ await putVideoData(+ file,+ encryptedPlaylist,+ videoObjectID,+ videoSize,+ );+ } catch (e) {+ if (isHTTP4xxError(e)) await markFailedVideoFile(file);+ throw e;+ }++ log.info(`Generate HLS for ${fileLogID(file)} | done`);+ } finally {+ await videoStreamDone(electron, playlistToken);+ }+};++/**+ * A semi-sibling of {@link decryptPlaylistJSON}, which does the gzip but leaves+ * the encryption up to the next layer.+ *+ * It is a trivial function, the main utility it provides is that it forces us+ * to conform to the {@link PlaylistJSON} type.+ */+const encodePlaylistJSON = (playlistJSON: PlaylistJSON) =>+ gzip(JSON.stringify(playlistJSON));diff --git a/web/apps/albums/vendor/ente-gallery/utils/avatar-colors.ts b/web/apps/albums/vendor/ente-gallery/utils/avatar-colors.tsnew file mode 100644index 0000000000..a8d672e931--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/utils/avatar-colors.ts@@ -0,0 +1,44 @@+/**+ * Avatar colors matching the mobile app's contact colors.+ *+ * These colors are used to give users a consistent colored avatar+ * based on their identifier (email or user ID).+ */+export const avatarColors = [+ "#76549A", // Purple+ "#DF7861", // Coral+ "#94B49F", // Sage green+ "#87A2FB", // Periwinkle blue+ "#C689C6", // Orchid+ "#937DC2", // Soft purple+ "#325288", // Deep blue+ "#85B4E0", // Sky blue+ "#C1A3A3", // Dusty rose+ "#E1A059", // Amber+ "#426165", // Teal+ "#6B77B2", // Slate blue+ "#957FEF", // Violet+ "#DD9DE2", // Pink+ "#82AB8B", // Forest green+ "#9BBBE8", // Light blue+ "#8FBEBE", // Seafoam+ "#8AC3A1", // Mint+ "#A8B0F2", // Lavender+ "#B0C695", // Lime green+ "#E99AAD", // Rose+ "#D18484", // Salmon+ "#78B5A7", // Cyan+];++/**+ * Get a consistent avatar color for a user based on their email or userName.+ *+ * Uses the same algorithm as the mobile app: the string length modulo the+ * number of available colors determines the color index.+ *+ * @param identifier - The user's email or userName (any string)+ * @returns A hex color string from the avatar colors palette+ */+export const getAvatarColor = (identifier: string): string => {+ return avatarColors[identifier.length % avatarColors.length]!;+};diff --git a/web/apps/albums/vendor/ente-gallery/utils/detect-type.ts b/web/apps/albums/vendor/ente-gallery/utils/detect-type.tsnew file mode 100644index 0000000000..fd6e385e41--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/utils/detect-type.ts@@ -0,0 +1,109 @@+import { lowercaseExtension } from "ente-base/file-name";+import {+ FileType,+ KnownFileTypeInfos,+ KnownNonMediaFileExtensions,+ type FileTypeInfo,+} from "ente-media/file-type";+import { fileTypeFromBuffer } from "file-type";++/**+ * Read the file's initial contents or use the file's name to detect its type.+ *+ * This is a more convenient to use abstraction over+ * {@link detectFileTypeInfoFromChunk} for use when we already have a+ * {@link File} object. See that method's documentation for more details.+ *+ * @param file A {@link File} object+ *+ * @returns The detected {@link FileTypeInfo}.+ */+export const detectFileTypeInfo = async (file: File): Promise<FileTypeInfo> =>+ detectFileTypeInfoFromChunk(() => readInitialChunkOfFile(file), file.name);++/**+ * The lower layer implementation of the type detector.+ *+ * Usually, when the code already has a {@link File} object at hand, it is+ * easier to use the higher level {@link detectFileTypeInfo} function.+ *+ * However, this lower level function is also exposed for use in cases like+ * during upload where we might not have a File object and would like to provide+ * the initial chunk of the file's contents in a different way.++ * This function first reads an initial chunk of the file and tries to detect+ * the file's {@link FileTypeInfo} from it. If that doesn't work, it then falls+ * back to using the file's name to detect it.+ *+ * If neither of these two approaches work, it throws an exception.+ *+ * If we were able to detect the file type, but it is explicitly not a media+ * (image or video) format that we support, then also this function will throw+ * an exception. Such exceptions can be identified using the+ * {@link isFileTypeNotSupportedError} predicate.+*+ * @param readInitialChunk A function to call to read the initial chunk of the+ * file's data. There is no strict requirement for the size of the chunk this+ * function should return, generally the first few KBs should be good.+ *+ * @param fileNameOrPath The full path or just the file name of the file whose+ * type we're trying to determine. This is used by the fallback layer that tries+ * to detect the type info from the file's extension.+ */+export const detectFileTypeInfoFromChunk = async (+ readInitialChunk: () => Promise<Uint8Array>,+ fileNameOrPath: string,+): Promise<FileTypeInfo> => {+ try {+ const typeResult = await detectFileTypeFromBuffer(+ await readInitialChunk(),+ );++ const mimeType = typeResult.mime;++ let fileType: FileType;+ if (mimeType.startsWith("image/")) {+ fileType = FileType.image;+ } else if (mimeType.startsWith("video/")) {+ fileType = FileType.video;+ } else {+ // This string should satisfy `isFileTypeNotSupportedError`.+ throw new Error(`Unsupported file format (MIME type ${mimeType})`);+ }++ return {+ fileType,+ // See https://github.com/sindresorhus/file-type/blob/main/core.d.ts+ // for the full list of ext values.+ extension: typeResult.ext,+ mimeType,+ };+ } catch (e) {+ const extension = lowercaseExtension(fileNameOrPath);+ const known = KnownFileTypeInfos.find((f) => f.extension == extension);+ if (known) return known;++ if (extension && KnownNonMediaFileExtensions.includes(extension)) {+ // This string should satisfy `isFileTypeNotSupportedError`.+ throw new Error(`Unsupported file format (extension ${extension})`);+ }++ throw e;+ }+};++export const isFileTypeNotSupportedError = (e: unknown) =>+ e instanceof Error && e.message.startsWith("Unsupported file format");++const readInitialChunkOfFile = async (file: File) => {+ const chunkSizeForTypeDetection = 4100;+ const chunk = file.slice(0, chunkSizeForTypeDetection);+ return new Uint8Array(await chunk.arrayBuffer());+};++const detectFileTypeFromBuffer = async (buffer: Uint8Array) => {+ const result = await fileTypeFromBuffer(buffer);+ if (!result)+ throw Error("Could not deduce file type from the file's contents");+ return result;+};diff --git a/web/apps/albums/vendor/ente-gallery/utils/file.ts b/web/apps/albums/vendor/ente-gallery/utils/file.tsnew file mode 100644index 0000000000..ec3807c265--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/utils/file.ts@@ -0,0 +1,75 @@+import type { EnteFile } from "ente-media/file";+import { fileCreationTime } 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 time of creation time of the file.+ //+ // For files with same creation time, sort based on the time of last+ // modification.+ const factor = sortAsc ? -1 : 1;+ return files.sort((a, b) => {+ const at = fileCreationTime(a);+ const bt = fileCreationTime(b);+ return at == bt+ ? factor *+ (b.metadata.modificationTime - a.metadata.modificationTime)+ : factor * (bt - at);+ });+};++/**+ * [Note: Collection file]+ *+ * File IDs themselves are unique across all the files for the user (in fact,+ * they're unique across all the files in an Ente instance).+ *+ * However, we can have multiple entries for the same file ID in our local+ * database and/or remote responses because the unit of account is not file, but+ * a "Collection File" – a collection and file pair.+ *+ * For example, if the same file is symlinked into two collections, then we will+ * have two "Collection File" entries for it, both with the same file ID, but+ * with different collection IDs.+ *+ * This function returns files such that only one of these entries is returned.+ * The entry that is returned is arbitrary in general, this function just picks+ * the first one for each unique file ID.+ *+ * If this function is invoked on a list on which {@link sortFiles} has already+ * been called, which by default sorts such that the newest file is first, then+ * this function's behaviour would be to return the newest file from among+ * multiple files with the same ID but different collections.+ */+export const uniqueFilesByID = (files: EnteFile[]) => {+ const seen = new Set<number>();+ return files.filter(({ id }) => {+ if (seen.has(id)) return false;+ seen.add(id);+ return true;+ });+};++/**+ * Segment the given {@link files} into lists indexed by their collection ID.+ *+ * Order is preserved.+ */+export const groupFilesByCollectionID = (files: EnteFile[]) =>+ files.reduce((result, file) => {+ const id = file.collectionID;+ let cfs = result.get(id);+ if (!cfs) result.set(id, (cfs = []));+ cfs.push(file);+ return result;+ }, new Map<number, EnteFile[]>());diff --git a/web/apps/albums/vendor/ente-gallery/utils/native-stream.ts b/web/apps/albums/vendor/ente-gallery/utils/native-stream.tsnew file mode 100644index 0000000000..edf8c83d66--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/utils/native-stream.ts@@ -0,0 +1,308 @@+/**+ * @file Streaming IPC communication with the Node.js layer of our desktop app.+ *+ * NOTE: These functions only work when we're running in our desktop app.+ *+ * See: [Note: IPC streams].+ */++import type { Electron, ElectronMLWorker, ZipItem } from "ente-base/types/ipc";+import { z } from "zod";+import type { FileSystemUploadItem } from "../services/upload";++/**+ * Stream the given file or zip entry from the user's local file system.+ *+ * This only works when we're running in our desktop app since it uses the+ * "stream://" protocol handler exposed by our custom code in the Node.js layer.+ * See: [Note: IPC streams].+ *+ * To avoid accidentally invoking it in a non-desktop app context, it requires+ * the {@link Electron} (or a functionally similar) object as a parameter (even+ * though it doesn't need or use it).+ *+ * @param pathOrZipItem Either the path on the file on the user's local file+ * system whose contents we want to stream. Or a tuple containing the path to a+ * zip file and the name of the entry within it.+ *+ * @return A ({@link Response}, size, lastModifiedMs) triple.+ *+ * * The response contains the contents of the file. In particular, the `body`+ * {@link ReadableStream} property of this response can be used to read the+ * files contents in a streaming manner.+ *+ * * The size is the size of the file that we'll be reading from disk.+ *+ * * The lastModifiedMs value is the last modified time of the file that we're+ * reading, expressed as epoch milliseconds.+ */+export const readStream = async (+ _: Electron | ElectronMLWorker,+ pathOrZipItem: string | ZipItem,+): Promise<{ response: Response; size: number; lastModifiedMs: number }> => {+ let url: URL;+ if (typeof pathOrZipItem == "string") {+ const params = new URLSearchParams({ path: pathOrZipItem });+ url = new URL(`stream://read?${params.toString()}`);+ } else {+ const [zipPath, entryName] = pathOrZipItem;+ const params = new URLSearchParams({ zipPath, entryName });+ url = new URL(`stream://read-zip?${params.toString()}`);+ }++ const req = new Request(url, { method: "GET" });++ const res = await fetch(req);+ if (!res.ok)+ throw new Error(+ `Failed to read stream from ${url.href}: HTTP ${res.status}`,+ );++ const size = readNumericHeader(res, "Content-Length");+ const lastModifiedMs = readNumericHeader(res, "X-Last-Modified-Ms");++ return { response: res, size, lastModifiedMs };+};++const readNumericHeader = (res: Response, key: string) => {+ const valueText = res.headers.get(key);+ const value = valueText === null ? NaN : +valueText;+ if (isNaN(value))+ throw new Error(+ `Expected a numeric ${key} when reading a stream response, instead got ${valueText}`,+ );+ return value;+};++/**+ * Write the given stream to a file on the local machine.+ *+ * This only works when we're running in our desktop app since it uses the+ * "stream://" protocol handler exposed by our custom code in the Node.js layer.+ * See: [Note: IPC streams].+ *+ * To avoid accidentally invoking it in a non-desktop app context, it requires+ * the {@link Electron} object as a parameter (even though it doesn't use it).+ *+ * @param path The path on the local machine where to write the file to.+ *+ * @param stream The stream which should be written into the file.+ */+export const writeStream = async (+ _: Electron,+ path: string,+ stream: ReadableStream | null,+) => {+ const params = new URLSearchParams({ path });+ const url = new URL(`stream://write?${params.toString()}`);++ // The duplex parameter needs to be set to 'half' when streaming requests.+ //+ // Currently browsers, and specifically in our case, since this code runs+ // only within our desktop (Electron) app, Chromium, don't support 'full'+ // duplex mode (i.e. streaming both the request and the response).+ // https://developer.chrome.com/docs/capabilities/web-apis/fetch-streaming-requests+ const req = new Request(url, {+ // GET can't have a body+ method: "POST",+ // [Note: duplex param required for stream body]+ //+ // The duplex parameter needs to be set to 'half' when streaming+ // requests. However, TypeScript's libdom.d.ts does not include the+ // "duplex" parameter, so we need to silence the tsc error. e.g. see+ // https://github.com/node-fetch/node-fetch/issues/1769.+ //+ // @ts-expect-error See: [Note: duplex param required for stream body]+ duplex: "half",+ body: stream,+ });++ const res = await fetch(req);+ if (!res.ok)+ throw new Error(+ `Failed to write stream to ${url.href}: HTTP ${res.status}`,+ );+};++/**+ * Initate a conversion to MP4, streaming the video contents to the node side.+ *+ * This is a variant of {@link writeStream} tailored for the conversion to MP4.+ *+ * @param _ An {@link Electron} instance, witness to the fact that we're running+ * in the context of the desktop app. It is otherwise not used.+ *+ * @param video A {@link Blob} containing the video to convert.+ *+ * @returns a token that can then be passed to {@link readVideoStream} to+ * retrieve the converted MP4 file. This three step sequence (write/read/done)+ * can then be ended by using {@link videoStreamDone}).+ *+ * See: [Note: Convert to MP4].+ */+export const initiateConvertToMP4 = async (+ _: Electron,+ video: Blob,+): Promise<string> => {+ const url = "stream://video?op=convert-to-mp4";+ const res = await fetch(url, { method: "POST", body: video });+ if (!res.ok)+ throw new Error(`Failed to write stream to ${url}: HTTP ${res.status}`);+ return res.text();+};++const GenerateHLSResult = z.object({+ /**+ * A token that can be used to passed to {@link readVideoStream} to retrieve+ * the generated HLS playlist.+ */+ playlistToken: z.string(),+ /**+ * The dimensions (width and height in pixels) of the generated video stream.+ */+ dimensions: z.object({ width: z.number(), height: z.number() }),+ /**+ * The size (in bytes) of the file containing the encrypted video segments.+ */+ videoSize: z.number(),+ /**+ * The ID of the uploaded encrypted video segment file on the remote bucket.+ */+ videoObjectID: z.string(),+});++export type GenerateHLSResult = z.infer<typeof GenerateHLSResult>;++/**+ * Initate the generation of a HLS stream, streaming the source video contents+ * to the node side.+ *+ * This is a variant of {@link writeStream} tailored for the HLS generation. It+ * is similar to {@link initiateConvertToMP4}, but also supports streaming+ * {@link FileSystemUploadItem}s and {@link ReadableStream}s.+ *+ * @param _ An {@link Electron} instance, witness to the fact that we're running+ * in the context of the desktop app. It is otherwise not used.+ *+ * @param video The video to convert.+ *+ * - If we're called during the upload process, then this will be set to the+ * {@link FileSystemUploadItem} that was uploaded. This way, we can directly+ * use the on-disk file instead of needing to download the original from+ * remote.+ *+ * - Otherwise it should be a {@link ReadableStream} of the video contents.+ *+ * @param fileID The ID of the {@link EnteFile} for which we're generating the+ * HLS.+ *+ * @param fetchURL The fully resolved API URL for obtaining the pre-signed URLs+ * to which the video segment file should be uploaded.+ *+ * @param authToken The user's auth token (for making the request to+ * {@link fetchURL}).+ *+ * @returns a token that can be used to retrieve the generated HLS playlist, and+ * metadata about the generated video (See {@link GenerateHLSResult}).+ *+ * In case the video is such that it doesn't require a separate stream to be+ * generated (e.g. it is a small video using an already compatible codec), then+ * this function will return `undefined`.+ *+ * See: [Note: Preview variant of videos].+ */+export const initiateGenerateHLS = async (+ _: Electron,+ video: FileSystemUploadItem | ReadableStream,+ fileID: number,+ fetchURL: string,+ authToken: string,+): Promise<GenerateHLSResult | undefined> => {+ const params = new URLSearchParams({+ op: "generate-hls",+ fileID: fileID.toString(),+ fetchURL,+ authToken,+ });++ let body: ReadableStream | null;+ if (video instanceof ReadableStream) {+ body = video;+ } else {+ // video is a DesktopUploadItem+ body = null;+ if (typeof video == "string") {+ // Path to a regular file on the user's file system.+ params.set("path", video);+ } else if (Array.isArray(video)) {+ // Path within a zip file on the user's file system.+ const [zipPath, entryName] = video;+ params.set("zipPath", zipPath);+ params.set("entryName", entryName);+ } else {+ // A File with a path. Use the path.+ params.set("path", video.path);+ }+ }++ const url = `stream://video?${params.toString()}`;+ const res = await fetch(url, {+ method: "POST",+ // @ts-expect-error See: [Note: duplex param required for stream body]+ duplex: "half",+ body,+ });+ if (!res.ok)+ throw new Error(`Failed to write stream to ${url}: HTTP ${res.status}`);++ if (res.status == 204) return undefined;++ return GenerateHLSResult.parse(await res.json());+};++/**+ * Variant of {@link readStream} tailored for video conversion.+ *+ * @param token A token obtained from a video conversion operation like+ * {@link initiateConvertToMP4} or {@link initiateGenerateHLS}.+ *+ * @returns a Response that contains the data associated with the provided+ * token.+ */+export const readVideoStream = async (+ _: Electron,+ token: string,+): Promise<Response> => {+ const params = new URLSearchParams({ token });+ const url = new URL(`stream://video?${params.toString()}`);++ const req = new Request(url, { method: "GET" });++ const res = await fetch(req);+ if (!res.ok)+ throw new Error(+ `Failed to read stream from ${url.href}: HTTP ${res.status}`,+ );++ return res;+};++/**+ * Sibling of {@link readVideoStream} to let the native side know when we are+ * done reading the response, so it can dispose any temporary resources.+ */+export const videoStreamDone = async (+ _: Electron,+ token: string,+): Promise<void> => {+ // The value for `done` is arbitrary, only its presence matters.+ const params = new URLSearchParams({ token, done: "1" });+ const url = new URL(`stream://video?${params.toString()}`);++ const req = new Request(url, { method: "GET" });+ const res = await fetch(req);+ if (!res.ok)+ throw new Error(+ `Failed to close stream at ${url.href}: HTTP ${res.status}`,+ );+};diff --git a/web/apps/albums/vendor/ente-gallery/utils/native-worker.ts b/web/apps/albums/vendor/ente-gallery/utils/native-worker.tsnew file mode 100644index 0000000000..e168ac4bbe--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/utils/native-worker.ts@@ -0,0 +1,33 @@+import type { Electron, UtilityProcessType } from "ente-base/types/ipc";++/**+ * Obtain a port from the Node.js layer that can be used to communicate with the+ * native utility process of type {@link type}.+ */+export const createUtilityProcess = (+ electron: Electron,+ type: UtilityProcessType,+): Promise<MessagePort> => {+ // The main process will do its thing, and send back the port it created to+ // us by sending an message on the "utilityProcessPort/<type>" channel via+ // the postMessage API. This roundabout way is needed because MessagePorts+ // cannot be transferred via the usual send/invoke pattern.++ const portEvent = `utilityProcessPort/${type}`;++ const port = new Promise<MessagePort>((resolve) => {+ const l = ({ source, data, ports }: MessageEvent) => {+ // The source check verifies that the message is coming from our own+ // preload script. The data is the message that was posted.+ if (source == window && data == portEvent) {+ window.removeEventListener("message", l);+ resolve(ports[0]!);+ }+ };+ window.addEventListener("message", l);+ });++ electron.triggerCreateUtilityProcess(type);++ return port;+};diff --git a/web/apps/albums/vendor/ente-gallery/utils/units.ts b/web/apps/albums/vendor/ente-gallery/utils/units.tsnew file mode 100644index 0000000000..229ec2ab9d--- /dev/null+++ b/web/apps/albums/vendor/ente-gallery/utils/units.ts@@ -0,0 +1,100 @@+import { t } from "i18next";++/**+ * Localized unit keys.+ *+ * For each of these, there is expected to be a localized key under+ * "storage_unit". e.g. "storage_unit.tb".+ */+const units = ["b", "kb", "mb", "gb", "tb"];++/**+ * Convert the given number of {@link bytes} to their equivalent GB string with+ * {@link precision}.+ *+ * The returned string does not have the GB suffix.+ */+export const bytesInGB = (bytes: number, precision = 0): string =>+ (bytes / (1024 * 1024 * 1024)).toFixed(precision);++/**+ * Convert the given number of {@link bytes} to a user visible string in an+ * appropriately sized unit.+ *+ * The returned string includes the (localized) unit suffix, e.g. "TB".+ *+ * @param precision Modify the number of digits after the decimal point.+ * Defaults to 2.+ */+export function formattedByteSize(bytes: number, precision = 2): string {+ if (bytes <= 0) return `0 ${t("storage_unit.mb")}`;++ const i = Math.min(+ Math.floor(Math.log(bytes) / Math.log(1024)),+ units.length - 1,+ );+ const quantity = bytes / Math.pow(1024, i);+ const unit = units[i];++ return `${quantity.toFixed(precision)} ${t(`storage_unit.${unit}`)}`;+}++interface FormattedStorageByteSizeOptions {+ /**+ * If `true` then round up the fractional quantity we obtain when dividing+ * the number of bytes by the number of bytes in the unit that got chosen.+ *+ * The default behaviour is to take the ceiling.+ */+ round?: boolean;+}++/**+ * Convert the given number of storage {@link bytes} to a user visible string in+ * an appropriately sized unit.+ *+ * This differs from {@link formattedByteSize} in that while+ * {@link formattedByteSize} is meant for arbitrary byte sizes, this function+ * has a few additional beautification heuristics that we want to apply when+ * displaying the "storage size" (in different contexts) as opposed to, say, a+ * generic "file size".+ *+ * @param options {@link FormattedStorageByteSizeOptions}.+ *+ * @return A user visible string, including the localized unit suffix.+ */+export const formattedStorageByteSize = (+ bytes: number,+ options?: FormattedStorageByteSizeOptions,+): string => {+ if (bytes <= 0) return `0 ${t("storage_unit.mb")}`;++ const i = Math.min(+ Math.floor(Math.log(bytes) / Math.log(1024)),+ units.length - 1,+ );++ let quantity = bytes / Math.pow(1024, i);+ let unit = units[i];++ // Round up bytes, KBs and MBs to the bigger unit whenever they'll come of+ // as more than 0.1.+ if (quantity > 100 && i < units.length - 2) {+ quantity /= 1024;+ unit = units[i + 1];+ }++ quantity = Number(quantity.toFixed(1));++ // Truncate or round storage sizes to trim off unnecessary and potentially+ // obscuring precision when they are larger that 10 GB.+ if (bytes >= 10 * 1024 * 1024 * 1024 /* 10 GB */) {+ if (options?.round) {+ quantity = Math.ceil(quantity);+ } else {+ quantity = Math.round(quantity);+ }+ }++ return `${quantity} ${t(`storage_unit.${unit}`)}`;+};diff --git a/web/apps/albums/vendor/ente-media/collection.ts b/web/apps/albums/vendor/ente-media/collection.tsnew file mode 100644index 0000000000..d3cc500ae1--- /dev/null+++ b/web/apps/albums/vendor/ente-media/collection.ts@@ -0,0 +1,741 @@+import { decryptBoxBytes } from "ente-base/crypto";+import {+ nullishToEmpty,+ nullishToFalse,+ nullToUndefined,+} from "ente-utils/transform";+import { z } from "zod";+import {+ decryptMagicMetadata,+ RemoteMagicMetadata,+ type MagicMetadata,+} from "./magic-metadata";++/**+ * A collection, as used and persisted locally by the client.+ *+ * A collection is, well, a collection of files. It is roughly equivalent to an+ * "album" (which is also the term we use in the UI), but there can also be+ * special type of collections like "favorites" which have special behaviour.+ *+ * A collection contains zero or more files ({@link EnteFile}).+ *+ * A collection can be owned by the user (in whose context this code is+ * running), or might be a collection that is shared with them.+ */+export interface Collection {+ /**+ * The collection's globally unique ID.+ *+ * The collection's ID is a integer assigned by remote as the identifier for+ * an {@link Collection} when it is created. It is globally unique across+ * all collections on an Ente instance (i.e., it is not scoped to a user).+ */+ id: number;+ /**+ * Information about the user who owns the collection.+ *+ * Each collection is owned by exactly one user. The owner may optionally+ * choose to share it with additional users, granting them varying level of+ * privileges.+ *+ * Within the {@link CollectionUser} instance of the {@link owner} field:+ *+ * - {@link email} will be set only if this is a shared collection that does+ * not belong to the current user.+ * - {@link role} will be blank.+ */+ owner: CollectionUser;+ /**+ * The "collection key" (base64 encoded).+ *+ * The collection key is used to encrypt and decrypt that files that are+ * associated with the collection. See: [Note: Collection file].+ */+ key: string;+ /**+ * The name of the collection.+ */+ name: string;+ /**+ * The type of the collection.+ *+ * Expected to be one of {@link CollectionType}.+ */+ type: string;+ /**+ * The other Ente users with whom the collection has been shared with.+ *+ * Within the {@link CollectionUser} instances of the {@link sharee} field:+ *+ * - {@link email} will be set.+ * - {@link role} is expected to be one of "VIEWER" or "COLLABORATOR".+ */+ sharees: CollectionUser[];+ /**+ * Public links that can be used to access and update the collection.+ */+ publicURLs: PublicURL[];+ /**+ * The last time the collection was updated (epoch microseconds).+ *+ * The collection is considered updated both+ *+ * - When the files associated with it modified (added, removed); and+ * - When the collection's own fields are modified.+ */+ updationTime: number;+ /**+ * Private mutable metadata associated with the collection that is only+ * visible to the owner of the collection.+ *+ * See: [Note: Metadatum]+ */+ magicMetadata?: MagicMetadata<CollectionPrivateMagicMetadataData>;+ /**+ * Public mutable metadata associated with the collection that is visible to+ * all users with whom the collection has been shared.+ *+ * See: [Note: Metadatum]+ */+ pubMagicMetadata?: MagicMetadata<CollectionPublicMagicMetadataData>;+ /**+ * Private mutable metadata associated with the collection that is only+ * visible to the current user if they're not the owner of the collection.+ *+ * Sometimes also referred to as "shareeMagicMetadata".+ *+ * This is metadata associated with each "share", and is only visible to+ * (and editable by) the user with which the collection has been shared, not+ * the owner. Each user with whom the collection has been shared gets their+ * own private copy. This allows each user to keep their own metadata+ * associated with a shared album (e.g. archive status).+ *+ * See: [Note: Metadatum]+ */+ sharedMagicMetadata?: MagicMetadata<CollectionShareeMagicMetadataData>;+}++/**+ * The known set of values for the {@link type} field of a {@link Collection}.+ *+ * This is the list of values, see {@link CollectionType} for the corresponding+ * TypeScript type.+ */+export const collectionTypes = [+ "album",+ "folder",+ "favorites",+ "uncategorized",+] as const;++/**+ * The type of a collection.+ *+ * - "album" - A regular "Ente Album" that the user sees in their library.+ *+ * - "folder" - An Ente Album that is also associated with an OS album on the+ * user's mobile device.+ *+ * A collection of type "folder" is created by the mobile app if there is an+ * associated on-device album for the new Ente album being created.+ *+ * This separation between "album" and "folder" allows different mobile+ * clients to push to the same Folder ("Camera", "Screenshots"), not allowing+ * for duplicate folders with the same name, while still allowing users to+ * create different albums with the same name.+ *+ * The web/desktop app does not create collections of type "folder", and+ * otherwise treats them as aliases for "album".+ *+ * - "favorites" - A special collection consisting of the items that the user+ * has marked as their favorites.+ *+ * The user can have at most one collection of type "favorites" (enforced at+ * remote). This collection is created on demand by the client where the user+ * first marks an item as a favorite. The user can choose to share their+ * "favorites" with other users, so it is possible for there to be multiple+ * collections of type "favorites" present in our local database, however only+ * one of those will belong to the logged in user (cf `owner.id`).+ *+ * - "uncategorized" - A special collection consisting of items that do not+ * belong to any other collection.+ *+ * In the remote schema, each item ({@link EnteFile}) is always associated+ * with a collection. The same item may belong to multiple collections (See:+ * [Note: Collection file]), but it must belong to at least one collection.+ *+ * In some scenarios, e.g. when deleting the last collection to which a file+ * belongs, the file would thus get orphaned and violate the schema+ * invariants. So in such cases, the client which is performing the+ * corresponding operation moves the file to the user's special+ * "uncategorized" collection, creating it if needed.+ *+ * Similar to "favorites", the user can have only one "uncategorized"+ * collection. However, unlike "favorites", the "uncategorized" collection+ * cannot be shared.+ */+export type CollectionType = (typeof collectionTypes)[number];++/**+ * The privilege level of a participant associated with a collection.+ *+ * - "VIEWER" - Has read-only access to files in the collection.+ *+ * - "COLLABORATOR" - Can additionally add files from the collection, and remove+ * files that they added from the collection (i.e., files they "own").+ *+ * - "ADMIN" - Can manage participants (invite/remove) similar to the owner, but+ * cannot delete the collection or remove the owner.+ *+ * - "OWNER" - The owner of the collection. Can remove any file, including those+ * added by other users, from the collection.+ *+ * It is guaranteed that a there will be exactly one participant of type OWNER,+ * and their user ID will be the same as the collection `owner.id`.+ */+export type CollectionParticipantRole =+ | "VIEWER"+ | "COLLABORATOR"+ | "ADMIN"+ | "OWNER"+ | "UNKNOWN";++/**+ * A subset of {@link CollectionParticipantRole} that are applicable when+ * sharing a collection with another Ente user.+ */+export type CollectionNewParticipantRole = "VIEWER" | "COLLABORATOR" | "ADMIN";++/**+ * Information about the user associated with a collection, either as an owner,+ * or as someone with whom the collection has been shared with.+ */+export interface CollectionUser {+ /**+ * The ID of the underlying {@link User} that this {@link CollectionUser}+ * stands for.+ */+ id: number;+ /**+ * The email of the user.+ *+ * - The email is present for the {@link owner} only for shared collections+ * that do not belong to the current user.+ * - The email is present for all {@link sharees}.+ * - Remote uses a blank string to indicate absent values.+ */+ email?: string;+ /**+ * The association / privilege level of the user with the collection.+ *+ * Expected to be one of {@link CollectionParticipantRole}.+ *+ * - The role is not present (blank string) for the {@link owner}.+ * - The role is present, and one of "VIEWER" and "COLLABORATOR" for the+ * {@link sharees}.+ * - Remote uses a blank string to indicate absent values.+ */+ role?: string;+}++/**+ * Zod schema for {@link CollectionUser}.+ *+ * [Note: Enums in remote objects]+ *+ * In some cases remote returns a value which is part of a known set. The+ * underlying type might be an integer or a string.+ *+ * While Zod allows us to validate enum types during a parse, we refrain from+ * doing this as this would cause existing clients to break if remote were to in+ * the future add new enum cases.+ *+ * This is especially pertinent for objects which we might persist locally,+ * since the client code which persists the object might not know about a+ * particular enum case but a future client which reads the saved value might.+ *+ * So we keep the underlying data type (string or number) as it is instead of+ * converting / validating to an enum or discarding unknown values.+ *+ * As an example consider the {@link role} item in {@link RemoteCollectionUser}.+ * There is a known set of values ({@link CollectionParticipantRole}) this can+ * be, but in the Zod schema we keep the data type as a string.+ */+export const RemoteCollectionUser = z.looseObject({+ id: z.number(),+ email: z.string().nullish().transform(nullToUndefined),+ role: z.string().nullish().transform(nullToUndefined),+});++type RemoteCollectionUser = z.infer<typeof RemoteCollectionUser>;++/**+ * A public link for a shared collection.+ *+ * This structure contains a (partial^) URL that can be used to access the+ * shared collection, along with other attributes of the link.+ *+ * ^ The URL is partial because it doesn't have the URL fragment, which is+ * client side only as it contains the decryption key+ */+export interface PublicURL {+ /**+ * A URL that can be used access the shared collection.+ *+ * This will be of the form "https://<public-albums-app>/?t=<token>", e.g.,+ * "https://albums.ente.io/?t=xxxxxx".+ *+ * In particular, this URL does not contain the URL fragment (the part after+ * the "#"). URL fragments are client side only, and not sent to remote.+ * They contain the decryption key.+ *+ * The client can use this field to form the fully usable URL (e.g.+ * "https://albums.ente.io/?t=xxxxxx#yyy...yyy") and provide it to the user+ * for sharing.+ */+ url: string;+ /**+ * The number of unique devices which can access the collection using the+ * public URL.+ *+ * Set to 0 to indicate no device limit.+ */+ deviceLimit: number;+ /**+ * The epoch microseconds until which the link is valid.+ *+ * Set to 0 to indicate no expiry.+ */+ validTill: number;+ /**+ * `true` if downloads are enabled from this link.+ *+ * When creating a new link this is `true` by default, and can optionally be+ * disabled in the public link settings.+ */+ enableDownload: boolean;+ enableJoin: boolean;+ /**+ * `true` if people can use the public link to upload new files to the+ * shared collection.+ */+ enableCollect: boolean;+ /**+ * `true` if comments are enabled on this public link.+ */+ enableComment: boolean;+ /**+ * `true` if the link is password protected.+ *+ * When this is `true`, {@link nonce}, {@link memLimit} and {@link opsLimit}+ * will also be set.+ */+ passwordEnabled: boolean;+ /**+ * The nonce to use when hashing the password.+ *+ * Only present when {@link passwordEnabled} is `true`.+ */+ nonce?: string;+ /**+ * The ops limit to use when hashing the password.+ *+ * Only present when {@link passwordEnabled} is `true`.+ */+ opsLimit?: number;+ /**+ * The mem limit to use when hashing the password.+ *+ * Only present when {@link passwordEnabled} is `true`.+ */+ memLimit?: number;+}++/**+ * Zod schema for the {@link PublicURL} we use in our interactions with remote.+ *+ * We also use the same schema when persisting the collection locally.+ */+export const RemotePublicURL = z.looseObject({+ url: z.string(),+ deviceLimit: z.number(),+ validTill: z.number(),+ enableDownload: z.boolean().nullish().transform(nullishToFalse),+ enableJoin: z.boolean().nullish().transform(nullishToFalse),+ enableCollect: z.boolean().nullish().transform(nullishToFalse),+ enableComment: z.boolean().nullish().transform(nullishToFalse),+ passwordEnabled: z.boolean().nullish().transform(nullishToFalse),+ nonce: z.string().nullish().transform(nullToUndefined),+ memLimit: z.number().nullish().transform(nullToUndefined),+ opsLimit: z.number().nullish().transform(nullToUndefined),+});++/**+ * Zod schema for {@link Collection}.+ *+ * [Note: Use looseObject when parsing JSON that will get persisted]+ *+ * While not always necessary, for a few cases (files and collections being the+ * most prominent and important) we try to retain any unknown fields in the JSON+ * we get from remote, so that future versions of the client with support for+ * fields unbeknownst to the current one can read and use them.+ *+ * In such cases, the nested objects should also (recursively) use the+ * looseObject schema. But not always - in some cases where the structures we+ * use are well established, e.g. {@link RemoteMagicMetadata} - we use the+ * default Zod behaviour of discarding unknown fields.+ *+ * > Note that even in the case of {@link RemoteMagicMetadata}, we still apply+ * > looseObject to the payload itself.+ * >+ * > See: [Note: Use looseObject for metadata Zod schemas]+ *+ * Unlike metadata, where we do strictly want to retain unknown or unacted on+ * fields, in the more general case we are okay with being a bit loose with+ * looseObject, and even intentionally dropping fields that we know we're not+ * going to use on the current client. Such looseness is okay because even if we+ * need to use them in the future, we can always refetch the objects again+ * (while in the case of metadata, we need to also push our changes to remote,+ * so it is functionally important for us to retain the source verbatim).+ */+export const RemoteCollection = z.looseObject({+ id: z.number(),+ owner: RemoteCollectionUser,+ encryptedKey: z.string(),+ /**+ * The nonce to use when decrypting the {@link encryptedKey} when the album+ * is owned by the user.+ *+ * Not set for shared albums (the decryption for uses the keypair instead).+ *+ * Remote might set this to blank to indicate absence.+ */+ keyDecryptionNonce: z.string().nullish().transform(nullToUndefined),+ /**+ * Expected to be present (along with {@link nameDecryptionNonce}), but it+ * is still optional since it might not be present if {@link name} is present.+ */+ encryptedName: z.string().nullish().transform(nullToUndefined),+ nameDecryptionNonce: z.string().nullish().transform(nullToUndefined),+ /**+ * Not used anymore, but still might be present for very old collections.+ *+ * Before public launch, collection names were stored unencrypted. For+ * backward compatibility, client should use {@link name} if present,+ * otherwise obtain it by decrypting it from {@link encryptedName} and+ * {@link nameDecryptionNonce}.+ */+ name: z.string().nullish().transform(nullToUndefined),+ /**+ * Expected to be one of {@link CollectionType}+ */+ type: z.string(),+ sharees: z.array(RemoteCollectionUser).nullish().transform(nullishToEmpty),+ publicURLs: z.array(RemotePublicURL).nullish().transform(nullishToEmpty),+ updationTime: z.number(),+ /**+ * Tombstone marker.+ *+ * This is set to `true` in the collection fetch response to indicate+ * collections which have been deleted on remote and should thus be pruned+ * by the client locally.+ */+ isDeleted: z.boolean().nullish().transform(nullToUndefined),+ magicMetadata: RemoteMagicMetadata.nullish().transform(nullToUndefined),+ pubMagicMetadata: RemoteMagicMetadata.nullish().transform(nullToUndefined),+ sharedMagicMetadata:+ RemoteMagicMetadata.nullish().transform(nullToUndefined),+});++export type RemoteCollection = z.infer<typeof RemoteCollection>;++/**+ * Decrypt a remote collection using the provided {@link collectionKey}.+ *+ * @param collection The remote collection to decrypt.+ *+ * @param collectionKey The base64 encoded key to use for decrypting the various+ * encrypted fields in {@link collection}.+ *+ * @returns A decrypted collection.+ */+export const decryptRemoteCollection = async (+ collection: RemoteCollection,+ collectionKey: string,+): Promise<Collection> => {+ // RemoteCollection is a looseObject, and we want to retain that semantic+ // for the parsed Collection. Mention all fields that we want to explicitly+ // drop or transform, passthrough the rest unchanged in the return value.+ //+ // See: [Note: Use looseObject when parsing JSON that will get persisted].+ const {+ owner,+ encryptedKey,+ keyDecryptionNonce,+ encryptedName,+ nameDecryptionNonce,+ sharees,+ attributes,+ isDeleted,+ magicMetadata: encryptedMagicMetadata,+ pubMagicMetadata: encryptedPubMagicMetadata,+ sharedMagicMetadata: encryptedSharedMagicMetadata,+ ...rest+ } = collection;++ // We've already used them to derive the `collectionKey`.+ ignore([encryptedKey, keyDecryptionNonce]);+ // Mobile specific attribute not currently used by us.+ ignore(attributes);+ // The deleted flag is used during collection fetch, but not used by us+ // beyond this point.+ ignore(isDeleted);++ const name =+ // `||` is used because remote sets name to blank to indicate absence.+ collection.name ||+ new TextDecoder().decode(+ await decryptBoxBytes(+ { encryptedData: encryptedName!, nonce: nameDecryptionNonce! },+ collectionKey,+ ),+ );++ let magicMetadata: Collection["magicMetadata"];+ if (encryptedMagicMetadata) {+ const genericMM = await decryptMagicMetadata(+ encryptedMagicMetadata,+ collectionKey,+ );+ const data = CollectionPrivateMagicMetadataData.parse(genericMM.data);+ magicMetadata = { ...genericMM, data };+ }++ let pubMagicMetadata: Collection["pubMagicMetadata"];+ if (encryptedPubMagicMetadata) {+ const genericMM = await decryptMagicMetadata(+ encryptedPubMagicMetadata,+ collectionKey,+ );+ const data = CollectionPublicMagicMetadataData.parse(genericMM.data);+ pubMagicMetadata = { ...genericMM, data };+ }++ let sharedMagicMetadata: Collection["sharedMagicMetadata"];+ if (encryptedSharedMagicMetadata) {+ const genericMM = await decryptMagicMetadata(+ encryptedSharedMagicMetadata,+ collectionKey,+ );+ const data = CollectionShareeMagicMetadataData.parse(genericMM.data);+ sharedMagicMetadata = { ...genericMM, data };+ }++ return {+ ...rest,+ key: collectionKey,+ owner: parseRemoteCollectionUser(owner),+ name,+ sharees: sharees.map(parseRemoteCollectionUser),+ publicURLs: rest.publicURLs,+ magicMetadata,+ pubMagicMetadata,+ sharedMagicMetadata,+ };+};++/**+ * A no-op function to pretend that we're using some values. This is handy when+ * we want to destructure some fields so that they don't get forwarded, but+ * otherwise don't need to use them.+ */+export const ignore = (xs: unknown) => typeof xs;++/**+ * A convenience function to discard the unused name field from the collection+ * user objects that we receive from remote.+ */+const parseRemoteCollectionUser = ({+ name,+ ...rest+}: RemoteCollectionUser): CollectionUser => {+ ignore(name);+ return rest;+};++/**+ * Additional context stored as part of the collection's magic metadata to+ * augment the {@link type} associated with a {@link Collection}.+ */+export const CollectionSubType = {+ /**+ * The default / normal value. No special semantics.+ */+ default: 0,+ /**+ * The user's default hidden collection, which contains the individually+ * hidden files.+ */+ defaultHidden: 1,+ /**+ * A collection created for sharing selected files.+ */+ quicklink: 2,+} as const;++export type CollectionSubType =+ (typeof CollectionSubType)[keyof typeof CollectionSubType];++/**+ * Ordering of the collection - Whether it is pinned or not.+ */+export const CollectionOrder = {+ /**+ * The default / normal value. No special semantics, behaves "unpinned" and+ * will retain its natural sort position.+ */+ default: 0,+ /**+ * The collection is "pinned" by moving to the beginning of the sort order.+ *+ * Multiple collections can be pinned, in which case they'll be sorted+ * amongst themselves under the otherwise applicable sort order.+ *+ * -- [pinned collections] -- [other collections] --+ */+ pinned: 1,+} as const;++export type CollectionOrder =+ (typeof CollectionOrder)[keyof typeof CollectionOrder];++/**+ * Mutable private metadata associated with a {@link Collection}.+ *+ * - Unlike {@link CollectionPublicMagicMetadataData} this is only available to+ * the owner of the file.+ *+ * See: [Note: Private magic metadata is called magic metadata on remote]+ */+export interface CollectionPrivateMagicMetadataData {+ /**+ * The subtype of the collection type (if applicable).+ *+ * Expected to be one of {@link CollectionSubType}.+ */+ subType?: number;+ /**+ * The (owner specific) visibility of the collection.+ *+ * The file's visibility is user specific attribute, and thus we keep it in+ * the private magic metadata. This allows the file's owner to share a file+ * and independently edit its visibility without revealing their visibility+ * preference to the other people with whom they have shared the file.+ *+ * Expected to be one of {@link ItemVisibility}.+ *+ * See: [Note: Enums in remote objects] for why we keep it as a number+ * instead of the expected enum.+ */+ visibility?: number;+ /**+ * An overrride to the sort ordering used for the collection.+ *+ * Expected to be one of {@link CollectionOrder}.+ */+ order?: number;+}++/**+ * Zod schema for {@link CollectionPrivateMagicMetadataData}.+ *+ * See: [Note: Use looseObject for metadata Zod schemas]+ */+export const CollectionPrivateMagicMetadataData = z.looseObject({+ subType: z.number().nullish().transform(nullToUndefined),+ visibility: z.number().nullish().transform(nullToUndefined),+ order: z.number().nullish().transform(nullToUndefined),+});++/**+ * Mutable public metadata associated with a {@link Collection}.+ *+ * - Unlike {@link CollectionPrivateMagicMetadataData}, this is available to all+ * people with whom the collection has been shared.+ *+ * For more details, see [Note: Metadatum].+ */+export interface CollectionPublicMagicMetadataData {+ /**+ * The ordering of the files within the collection.+ *+ * The default is desc ("Newest first").+ *+ * If true, then the files within the collection are sorted in ascending+ * order of their time ("Oldest first").+ *+ * To reset to the default, set this to false.+ */+ asc?: boolean;+ /**+ * The file ID of the file to use as the cover for the collection.+ *+ * To reset to the default cover, set this to 0.+ */+ coverID?: number;+ /**+ * The layout type for the public collection display.+ *+ * Expected to be one of: "masonry", "grouped", "continuous", "trip".+ */+ layout?: string;+}++/**+ * Zod schema for {@link CollectionPublicMagicMetadataData}.+ */+export const CollectionPublicMagicMetadataData = z.looseObject({+ asc: z.boolean().nullish().transform(nullToUndefined),+ coverID: z.number().nullish().transform(nullToUndefined),+ layout: z.string().nullish().transform(nullToUndefined),+});++/**+ * Per-sharee mutable metadata associated with a shared {@link Collection}.+ *+ * [Note: Share specific metadata]+ *+ * When a collection is shared with a particular user, then remote creates a new+ * "share" entity defined by the (collectionID, fromUserID, toUserID) tuple+ * (this entity is not exposed to us directly, but it is helpful to know the+ * underlying implementation for this discussion).+ *+ * Remote also allows us to store mutable metadata (aka "magic metadata") with+ * each such share entity. This effectively acts as a private space where each+ * user with whom a collection has been shared can store and mutate metadata+ * about this shared collection without affecting either the owner or other+ * users with whom the collection has been shared.+ */+export interface CollectionShareeMagicMetadataData {+ /**+ * The (sharee specific) visibility of the collection.+ *+ * Expected to be one of {@link ItemVisibility}.+ */+ visibility?: number;+ /**+ * An override to the sort ordering used for the collection by the sharee.+ *+ * Expected to be one of {@link CollectionOrder}.+ */+ order?: number;+}++/**+ * Zod schema for {@link CollectionShareeMagicMetadataData}.+ */+export const CollectionShareeMagicMetadataData = z.looseObject({+ visibility: z.number().nullish().transform(nullToUndefined),+ order: z.number().nullish().transform(nullToUndefined),+});diff --git a/web/apps/albums/vendor/ente-media/file-metadata.ts b/web/apps/albums/vendor/ente-media/file-metadata.tsnew file mode 100644index 0000000000..68968317fa--- /dev/null+++ b/web/apps/albums/vendor/ente-media/file-metadata.ts@@ -0,0 +1,839 @@+import { type Location } from "ente-base/types";+import { type EnteFile } from "ente-media/file";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";+import { FileType } from "./file-type";++/**+ * Information about the file that never changes post upload.+ *+ * ---+ *+ * [Note: Metadatum]+ *+ * There are three different sources of metadata relating to a file.+ *+ * 1. Metadata+ * 2. Magic metadata+ * 3. Public magic metadata+ *+ * The names of API entities are such for historical reasons, but we can think+ * of them as:+ *+ * 1. Metadata+ * 2. Private mutable metadata+ * 3. Public mutable metadata+ *+ * Metadata is the original metadata that we attached to the file when it was+ * uploaded. It is immutable, and it never changes.+ *+ * Later on, the user might make changes to the file's metadata. Since the+ * metadata is immutable, we need a place to keep these mutations.+ *+ * Some mutations are "private" to the user who owns the file. For example, the+ * user might archive the file. Such modifications get written to (2), Private+ * Mutable Metadata.+ *+ * Other mutations are "public" across all the users with whom the file is+ * shared. For example, if the user (owner) edits the name of the file, all+ * people with whom this file is shared can see the new edited name. Such+ * modifications get written to (3), Shared Mutable Metadata.+ *+ * When the client needs to show a file, it needs to "merge" in two or three of+ * these sources (nb: remote will only send the permissible ones):+ *+ * - When showing a shared file, (1) and (3) are merged, with changes from (3)+ * taking precedence, to obtain the full metadata pertinent to the file.+ *+ * - When showing a normal (un-shared) file, (1), (2) and (3) are merged, with+ * changes from (2) and (3) taking precedence, to obtain the full metadata.+ * (2) and (3) have no intersection of keys, so they can be merged in any+ * order.+ *+ * While these sources can be conceptually merged, it is important for the+ * client to also retain the original sources unchanged. This is because the+ * metadatas (any of the three) might have keys that the current client does not+ * yet understand, so when updating some key, say filename in (3), it should+ * only edit the key it knows about but retain the rest of the source JSON+ * unchanged.+ *+ * A similar concept applies to collections, which can (like files) have+ * metadata associated with them with varying axis of mutability and access.+ *+ * Collections also have another type of metadata.+ *+ * 4. Shared magic metadata+ *+ * which in our hypothetical naming scheme can be thought of as+ *+ * 4. Per-sharee private mutable metadata+ *+ * This is "magic metadata" associated with each share. Each user with whom the+ * collection has been shared with can use it store metadata (e.g. archive+ * status) that is private to them, and can only be edited by them. For more+ * details on this type of metadata, see [Note: Share specific metadata].+ */+export interface FileMetadata {+ /**+ * The "Ente" file type - image, video or live photo.+ *+ * Expected to be one of {@link FileType}.+ *+ * See: [Note: Enums in remote objects] for why we keep it as a number+ * instead of the expected enum.+ */+ fileType: number;+ /**+ * The name of the file (including its extension).+ *+ * Don't use this property directly, use {@link fileFileName} instead which+ * takes into account subsequent edits too.+ */+ title: string;+ /**+ * The time when this file was created (epoch microseconds).+ *+ * This is our best attempt at detecting the time when the photo or live+ * photo or video was taken.+ *+ * - We first try to obtain this from metadata, using Exif and other+ * metadata for images and FFmpeg-extracted metadata for video.+ *+ * - If no suitable metadata is available, then we try to deduce it from+ * file name (e.g. for screenshots without any embedded metadata).+ *+ * - If nothing can be found, then it is set to the current time at the time+ * of the upload.+ */+ creationTime: number;+ /**+ * The last modification time of the file (epoch microseconds).+ */+ modificationTime: number;+ /**+ * The latitude where the file was taken.+ */+ latitude?: number;+ /**+ * The longitude where the file was taken.+ */+ longitude?: number;+ /**+ * A hash of the file's contents.+ *+ * For images and videos this is the hash of the file's contents. For live+ * photos, this is the image hash joined with video hash using a colon (i.e.+ * `${imageHash}:{videoHash}`).+ *+ * Legacy compatibility:+ *+ * - The hash might not be present for files uploaded from ancient versions+ * of Ente (Newer clients will always include it in the metadata).+ *+ * - For live photos, older version of the web and desktop client used to+ * add two separate fields - {@link imageHash} and {@link videoHash} - to+ * the file's metadata instead of setting the {@link hash}. This behaviour+ * is deprecated, and if we now see a live photo without a {@link hash},+ * we should reconstruct the hash locally from the image and video hashes+ * by combining them as `${imageHash}:{videoHash}`.+ */+ hash?: string;+ /**+ * The hash of the image component of a live photo.+ *+ * This is a legacy field, and should not be added by us anymore. It is+ * retained to allow us to reconstruct the hash for live photos uploaded by+ * older clients.+ */+ imageHash?: string;+ /**+ * The hash of the video component of a live photo.+ *+ * This is a legacy field, and should not be added by us anymore. It is+ * retained to allow us to reconstruct the hash for live photos uploaded by+ * older clients.+ */+ videoHash?: string;+ /**+ * The duration (in integral seconds) of the video.+ *+ * Only present for videos (`fileType == FileType.video`). For compatibility+ * with other clients, this must be a integer number of seconds, without any+ * sub-second fraction.+ */+ duration?: number;+ /**+ * `true` if the uploading client was unable to generate a thumbnail for the+ * file when uploading it (e.g. unsupported format), and so instead a+ * placeholder thumbnail was used.+ */+ hasStaticThumbnail?: boolean;+}++/**+ * Zod schema for {@link FileMetadata}.+ */+export const FileMetadata = z.looseObject({+ fileType: z.number(),+ title: z.string(),+ creationTime: z.number(),+ modificationTime: z.number(),+ latitude: z.number().nullish().transform(nullToUndefined),+ longitude: z.number().nullish().transform(nullToUndefined),+ hash: z.string().nullish().transform(nullToUndefined),+ imageHash: z.string().nullish().transform(nullToUndefined),+ videoHash: z.string().nullish().transform(nullToUndefined),+ duration: z.number().nullish().transform(nullToUndefined),+ hasStaticThumbnail: z.boolean().nullish().transform(nullToUndefined),+});++/**+ * Mutable private metadata associated with an {@link EnteFile}.+ *+ * - Unlike {@link FileMetadata}, this can change after the file has been+ * uploaded.+ *+ * - Unlike {@link PublicMagicMetadata}, this is only available to the owner of+ * the file.+ *+ * [Note: Private magic metadata is called magic metadata on remote]+ *+ * For historical reasons, the unqualified phrase "magic metadata" in various+ * APIs refers to the (this) private metadata, even though the mutable public+ * metadata is the much more frequently used of the two. See: [Note: Metadatum].+ */+export interface FilePrivateMagicMetadataData {+ /**+ * The visibility of the file.+ *+ * The file's visibility is user specific attribute, and thus we keep it in+ * the private magic metadata. This allows the file's owner to share a file+ * and independently edit its visibility without revealing their visibility+ * preference to the other people with whom they have shared the file.+ *+ * Expected to be one of {@link ItemVisibility}.+ */+ visibility?: number;+}++/**+ * Zod schema for {@link FilePrivateMagicMetadataData}.+ *+ * See: [Note: Use looseObject for metadata Zod schemas]+ */+export const FilePrivateMagicMetadataData = z.looseObject({+ visibility: z.number().nullish().transform(nullToUndefined),+});++/**+ * The visibility of an Ente file or collection.+ */+export const ItemVisibility = {+ /**+ * The normal state - The item is visible.+ */+ visible: 0,+ /**+ * The item has been archived.+ */+ archived: 1,+ /**+ * The item has been hidden.+ */+ hidden: 2,+} as const;++/**+ * The visibility of an Ente file or collection.+ *+ * This is the erasable type. See the {@link ItemVisibility} object for the+ * possible values and their symbolic constants.+ */+export type ItemVisibility =+ (typeof ItemVisibility)[keyof typeof ItemVisibility];++/**+ * Mutable public metadata associated with an {@link EnteFile}.+ *+ * - Unlike {@link FileMetadata}, this can change after the file has been+ * uploaded.+ *+ * - Unlike {@link FilePrivateMagicMetadataData}, this is available to all the+ * people with whom the file has been shared.+ *+ * For more details, see [Note: Metadatum].+ *+ * ---+ *+ * [Note: Optional magic metadata keys]+ *+ * Remote does not support nullish (`undefined` or `null`) values for the keys+ * in the magic metadata associated with a file. All of the keys themselves are+ * optional though.+ *+ * That is, all magic metadata properties are of the form:+ *+ * foo?: T+ *+ * And never like:+ *+ * foo: T | undefined+ */+export interface FilePublicMagicMetadataData {+ /**+ * A ISO 8601 date time string without a timezone, indicating the local time+ * where the photo (or video) was taken.+ *+ * e.g. "2022-01-26T13:08:20".+ *+ * See: [Note: Photos are always in local date/time].+ */+ dateTime?: string;+ /**+ * When available, a "±HH:mm" string indicating the UTC offset of the place+ * where the photo was taken.+ *+ * e.g. "+02:00".+ */+ offsetTime?: string;+ /**+ * Modified value of the date time associated with an {@link EnteFile}.+ *+ * Epoch microseconds.+ *+ * This field stores edits to the {@link creationTime} {@link FileMetadata}+ * field.+ */+ editedTime?: number;+ /**+ * Modified file name of the {@link EnteFile}.+ *+ * This field stores edits to the {@link title} {@link FileMetadata} field.+ */+ editedName?: string;+ /**+ * The width of the photo (or video) in pixels.+ *+ * While this should usually be present, it is not guaranteed to be.+ */+ w?: number;+ /**+ * The height of the photo (or video) in pixels, if available.+ *+ * While this should usually be present, it is not guaranteed to be.+ */+ h?: number;+ /**+ * An arbitrary caption / description string that the user has added to the+ * file.+ *+ * The length of this field is capped to some arbitrary maximum by client+ * side checks.+ */+ caption?: string;+ /**+ * The name provided by the person who uploaded the file using an otherwise+ * anonymous public link upload.+ *+ * When sharing an album using a public link, the owner of the collection+ * can enable public uploads. When uploading files this way, the public+ * albums app asks the person doing the upload their name, and that gets+ * persisted here in the file's public magic metadata so that it can be+ * shown to the Ente users who are participants in the collection.+ *+ * (The owner of such files will be the owner of the collection)+ */+ uploaderName?: string;+ /** Camera make (manufacturer) extracted from metadata. */+ cameraMake?: string;+ /** Camera model extracted from metadata. */+ cameraModel?: string;+ /**+ * Edited latitude of the file+ *+ * If the user edits the location (latitude and longitude) of a file within+ * Ente, then the edits will be stored as the {@link lat} and {@link long}+ * properties in the file's public magic metadata.+ */+ lat?: number;+ /**+ * Edited longitude of the file.+ *+ * See {@link long}.+ */+ long?: number;+ /**+ * An arbitrary integer set to indicate that this file should be skipped for+ * the purpose of HLS generation.+ *+ * Current semantics:+ *+ * - if 1, skip this file+ * - otherwise attempt processing+ *+ * [Note: Marking files which do not need video processing]+ *+ * Some video files do not require generation of a HLS stream. The current+ * logic is H.264 files less than 10 MB, but this might change in future+ * clients.+ *+ * For such skipped files, there thus won't be a HLS playlist generated.+ * However, we still need a way to indicate to other clients that this file+ * has already been looked at.+ *+ * To that end, we add a flag to the public magic metadata for the file. To+ * allow future flexibility, this flag is an integer "streaming version".+ * Currently it is set to 1 by a client who recognizes that this file does+ * not need processing, and other clients can ignore this file if they find+ * sv == 1. In the future, there might be other values for sv (e.g. if the+ * skip logic changes).+ */+ sv?: number;+}++/**+ * Zod schema for the {@link PublicMagicMetadata} type.+ *+ * [Note: Use looseObject for metadata Zod schemas]+ *+ * It is important to (recursively) use the {@link looseObject} option when+ * defining Zod schemas for the various metadata types (the plaintext JSON+ * objects) because we want to retain all the fields we get from remote. There+ * might be other, newer, clients out there adding fields that the current+ * client might not we aware of, and we don't want to overwrite them.+ */+export const FilePublicMagicMetadataData = z.looseObject({+ dateTime: z.string().nullish().transform(nullToUndefined),+ offsetTime: z.string().nullish().transform(nullToUndefined),+ editedTime: z.number().nullish().transform(nullToUndefined),+ editedName: z.string().nullish().transform(nullToUndefined),+ w: z.number().nullish().transform(nullToUndefined),+ h: z.number().nullish().transform(nullToUndefined),+ // Some legacy remote records have been seen with numeric captions.+ caption: z+ .union([z.string(), z.number()])+ .nullish()+ .transform((v) => (v == null ? undefined : String(v))),+ uploaderName: z.string().nullish().transform(nullToUndefined),+ cameraMake: z.string().nullish().transform(nullToUndefined),+ cameraModel: z.string().nullish().transform(nullToUndefined),+ lat: z.number().nullish().transform(nullToUndefined),+ long: z.number().nullish().transform(nullToUndefined),+ sv: z.number().nullish().transform(nullToUndefined),+});++/**+ * Return the hash of the file by reading it from its metadata.+ *+ * This is a convenience function that directly reads the information from the+ * metadata in the happy path, but also has branches to handle the legacy format+ * that older clients used to upload. For more details, see the note in the+ * documentation for {@link hash} in {@link FileMetadata}.+ */+export const metadataHash = (metadata: FileMetadata) => {+ const hash = metadata.hash;+ if (hash) return hash;++ // Handle past live photos upload from web client.+ if (+ metadata.fileType == FileType.livePhoto &&+ metadata.imageHash &&+ metadata.videoHash+ ) {+ return `${metadata.imageHash}:${metadata.videoHash}`;+ }++ // Items uploaded by very old clients might not have a hash, so this is not+ // necessarily an error even if rare.+ return undefined;+};++/**+ * Return `true` if the {@link ItemVisibility} of the given {@link file} is+ * archived.+ */+export const isArchivedFile = (file: EnteFile) =>+ file.magicMetadata?.data.visibility == ItemVisibility.archived;++/**+ * Return the file name of the file (including both the name and the extension).+ *+ * This function handles files with edited names. It will first look into the+ * public magic metadata of a file to see if the file has an edited name, and if+ * so, return that. Otherwise it will return the original name of the file+ * stored in its metadata.+ *+ * @returns The provided {@link EnteFile}'s filename, including the extension.+ * e.g. "flower.png".+ */+export const fileFileName = (file: EnteFile) =>+ file.pubMagicMetadata?.data.editedName ?? file.metadata.title;++/**+ * Return the file's creation timestamp (epoch microseconds).+ *+ * This function handles files with edited dates.+ *+ * While sometimes the epoch timestamp is the correct value to use, it is also+ * possible that {@link fileCreationPhotoDate} might be more appropriate.+ */+export const fileCreationTime = (file: EnteFile) =>+ file.pubMagicMetadata?.data.editedTime ?? file.metadata.creationTime;++/**+ * Return the file's creation date as a Date in the hypothetical "timezone of+ * the photo".+ *+ * This function handles files with edited dates. For all the details and+ * nuance, see {@link createPhotoDate}.+ */+export const fileCreationPhotoDate = (file: EnteFile) =>+ createPhotoDate(+ file.pubMagicMetadata?.data.dateTime ??+ file.pubMagicMetadata?.data.editedTime ??+ file.metadata.creationTime,+ );++/**+ * Return the GPS coordinates (if any) present in the given {@link EnteFile}.+ *+ * This function handles files with edited locations.+ */+export const fileLocation = (file: EnteFile): Location | undefined => {+ const { lat, long } = file.pubMagicMetadata?.data ?? {};+ // Use (lat, long) only if both are present and nonzero.+ const edited = lat && long;++ const latitude = nullToUndefined(edited ? lat : file.metadata.latitude);+ const longitude = nullToUndefined(edited ? long : file.metadata.longitude);++ if (latitude === undefined || longitude === undefined) return undefined;+ if (Number.isNaN(latitude) || Number.isNaN(longitude)) return undefined;+ if (latitude === 0 && longitude === 0) return undefined;++ return { latitude, longitude };+};++/**+ * Return the camera make (manufacturer) for the file.+ */+export const fileCameraMake = (file: EnteFile): string | undefined => {+ const rawMake = file.pubMagicMetadata?.data.cameraMake;+ if (!rawMake) return undefined;+ const make = rawMake.trim();+ if (make.length === 0) return undefined;+ return make;+};++/**+ * Return the camera model for the file.+ */+export const fileCameraModel = (file: EnteFile): string | undefined => {+ const rawModel = file.pubMagicMetadata?.data.cameraModel;+ if (!rawModel) return undefined;+ const model = rawModel.trim();+ if (model.length === 0) return undefined;+ return model;+};++/**+ * Return a user-friendly string describing the camera used for the file.+ */+export const fileCameraLabel = (file: EnteFile): string | undefined => {+ const make = fileCameraMake(file);+ const model = fileCameraModel(file);+ if (!make && !model) return undefined;+ if (make && model) return `${make} ${model}`;+ return model ?? make;+};++/**+ * Return the duration of the video as a formatted "HH:mm:ss" string (when+ * present) for the given {@link EnteFile}.+ *+ * Only files with type `FileType.video` are expected to have a duration.+ *+ * @returns The duration of the video as a string of the form "HH:mm:ss". The+ * underlying duration present in the file's metadata is guaranteed to be+ * integral, so there will never be a subsecond component.+ *+ * - If the hour component is all zeroes, it will be omitted.+ *+ * - Leading zeros in the minutes component will be trimmed off if an hour+ * component is not present. If minutes is all zeros, then "0" will be used.+ *+ * - For example, an underlying duration of 595 seconds will result in a+ * formatted string of the form "9:55". While an underlying duration of 9+ * seconds will be returned as a string "0:09".+ *+ * - A zero duration will be treated as undefined.+ */+export const fileDurationString = (file: EnteFile): string | undefined => {+ const d = file.metadata.duration;+ if (!d) return undefined;++ const s = d % 60;+ const m = Math.floor(d / 60) % 60;+ const h = Math.floor(d / 3600);++ const ss = s > 9 ? `${s}` : `0${s}`;+ if (h) {+ const mm = m > 9 ? `${m}` : `0${m}`;+ return `${h}:${mm}:${ss}`;+ } else {+ return `${m}:${ss}`;+ }+};++/**+ * Metadata about a file extracted from various sources (like Exif) when+ * uploading it into Ente.+ *+ * Depending on the file type and the upload sequence, this data can come from+ * various places:+ *+ * - For images it comes from the Exif and other forms of metadata (XMP, IPTC)+ * embedded in the file.+ *+ * - For videos, similarly it is extracted from the metadata embedded in the+ * file using ffmpeg.+ *+ * - From various sidecar files (like metadata JSONs) that might be sitting next+ * to the original during an import.+ *+ * These bits then get distributed and saved in the various metadata fields+ * associated with an {@link EnteFile} (See: [Note: Metadatum]).+ *+ * The advantage of having them be attached to an {@link EnteFile} is that it+ * allows us to perform operations using these attributes without needing to+ * re-download the original image.+ *+ * The disadvantage is that it increases the network payload (anything attached+ * to an {@link EnteFile} comes back in the diff response), and thus latency and+ * local storage costs for all clients. Thus, we need to curate what gets+ * preserved within the {@link EnteFile}'s metadatum.+ */+export interface ParsedMetadata {+ /** The width of the image, in pixels. */+ width?: number;+ /** The height of the image, in pixels. */+ height?: number;+ /**+ * The date/time when this photo was taken.+ *+ * Logically this is a date in local timezone of the place where the photo+ * was taken. See: [Note: Photos are always in local date/time].+ */+ creationDate?: ParsedMetadataDate | undefined;+ /** The GPS coordinates where the photo was taken. */+ location?: Location;+ /**+ * A caption / description attached by the user to the photo.+ */+ description?: string;+ /** Camera make (manufacturer) extracted from metadata (e.g. Apple, Canon). */+ cameraMake?: string;+ /** Camera model extracted from metadata (e.g. iPhone 15 Pro). */+ cameraModel?: string;+}++/**+ * [Note: Photos are always in local date/time]+ *+ * Photos out in the wild frequently do not have associated timezone offsets for+ * the date/time embedded in their metadata. This is a artifact of an era where+ * cameras didn't know often even know their date/time correctly, let alone the+ * UTC offset of their local data/time.+ *+ * This is beginning to change with smartphone cameras, and is even reflected in+ * the standards. e.g. Exif metadata now has auxiliary "OffsetTime*" tags for+ * indicating the UTC offset of the local date/time in the existing Exif tags+ * (See: [Note: Exif dates]).+ *+ * So a photos app needs to deal with a mixture of photos whose dates may or may+ * not have UTC offsets. This is fact #1.+ *+ * Users expect to see the time they took the photo, not the time in the place+ * they are currently. People expect a New Year's Eve photo from a vacation to+ * show up as midnight, not as (e.g.) 19:30 IST. This is fact #2.+ *+ * Combine these two facts, and if you ponder a bit, you'll find that there is+ * only one way for a photos app to show / sort / label the date – by using the+ * local date/time without the attached UTC offset, **even if it is present**.+ *+ * The UTC offset is still useful though, and we don't want to lose that+ * information. The number of photos with a UTC offset will only increase. And+ * whenever it is present, it provides additional context for the user.+ *+ * So we keep both the local date/time string (an ISO 8601 string guaranteed to+ * be without an associated UTC offset), and an (optional) UTC offset string.+ *+ * It is important to NOT think of the local date/time string as an instant of+ * time that can be converted to a UTC timestamp. It cannot be converted to a+ * UTC timestamp because while it itself might have the optional associated UTC+ * offset, its siblings photos might not. The only way to retain their+ * comparability is to treat them all the "time zone where the photo was taken".+ *+ * All this is good, but we still need to retain the existing `creationTime` UTC+ * epoch timestamp because in some cases when importing photos from other+ * providers, that's all we get. We could try and convert that to a date/time+ * string too, but since we anyways need to handle existing code that deals with+ * epoch timestamps, we retain them as they were provided.+ */+export interface ParsedMetadataDate {+ /**+ * A local date/time.+ *+ * This is a partial ISO 8601 date/time string guaranteed not to have a+ * timezone offset. e.g. "2023-08-23T18:03:00.000".+ */+ dateTime: string;+ /**+ * An optional offset from UTC.+ *+ * This is an optional UTC offset string of the form "±HH:mm" or "Z",+ * specifying the timezone offset for {@link dateTime} when available.+ */+ offset: string | undefined;+ /**+ * UTC epoch microseconds derived from {@link dateTime} and+ * {@link offset}.+ *+ * When the {@link offset} is present, this will accurately reflect a+ * UTC timestamp. When the {@link offset} is not present it convert to a+ * UTC timestamp by assuming that the given {@link dateTime} is in the local+ * time where this code is running. This is a good assumption but not always+ * correct (e.g. vacation photos).+ */+ timestamp: number;+}++/**+ * Parse a partial or full ISO 8601 string into a {@link ParsedMetadataDate}.+ *+ * @param s A partial or full ISO 8601 string. That is, it is a string of the+ * form "2023-08-23T18:03:00.000+05:30" or "2023-08-23T12:33:00.000Z" with all+ * components except the year potentially missing.+ *+ * @return A {@link ParsedMetadataDate}, or `undefined` if {@link s} cannot be+ * parsed.+ *+ * ---+ * Some examples:+ *+ * - "2023" => ("2023-01-01T00:00:00.000", undefined)+ * - "2023-08" => ("2023-08-01T00:00:00.000", undefined)+ * - "2023-08-23" => ("2023-08-23T00:00:00.000", undefined)+ * - "2023-08-23T18:03:00" => ("2023-08-23T18:03:00.000", undefined)+ * - "2023-08-23T18:03:00+05:30" => ("2023-08-23T18:03:00.000', "+05:30")+ * - "2023-08-23T18:03:00.000+05:30" => ("2023-08-23T18:03:00.000", "+05:30")+ * - "2023-08-23T12:33:00.000Z" => ("2023-08-23T12:33:00.000", "Z")+ */+export const parseMetadataDate = (+ s: string,+): ParsedMetadataDate | undefined => {+ // Construct the timestamp using the original string itself. If s is+ // parseable as a date, then this'll be give us the correct UTC timestamp.+ // If the UTC offset is not present, then this will be in the local+ // (current) time.+ const timestamp = new Date(s).getTime() * 1000;+ if (isNaN(timestamp)) {+ // s in not a well formed ISO 8601 date time string.+ return undefined;+ }++ // Now we try to massage s into two parts - the local date/time string, and+ // an UTC offset string.++ let offset: string | undefined;+ let sWithoutOffset: string;++ // Check to see if there is a time-zone descriptor of the form "Z" or+ // "±05:30" or "±0530" at the end of s.+ const m = /Z|[+-]\d\d:?\d\d$/.exec(s);+ if (m?.index) {+ sWithoutOffset = s.substring(0, m.index);+ offset = s.substring(m.index);+ } else {+ sWithoutOffset = s;+ }++ // Convert sWithoutOffset - a potentially partial ISO 8601 string - to a+ // canonical ISO 8601 string.+ //+ // In its full generality, this is non-trivial. The approach we take is:+ //+ // 1. Rely on the browser to be able to partial ISO 8601 string. This relies+ // on non-standard behaviour but works in practice seemingly.+ //+ // 2. Get an ISO 8601 representation of it. This is standard.+ //+ // A thing to watch out for is that browsers treat date only and date time+ // strings differently when the offset is not present (as would be for us).+ //+ // > When the time zone offset is absent, date-only forms are interpreted as+ // > a UTC time and date-time forms are interpreted as local time.+ // >+ // > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format+ //+ // For our purpose, we want to always interpret them as UTC time. This way,+ // when we later gets back its string representation for step 2, we will get+ // back the same numerical value, and can just chop off the "Z".+ //+ // So if the length of the string is less than or equal to yyyy-mm-dd (10),+ // then we use it verbatim, otherwise we append a "Z".++ const date = new Date(+ sWithoutOffset + (sWithoutOffset.length <= 10 ? "" : "Z"),+ );++ // The string returned by `toISOString` is guaranteed to be UTC and denoted+ // by the suffix "Z". If we chop that off, we get back a canonical+ // representation we wish for: A otherwise well-formed ISO 9601 string but+ // any time zone descriptor.+ const dateTime = dropLast(date.toISOString());++ return { dateTime, offset, timestamp };+};++const dropLast = (s: string) => (s ? s.substring(0, s.length - 1) : s);++/**+ * Return a date that can be used on the represent a photo on the UI, by+ * constructing it from a {@link ParsedMetadataDate}, or its {@link dateTime}+ * component, or a UTC epoch timestamp.+ *+ * These dates are all hypothetically in the timezone of the place where the+ * photo was taken. Different photos might've been taken in different timezones,+ * which is why it is hypothetical, so concretely these are all mapped to the+ * current timezone.+ *+ * The difference is subtle, but we should not think of these as absolute points+ * on the UTC timeline. They are instead better thought of as dates without an+ * associated timezone. For the purpose of mapping them all to a comparable+ * dimension them we all contingently use the current timezone - this makes it+ * easy to use JavaScript Date constructor which assumes that any date/time+ * string without an associated timezone is in the current timezone.+ *+ * Whenever we're surfacing them in the UI, or using them for grouping (say by+ * day), we should use their current timezone representation, not the UTC one.+ *+ * See also: [Note: Photos are always in local date/time].+ */+export const createPhotoDate = (+ dateLike: ParsedMetadataDate | string | number,+) => {+ switch (typeof dateLike) {+ case "object":+ // A ISO 8601 string without a timezone. The Date constructor will+ // assume the timezone to be the current timezone.+ return new Date(dateLike.dateTime);+ case "string":+ // This is expected to be a string with the same meaning as+ // `ParsedMetadataDate.dateTime`.+ return new Date(dateLike);+ case "number":+ // A UTC epoch microseconds value.+ return new Date(dateLike / 1000);+ }+};diff --git a/web/apps/albums/vendor/ente-media/file-type.ts b/web/apps/albums/vendor/ente-media/file-type.tsnew file mode 100644index 0000000000..c0deee74bb--- /dev/null+++ b/web/apps/albums/vendor/ente-media/file-type.ts@@ -0,0 +1,75 @@+/**+ * The type of an {@link EnteFile}.+ *+ * This is an object containing symbolic constant. There is also an eraseable+ * TypeScript type type with the same name, {@link FileType}.+ */+export const FileType = {+ /**+ * An image (e.g. JPEG).+ */+ image: 0,+ /**+ * A video (e.g. MP4).+ */+ video: 1,+ /**+ * A live photo, aka motion photo.+ *+ * This is a combination of an image and a (short) video capturing the+ * before and after when the image was taken. We preserve it as a zip+ * containing both the parts.+ */+ livePhoto: 2,+} as const;++/**+ * The type of an {@link EnteFile}.+ *+ * This is an eraseable TypeScript type. There is also a {@link FileType} object+ * with the same name that contains the corresponding symbolic constants.+ */+export type FileType = (typeof FileType)[keyof typeof FileType];++export interface FileTypeInfo {+ fileType: FileType;+ /**+ * A lowercased, standardized extension for files of the current type.+ *+ * For live photos, this is set to the extension of the image component of+ * the live photo.+ */+ extension: string;+ mimeType?: string;+}++// list of format that were missed by type-detection for some files.+export const KnownFileTypeInfos: FileTypeInfo[] = [+ { fileType: FileType.image, extension: "jpeg", mimeType: "image/jpeg" },+ { fileType: FileType.image, extension: "jpg", mimeType: "image/jpeg" },+ { fileType: FileType.video, extension: "webm", mimeType: "video/webm" },+ { fileType: FileType.video, extension: "mod", mimeType: "video/mpeg" },+ { fileType: FileType.video, extension: "mp4", mimeType: "video/mp4" },+ { fileType: FileType.image, extension: "gif", mimeType: "image/gif" },+ { fileType: FileType.video, extension: "dv", mimeType: "video/x-dv" },+ { fileType: FileType.video, extension: "wmv", mimeType: "video/x-ms-asf" },+ { fileType: FileType.video, extension: "hevc", mimeType: "video/hevc" },+ {+ fileType: FileType.image,+ extension: "raf",+ mimeType: "image/x-fuji-raf",+ },+ {+ fileType: FileType.image,+ extension: "orf",+ mimeType: "image/x-olympus-orf",+ },+ {+ fileType: FileType.image,+ extension: "crw",+ mimeType: "image/x-canon-crw",+ },+ { fileType: FileType.video, extension: "mov", mimeType: "video/quicktime" },+];++export const KnownNonMediaFileExtensions = ["xmp", "html", "txt"];diff --git a/web/apps/albums/vendor/ente-media/file.ts b/web/apps/albums/vendor/ente-media/file.tsnew file mode 100644index 0000000000..04f2e004c7--- /dev/null+++ b/web/apps/albums/vendor/ente-media/file.ts@@ -0,0 +1,473 @@+import { decryptBox, decryptMetadataJSON } from "ente-base/crypto";+import log from "ente-base/log";+import { nullishToBlank, nullToUndefined } from "ente-utils/transform";+import { z } from "zod";+import { ignore } from "./collection";+import {+ fileFileName,+ FileMetadata,+ FilePrivateMagicMetadataData,+ FilePublicMagicMetadataData,+} from "./file-metadata";+import { FileType } from "./file-type";+import {+ decryptMagicMetadata,+ RemoteMagicMetadata,+ type MagicMetadata,+} from "./magic-metadata";++/**+ * A File.+ *+ * An EnteFile represents a file in Ente. It does not contain the actual data.+ *+ * It is named with an "Ente" prefix to disambiguate it from the web's native+ * {@link File} type.+ *+ * All files have an id (numeric) that is unique across all the files stored by+ * an Ente instance. Each file is also always associated with a collection, and+ * has an owner (both of these linkages are stored as the corresponding numeric+ * IDs within the EnteFile structure).+ *+ * > For shared files, the owner of the file is not necessarily the owner of all+ * > the collections to which the file belongs.+ *+ * While the file ID is unique, we'd can still have multiple entries for each+ * file ID in our local state, one for each {@link Collection} to which the file+ * belongs. That is, the uniqueness is across the (fileID, collectionID) pairs.+ * See [Note: Collection file].+ *+ * [Note: File lifecycle]+ *+ * 1. **Normal**: A file starts off by belonging to at least one collection. It+ * can then be added to additional collections, each of which will be an+ * EnteFile with a distinct (fileID, collectionID) pair.+ *+ * 2. **Trash**: If the user deletes the file, then the file moves to trash.+ * Such files will have {@link isDeleted} `true` in their+ * {@link RemoteEnteFile} entries when we perform a collection diff to let+ * the client know that the corresponding file is no longer part of the+ * collection.+ *+ * Such files will now be returned as part of the trash diff, with both+ * {@link isDeleted} and {@link isRestored} set to `false` for their trash+ * entry.+ *+ * 3. **Restore**: If the the user were to restore the file before permanent+ * deletion, then it effectively works as moving a normal file to an normal+ * collection. In particular, if we were to restore the file back to one of+ * the collections it was part of pre-trash, and then fetch the collection+ * diff for that collection, we would get back the same file object, except+ * with {@link isDeleted} will now be `false`.+ *+ * The trash entry for restored files will have {@link isRestored} set to+ * `true` to notify clients that an item that was previously in trash is no+ * longer there because it has been restored.+ *+ * 4. **Permanent deletion**: If the file remains in trash for 30 days, or if+ * the user explictly permanently deletes it from the trash, or if the user+ * explicitly clears the trash, then it will get permanently deleted.+ *+ * The trash entry for such permanently deleted files will have+ * {@link isDeleted} set to `true` to notify clients that an item that was+ * previously in trash is no longer there because it has been permanently+ * deleted.+ *+ * When a file is permanently deleted, remote will scrub off data from its+ * fields. See: [Note: Optionality of remote file fields].+ */+export interface EnteFile {+ /**+ * The file's globally unique ID.+ *+ * The file's ID is a integer assigned by remote as the identifier for an+ * {@link EnteFile} when it is created. It is globally unique across all+ * files stored by an Ente instance, and is not scoped to the current user.+ */+ id: number;+ /**+ * The ID of the collection with which this file as associated.+ *+ * The same file (ID) may be associated with multiple collectionID, each of+ * which will come and stay as distinct {@link EnteFile} instances - all of+ * which will have the same {@link id} but distinct {@link collectionID}.+ *+ * So the ({@link id}, {@link collectionID}) pair is a primary key, not the+ * {@link id} on its own. See: [Note: Collection file].+ */+ collectionID: number;+ /**+ * The ID of the Ente user who owns the file.+ *+ * Files uploaded by non users on public links belong to the owner of the+ * collection who created the public link (See {@link uploaderName} in+ * {@link FilePublicMagicMetadataData}).+ */+ ownerID: number;+ /**+ * The file's key.+ *+ * This is the base64 representation of the decrypted encryption key+ * associated with this file. When we get the file from remote (as a+ * {@link RemoteEnteFile}), the file key itself would have been encrypted by+ * the key of the {@link Collection} to which this file belongs.+ *+ * This key is used to encrypt both the file's contents, and any associated+ * data (e.g., metadatum, thumbnail) for the file.+ */+ key: string;+ /**+ * Information pertaining to the encrypted S3 object that has the file's+ * contents.+ */+ file: FileObjectAttributes;+ /**+ * Information pertaining to the encrypted S3 object that has the contents+ * of the file's thumbnail.+ */+ thumbnail: FileObjectAttributes;+ /**+ * Static, remote visible, information associated with a file.+ *+ * This is information about storage used by the file and its thumbnail.+ * Unlike {@link metadata} which is E2EE, the {@link FileInfo} is remote+ * visible for bookkeeping purposes.+ *+ * Files uploaded by very old versions of Ente might not have this field.+ */+ info?: FileInfo;+ /**+ * The last time the file was updated (epoch microseconds).+ *+ * (e.g. magic metadata updates).+ */+ updationTime: number;+ /**+ * Public static metadata associated with a file.+ *+ * This is the immutable metadata that gets associated with a file when it+ * is uploaded, and there after cannot be changed.+ *+ * It is visible to all users with whom the file gets shared.+ *+ * > {@link pubMagicMetadata} contains fields that override fields present+ * > in the metadata. Clients overlay those atop the metadata fields, and+ * > thus they can be used to implement edits.+ *+ * See: [Note: Metadatum].+ */+ metadata: FileMetadata;+ /**+ * Private mutable metadata associated with the file that is only visible to+ * the owner of the file.+ *+ * See: [Note: Metadatum]+ */+ magicMetadata?: MagicMetadata<FilePrivateMagicMetadataData>;+ /**+ * Public mutable metadata associated with the file that is visible to all+ * users with whom the file has been shared.+ *+ * While in almost all cases, files will have associated public magic+ * metadata since newer clients have something or the other they need to add+ * to it, its presence is not guaranteed.+ *+ * See: [Note: Metadatum]+ */+ pubMagicMetadata?: MagicMetadata<FilePublicMagicMetadataData>;+}++/**+ * Attributes about an object related to an {@link EnteFile}.+ *+ * - The file's contents,+ *+ * - The file's thumbnail's contents.+ */+export interface FileObjectAttributes {+ /**+ * The decryption header that was used when encrypting the objects's+ * contents (with the file's key) before uploading them to S3 remote.+ */+ decryptionHeader: string;+}++export const RemoteFileObjectAttributes = z.looseObject({+ /**+ * The decryption header (base64 string) used when encrypting the object.+ *+ * For permanently deleted files, this will still be present, but remote may+ * scrub it to a blank string or a placeholder.+ */+ decryptionHeader: z.string(),+});++/**+ * Static information associated with a file.+ */+export interface FileInfo {+ /**+ * The size of the file (in bytes).+ *+ * This will not be present for files with zero length.+ */+ fileSize?: number;+ /**+ * The size of the thumbnail associated with the file (in bytes).+ *+ * This will not be present for files that don't have thumbnails (an old Locker issue)+ */+ thumbSize?: number;+}++export const RemoteFileInfo = z.looseObject({+ fileSize: z.number().nullish().transform(nullToUndefined),+ thumbSize: z.number().nullish().transform(nullToUndefined),+});++const RemoteFileMetadata = z.object({+ /**+ * The metadata JSON object associated with the file, encrypted using the+ * file's key.+ *+ * Base64 encoded.+ *+ * There is one case when this will be not be present - for permanently+ * deleted files when we get them as part of a trash diff (see the longer+ * note about this below):+ *+ * [Note: Optionality of remote file fields]+ *+ * When a file is permanently deleted, remote will scrub off data from its+ * fields (either by nulling them outright, or inserting placeholders,+ * depending on the remote schema).+ *+ * So a {@link RemoteEnteFile} object present in the trash item of a+ * permanently deleted file in the trash diff response (i.e. a trash item+ * with {@link isDeleted} is set to `true`) may not have the fields which we+ * normally would expect to always be there for files.+ *+ * This is not a problem in code flow since the client will not even attempt+ * to decrypt or use such file entries, so the absence of these fields has+ * no impact. However, it does impact JSON validation, which might+ * preemptively (and unnecessarily) fail for such {@link RemoteEnteFile}s.+ *+ * Luckily, this is simple to handle since most of the data in a+ * {@link RemoteEnteFile} is already optional. The only tweak we require is+ * handling missing {@link encryptedData} of the {@link RemoteEnteFile}'s+ * {@link metadata} field in such cases. We could mark it as a optional too,+ * but since we anyways shouldn't be using this field, so for convenience of+ * the upstream types, we transform such missing values to a blank string.+ */+ encryptedData: z.string().nullish().transform(nullishToBlank),+ /**+ * The base64 encoded decryption header that was used during encryption of+ * {@link encryptedData}.+ *+ * For permanently deleted files, this will still be present, but remote may+ * scrub it to a blank string or a placeholder.+ */+ decryptionHeader: z.string(),+});++export type RemoteFileMetadata = z.infer<typeof RemoteFileMetadata>;++/**+ * Zod schema for a {@link EnteFile} as represented in our interactions with+ * remote.+ *+ * The contents of the fields are encrypted by the file's key (which itself is+ * encrypted by the key of the collection that contains the file). EnteFile is+ * the decrypted local representation.+ *+ * See: [Note: Use looseObject when parsing JSON that will get persisted]+ */+export const RemoteEnteFile = z.looseObject({+ id: z.number(),+ collectionID: z.number(),+ ownerID: z.number(),+ /**+ * The file's key, encrypted using the key of the collection that contains+ * the file.+ *+ * Base64 encoded.+ */+ encryptedKey: z.string(),+ /**+ * The nonce to use when decrypting {@link encryptedKey}.+ *+ * Base64 encoded.+ */+ keyDecryptionNonce: z.string(),+ file: RemoteFileObjectAttributes,+ thumbnail: RemoteFileObjectAttributes,+ info: RemoteFileInfo.nullish().transform(nullToUndefined),+ updationTime: z.number(),+ /**+ * Removal marker in diff responses.+ *+ * This is set to `true` in the collection diff response to indicate files+ * that are no longer part of the collection.+ *+ * - They may have been removed from the collection.+ *+ * - They have been deleted (either moved to trash, or permanently deleted).+ */+ isDeleted: z.boolean().nullish().transform(nullToUndefined),+ metadata: RemoteFileMetadata,+ magicMetadata: RemoteMagicMetadata.nullish().transform(nullToUndefined),+ pubMagicMetadata: RemoteMagicMetadata.nullish().transform(nullToUndefined),+});++export type RemoteEnteFile = z.infer<typeof RemoteEnteFile>;++/**+ * Zod schema for a response for various "/diff" APIs that return changes since+ * a provided timestamp.+ *+ * - "/collections/v2/diff"+ * - "/public-collection/diff"+ * - "/cast/diff"+ */+export const FileDiffResponse = z.object({+ /**+ * A batch of changes (upserts or deletions).+ *+ * See also: [Note: Diff response will have at most one entry for an id].+ */+ diff: RemoteEnteFile.array(),+ /**+ * If `true`, then there are more changes that can be fetched by doing+ * another of the same API call, this time passing it the latest from+ * amongst the timestamps of entries in {@link diff}.+ */+ hasMore: z.boolean(),+});++/**+ * Decrypt a remote file using the provided {@link collectionKey}.+ *+ * @param file The remote file to decrypt.+ *+ * @param collectionKey The base64 encoded key of the collection to which this+ * file belongs. It is needed to decrypt the file's key (which in turn is needed+ * to decrypt the file's contents and other encrypted fields).+ *+ * @returns A decrypted {@link EnteFile}.+ */+export const decryptRemoteFile = async (+ remoteFile: RemoteEnteFile,+ collectionKey: string,+): Promise<EnteFile> => {+ // RemoteEnteFile is a looseObject, and we want to retain that semantic for+ // the parsed EnteFile. Mention all fields that we want to explicitly drop+ // or transform, passthrough the rest unchanged in the return value.+ //+ // See: [Note: Use looseObject when parsing JSON that will get persisted].+ const {+ id,+ encryptedKey,+ keyDecryptionNonce,+ isDeleted,+ metadata: encryptedMetadata,+ magicMetadata: encryptedMagicMetadata,+ pubMagicMetadata: encryptedPubMagicMetadata,+ ...rest+ } = remoteFile;++ // This flag is relevant only in the diff response, where it indicates that+ // the file should be removed from the corresponding collection. We would've+ // already acted on that information, so drop it from our local state.+ ignore(isDeleted);++ const key = await decryptBox(+ { encryptedData: encryptedKey, nonce: keyDecryptionNonce },+ collectionKey,+ );++ const metadataJSON = await decryptMetadataJSON(encryptedMetadata, key);+ const metadata = FileMetadata.parse(+ transformDecryptedMetadataJSON(id, metadataJSON),+ );++ let magicMetadata: EnteFile["magicMetadata"];+ if (encryptedMagicMetadata) {+ const genericMM = await decryptMagicMetadata(+ encryptedMagicMetadata,+ key,+ );+ const data = FilePrivateMagicMetadataData.parse(genericMM.data);+ magicMetadata = { ...genericMM, data };+ }++ let pubMagicMetadata: EnteFile["pubMagicMetadata"];+ if (encryptedPubMagicMetadata) {+ const genericMM = await decryptMagicMetadata(+ encryptedPubMagicMetadata,+ key,+ );+ const data = FilePublicMagicMetadataData.parse(genericMM.data);+ pubMagicMetadata = { ...genericMM, data };+ }++ return { ...rest, id, key, metadata, magicMetadata, pubMagicMetadata };+};++/**+ * Apply some transforms to gracefully handle metadata from old clients.+ *+ * @param metadataJSON The decrypted and parsed metadata JSON. Since TypeScript+ * does not have a native JSON type, this is typed as an `unknown`.+ *+ * @returns A JSON object with any transformations applied, if needed.+ */+export const transformDecryptedMetadataJSON = (+ fileID: number,+ metadataJSON: unknown,+) => {+ // The file ID threshold is an arbitrary cutoff so that this graceful+ // handling does not mask new issues.+ if (fileID > 100000000) return metadataJSON;++ if (typeof metadataJSON != "object") return metadataJSON;+ if (!metadataJSON) return metadataJSON;++ // In very rare cases (have found only one so far, a very old file in+ // Vishnu's account, uploaded by an initial dev version of Ente) the photo+ // has no modification time. Gracefully handle such cases.+ if (+ !("modificationTime" in metadataJSON) ||+ !metadataJSON.modificationTime+ ) {+ if ("creationTime" in metadataJSON) {+ log.info(`Patching metadata modification time for file ${fileID}`);+ (metadataJSON as Record<string, unknown>).modificationTime =+ metadataJSON.creationTime;+ }+ }++ // In very rare cases (again, some files shared with Vishnu's account,+ // uploaded by dev builds) the photo might not have a file type. Gracefully+ // handle these too.+ if (+ !("fileType" in metadataJSON) ||+ typeof metadataJSON.fileType != "number"+ ) {+ log.info(`Patching metadata file type for file ${fileID}`);+ (metadataJSON as Record<string, unknown>).fileType = FileType.image;+ }++ return metadataJSON;+};++/**+ * A short identifier for a file in log messages.+ *+ * e.g. "file flower.png (827233681)"+ *+ * @returns a string to use as an identifier when logging information about the+ * given {@link file}. The returned string contains the file name (for ease of+ * debugging) and the file ID (for exactness).+ */+export const fileLogID = (file: EnteFile) =>+ `file ${fileFileName(file)} (${file.id})`;diff --git a/web/apps/albums/vendor/ente-media/formats.ts b/web/apps/albums/vendor/ente-media/formats.tsnew file mode 100644index 0000000000..c2a98ca635--- /dev/null+++ b/web/apps/albums/vendor/ente-media/formats.ts@@ -0,0 +1,35 @@+/**+ * List used by {@link needsJPEGConversion}.+ */+const needsJPEGConversionExtensions = [+ "arw",+ "cr2",+ "cr3",+ "dng",+ "heic",+ "jp2",+ "nef",+ "psd",+ "rw2",+ "tif",+ "tiff",+];++/**+ * Return `true` if {@link extension} is from amongst a known set of image file+ * extensions that (a) we know that the browser is unlikely to support, and (b)+ * which we should be able to convert to JPEG when running in our desktop app.+ *+ * These two are independent constraints, but we only return true if we satisfy+ * both of them instead of having two disjoint lists.+ */+export const needsJPEGConversion = (extension: string) =>+ needsJPEGConversionExtensions.includes(extension.toLowerCase());++/**+ * Return `true` if {@link extension} in for an HEIC-like file.+ */+export const isHEICExtension = (extension: string) => {+ const ext = extension.toLowerCase();+ return ext == "heic" || ext == "heif";+};diff --git a/web/apps/albums/vendor/ente-media/heic-convert.ts b/web/apps/albums/vendor/ente-media/heic-convert.tsnew file mode 100644index 0000000000..2eb561a6cb--- /dev/null+++ b/web/apps/albums/vendor/ente-media/heic-convert.ts@@ -0,0 +1,27 @@+import { ComlinkWorker } from "ente-base/worker/comlink-worker";+import type { HEICConvertWorker } from "./heic-convert.worker";++/**+ * Convert a HEIC image to a JPEG.+ *+ * Behind the scenes, it uses a web worker to do the conversion using a Wasm+ * HEIC conversion package.+ *+ * @param heicBlob The HEIC blob to convert.+ *+ * @returns The JPEG blob.+ */+export const heicToJPEG = async (heicBlob: Blob) =>+ worker().then((w) => w.heicToJPEG(heicBlob));++/** Cached instance of the {@link ComlinkWorker} that wraps our web worker. */+let _comlinkWorker: ComlinkWorker<typeof HEICConvertWorker> | undefined;++/** Lazily created, cached, instance of our web worker. */+const worker = async () => (_comlinkWorker ??= createComlinkWorker()).remote;++const createComlinkWorker = () =>+ new ComlinkWorker<typeof HEICConvertWorker>(+ "heic-convert-worker",+ new Worker(new URL("heic-convert.worker.ts", import.meta.url)),+ );diff --git a/web/apps/albums/vendor/ente-media/heic-convert.worker.ts b/web/apps/albums/vendor/ente-media/heic-convert.worker.tsnew file mode 100644index 0000000000..6ab4283fe7--- /dev/null+++ b/web/apps/albums/vendor/ente-media/heic-convert.worker.ts@@ -0,0 +1,37 @@+import { expose } from "comlink";+import { logUnhandledErrorsAndRejectionsInWorker } from "ente-base/log-web";+import { wait } from "ente-utils/promise";+import HeicConvert from "heic-convert";++export class HEICConvertWorker {+ /**+ * Convert a HEIC file to a JPEG file.+ *+ * Both the input and output are blobs.+ */+ async heicToJPEG(heicBlob: Blob) {+ const output = await heicToJPEG(heicBlob);+ // I'm told this library used to have big memory spikes, and adding+ // pauses to get GC to run helped. This might just be superstition tho.+ await wait(10 /* ms */);+ return output;+ }+}++expose(HEICConvertWorker);++logUnhandledErrorsAndRejectionsInWorker();++const heicToJPEG = async (heicBlob: Blob): Promise<Blob> => {+ const buffer = new Uint8Array(await heicBlob.arrayBuffer());+ // [Note: Revisit some Node.js types errors post 22 upgrade]+ //+ // Going beyond "typescript" "5.6.3" we start seeing a type error here. This+ // is possibly fixed in the newer Node.js types, but we're at 20 currently.+ //+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ // @ts-ignore+ const result = await HeicConvert({ buffer, format: "JPEG" });+ const convertedData = new Uint8Array(result);+ return new Blob([convertedData], { type: "image/jpeg" });+};diff --git a/web/apps/albums/vendor/ente-media/image.ts b/web/apps/albums/vendor/ente-media/image.tsnew file mode 100644index 0000000000..2912af02a4--- /dev/null+++ b/web/apps/albums/vendor/ente-media/image.ts@@ -0,0 +1,33 @@+/**+ * Compute optimal dimensions for a resized version of an image while+ * maintaining aspect ratio of the source image.+ *+ * @param width The width of the source image.+ *+ * @param height The height of the source image.+ *+ * @param maxDimension The maximum width of height of the resized image.+ *+ * This function returns a new size limiting it to maximum width and height+ * (both specified by {@link maxDimension}), while maintaining aspect ratio of+ * the source {@link width} and {@link height}.+ *+ * It returns `{0, 0}` for invalid inputs.+ */+export const scaledImageDimensions = (+ width: number,+ height: number,+ maxDimension: number,+): { width: number; height: number } => {+ if (width == 0 || height == 0) return { width: 0, height: 0 };+ const widthScaleFactor = maxDimension / width;+ const heightScaleFactor = maxDimension / height;+ const scaleFactor = Math.min(widthScaleFactor, heightScaleFactor);+ const resizedDimensions = {+ width: Math.round(width * scaleFactor),+ height: Math.round(height * scaleFactor),+ };+ if (resizedDimensions.width == 0 || resizedDimensions.height == 0)+ return { width: 0, height: 0 };+ return resizedDimensions;+};diff --git a/web/apps/albums/vendor/ente-media/live-photo.ts b/web/apps/albums/vendor/ente-media/live-photo.tsnew file mode 100644index 0000000000..4830e23bd5--- /dev/null+++ b/web/apps/albums/vendor/ente-media/live-photo.ts@@ -0,0 +1,142 @@+import {+ fileNameFromComponents,+ lowercaseExtension,+ nameAndExtension,+} from "ente-base/file-name";+import JSZip from "jszip";+import { FileType } from "./file-type";++const potentialImageExtensions = [+ "heic",+ "heif",+ "jpeg",+ "jpg",+ "png",+ "gif",+ "bmp",+ "tiff",+ "webp",+];++const potentialVideoExtensions = [+ "mov",+ "mp4",+ "m4v",+ "avi",+ "wmv",+ "flv",+ "mkv",+ "webm",+ "3gp",+ "3g2",+ "avi",+ "ogv",+ "mpg",+ "mp",+];++/**+ * Use the file extension of the given {@link fileName} to deduce if is is+ * potentially the image or the video part of a Live Photo.+ */+export const potentialFileTypeFromExtension = (+ fileName: string,+): FileType | undefined => {+ const ext = lowercaseExtension(fileName);+ if (!ext) return undefined;++ if (potentialImageExtensions.includes(ext)) return FileType.image;+ else if (potentialVideoExtensions.includes(ext)) return FileType.video;+ else return undefined;+};++/**+ * An in-memory representation of a live photo.+ */+interface LivePhoto {+ imageFileName: string;+ imageData: Uint8Array;+ videoFileName: string;+ videoData: Uint8Array;+}++/**+ * Convert a binary serialized representation of a live photo to an in-memory+ * {@link LivePhoto}.+ *+ * A live photo is a zip file containing two files - an image and a video. This+ * functions reads that zip file (blob), and return separate bytes (and+ * filenames) for the image and video parts.+ *+ * @param fileName The name of the overall live photo. Both the image and video+ * parts of the decompressed live photo use this as their name, combined with+ * their original extensions.+ *+ * @param zipBlob A blob contained the zipped data (i.e. the binary serialized+ * live photo).+ */+export const decodeLivePhoto = async (+ fileName: string,+ zipBlob: Blob,+): Promise<LivePhoto> => {+ let imageFileName, videoFileName: string | undefined;+ let imageData, videoData: Uint8Array | undefined;++ const [name] = nameAndExtension(fileName);+ const zip = await JSZip.loadAsync(zipBlob, { createFolders: true });++ for (const zipFileName in zip.files) {+ if (zipFileName.startsWith("image")) {+ const [, imageExt] = nameAndExtension(zipFileName);+ imageFileName = fileNameFromComponents([name, imageExt]);+ imageData = await zip.files[zipFileName]?.async("uint8array");+ } else if (zipFileName.startsWith("video")) {+ const [, videoExt] = nameAndExtension(zipFileName);+ videoFileName = fileNameFromComponents([name, videoExt]);+ videoData = await zip.files[zipFileName]?.async("uint8array");+ }+ }++ if (!imageFileName || !imageData)+ throw new Error(+ `Decoded live photo ${fileName} does not have an image`,+ );++ if (!videoFileName || !videoData)+ throw new Error(`Decoded live photo ${fileName} does not have a video`);++ return { imageFileName, imageData, videoFileName, videoData };+};++/** Variant of {@link LivePhoto}, but one that allows files and data. */+interface EncodeLivePhotoInput {+ imageFileName: string;+ imageFileOrData: File | Uint8Array;+ videoFileName: string;+ videoFileOrData: File | Uint8Array;+}++/**+ * Return a binary serialized representation of a live photo.+ *+ * This function takes the (in-memory) image and video data from the+ * {@link livePhoto} object, writes them to a zip file (using the respective+ * filenames), and returns the {@link Uint8Array} that represent the bytes of+ * this zip file.+ *+ * @param livePhoto The in-mem photo to serialized.+ */+export const encodeLivePhoto = async ({+ imageFileName,+ imageFileOrData,+ videoFileName,+ videoFileOrData,+}: EncodeLivePhotoInput) => {+ const [, imageExt] = nameAndExtension(imageFileName);+ const [, videoExt] = nameAndExtension(videoFileName);++ const zip = new JSZip();+ zip.file(fileNameFromComponents(["image", imageExt]), imageFileOrData);+ zip.file(fileNameFromComponents(["video", videoExt]), videoFileOrData);+ return await zip.generateAsync({ type: "uint8array" });+};diff --git a/web/apps/albums/vendor/ente-media/magic-metadata.ts b/web/apps/albums/vendor/ente-media/magic-metadata.tsnew file mode 100644index 0000000000..74bc85219d--- /dev/null+++ b/web/apps/albums/vendor/ente-media/magic-metadata.ts@@ -0,0 +1,228 @@+import { decryptMetadataJSON, encryptMetadataJSON } from "ente-base/crypto";+import { nullishToZero } from "ente-utils/transform";+import { z } from "zod";++/**+ * Zod schema of the mutable metadatum objects that we send to or receive from+ * remote. It contains an encrypted metadata JSON object with some bookkeeping+ * information attached.+ *+ * See {@link RemoteMagicMetadata} for the corresponding type.+ */+export const RemoteMagicMetadata = z.object({+ version: z.number(),+ count: z.number().nullish().transform(nullishToZero),+ data: z.string(),+ header: z.string(),+});++/**+ * The type of the mutable metadata fields, as represented by remote.+ *+ * See: [Note: Metadatum]+ *+ * This is the magic metadata that we send to and receive from remote. It+ * contains an encrypted JSON object, and a version + count of entries to ensure+ * that clients do not overwrite already applied updates with stale objects.+ *+ * When decrypt these into specific local {@link MagicMetadata} instantiations+ * before using and storing them on the client.+ */+export interface RemoteMagicMetadata {+ /**+ * Monotonically increasing iteration of this metadata object.+ *+ * The version starts at 1. Remote increments this version number each time+ * a client updates the corresponding magic metadata field.+ */+ version: number;+ /**+ * The number of keys with non-nullish (i.e. not null and not undefined)+ * values in the encrypted JSON object that the encrypted metadata blob+ * contains.+ *+ * [Note: Magic metadata data cannot have nullish values]+ *+ * Clients are expected to retain the magic metadata verbatim so that they+ * don't accidentally overwrite fields that they might not understand. See:+ * [Note: Use looseObject for metadata Zod schemas]+ *+ * Remote enforces this by requiring that during edits and updates, this+ * number should be greater than or equal to the previous version.+ *+ * Locally we enforce this in the {@link createMagicMetadata} function+ * (which is used for both creation and updates), which trims off any+ * entries in the data object whose value is `null` or `undefined` before+ * arriving at the final object to use.+ *+ * This has the side effect that metadata entries cannot be deleted by+ * setting their value to nullish. However usually the specific field+ * semantics allow a reset to default behaviour by setting the value of the+ * entry to the corresponding empty primitive (e.g. 0).+ */+ count: number;+ /**+ * The encrypted data.+ *+ * This are the base64 encoded bytes of the encrypted magic metadata JSON+ * object.+ *+ * The encryption will happen using the "key" associated with the object+ * whose magic metadata field this is. For example, if this is the+ * {@link pubMagicMetadata} of an {@link EnteFile}, then the file's key will+ * be used for encryption and decryption.+ */+ data: string;+ /**+ * The base64 encoded decryption header that will be needed for the client+ * for decrypting {@link data}.+ */+ header: string;+}++/**+ * The decrypted form of {@link RemoteMagicMetadata} used and locally persisted+ * by the client.+ *+ * The bookkeeping fields ({@link version} and {@link count}) are copied over+ * from the remote object ({@link RemoteMagicMetadata}), while the encrypted+ * contents ({@link data} and {@link header} of {@link RemoteMagicMetadata}) are+ * decrypted into a JSON object that is stored as {@link data}.+ *+ * Since different types of magic metadata fields are expected to contain+ * different JSON objects as {@link data}, the type is generic, with the generic+ * parameter `T` standing for the type of the JSON object.+ *+ * > Since TypeScript does not currently have a native JSON type, this T doesn't+ * > have other constraints enforced by the type system, but it is meant to be a+ * > JSON object.+ *+ * The word "magic metadata" by itself ambiguous. It refers to both the specific+ * "magicMetadata" fields present in, say, the file and collection objects, and+ * also to the shape of the structure this field shares with other semantically+ * similar fields (e.g. public magic metadata). This type uses it in the second+ * sense - to describe the shape of any of the magic metadata like fields used+ * in various types. See: [Note: Metadatum].+ */+export interface MagicMetadata<T = unknown> {+ version: number;+ count: number;+ /**+ * The "metadata" itself.+ *+ * This is expected to be a JSON object, whose exact schema depends on the+ * magic metadata field in the parent object.+ */+ data: T;+}++/**+ * Encrypt the provided magic metadata into a form that can be used in+ * communication with remote, trimming the JSON object and updating the count.+ *+ * @param magicMetadata The decrypted {@link MagicMetadata} that is being used+ * by the client.+ *+ * Any entries in {@link magicMetadata}'s {@link data} that are `null` or+ * `undefined` are discarded before obtaining the final object that will be+ * encrypted (and whose count will be used).+ *+ * So in particular, it is okay for the count in the {@link magicMetadata} to be+ * out of sync with the count in the `data` JSON object because this function+ * will recompute the count using the trimmed JSON object.+ *+ * @param key The base64 encoded key to use for encrypting the {@link data}+ * contents of {@link magicMetadata}.+ *+ * The specific key used depends on the object whose magic metadata field this+ * is meant for. For example, if this were the {@link pubMagicMetadata}+ * associated with an {@link EnteFile}, then this would be the file's key.+ *+ * @returns a {@link RemoteMagicMetadata} object that contains the encrypted+ * contents of the {@link data} present in the provided {@link magicMetadata}.+ * The {@link version} is copied over from the provided {@link magicMetadata},+ * while the {@link count} is obtained from the number of entries in the trimmed+ * JSON object that was encrypted.+ */+export const encryptMagicMetadata = async (+ magicMetadata: MagicMetadata,+ key: string,+): Promise<RemoteMagicMetadata> => {+ const { version } = magicMetadata;++ const newMM = createMagicMetadata(magicMetadata.data);+ const { count } = newMM;++ const { encryptedData: data, decryptionHeader: header } =+ await encryptMetadataJSON(newMM.data, key);++ return { version, count, data, header };+};++/**+ * A function to wrap an arbitrary JSON object in the {@link MagicMetadata}+ * envelope used for the various magic metadata fields.+ *+ * A trimmed JSON object is obtained from the provided JSON object by removing+ * any entries whose values is nullish (`null` or `undefined`).+ *+ * Then,+ *+ * - The `version` is set to provided value (or 1).+ * - The `count` is set to the number of entries in the trimmed JSON object.+ * - The `data` is set to the trimmed JSON object.+ *+ * {@link encryptMagicMetadata} internally uses this function to obtain an+ * trimmed `data` and its corresponding `count`. This function is also exported+ * for use in places where we just have a JSON object and would like to a new+ * {@link MagicMetadata} object to house it from scratch.+ *+ * @param data A JSON object. Since TypeScript does not have a JSON type, this+ * uses the `unknown` type.+ *+ * @param version An optional version number to use. This is useful when+ * updating existing magic metadata, where the version in the update that we+ * send to remote must match the existing version.+ *+ * If not provided, the 1 is used as the version.+ */+export const createMagicMetadata = (data: unknown, version?: number) => {+ // Discard any entries that with nullish (`null` or `undefined`) values.+ //+ // See: [Note: Magic metadata data cannot have nullish values]+ const jsonObject = Object.fromEntries(+ Object.entries(data ?? {}).filter(+ ([, v]) => v !== null && v !== undefined,+ ),+ );++ const count = Object.keys(jsonObject).length;++ return { version: version ?? 1, count, data: jsonObject };+};++/**+ * Decrypt the magic metadata received from remote into an object suitable for+ * use and persistence by the client.+ *+ * This is meant as the inverse of {@link encryptMagicMetadata}, see that+ * function's documentation for details.+ */+export const decryptMagicMetadata = async (+ remoteMagicMetadata: RemoteMagicMetadata,+ key: string,+): Promise<MagicMetadata> => {+ const {+ version,+ count,+ data: encryptedData,+ header: decryptionHeader,+ } = remoteMagicMetadata;++ const data = await decryptMetadataJSON(+ { encryptedData, decryptionHeader },+ key,+ );++ return { version, count, data };+};diff --git a/web/apps/albums/vendor/ente-new/albums/components/UploaderNameInput.tsx b/web/apps/albums/vendor/ente-new/albums/components/UploaderNameInput.tsxnew file mode 100644index 0000000000..78cf0a94e2--- /dev/null+++ b/web/apps/albums/vendor/ente-new/albums/components/UploaderNameInput.tsx@@ -0,0 +1,381 @@+import { User03Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import CloseIcon from "@mui/icons-material/Close";+import {+ Box,+ Button,+ Dialog,+ IconButton,+ styled,+ TextField,+ Typography,+} from "@mui/material";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import log from "ente-base/log";+import { useFormik } from "formik";+import { t } from "i18next";+import React from "react";++// =============================================================================+// Sparkle Icons+// =============================================================================++const SparkleTopRight: React.FC = () => (+ <svg+ width="14"+ height="16"+ viewBox="0 0 20 22"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ style={{ position: "absolute", top: 0, right: 8 }}+ >+ <path+ d="M19.728 9.21189C15.334 9.91374 11.912 12.6353 11.37 16.3181C11.912 12.6353 9.421 9.04853 5.4114 7.10627C9.806 6.40442 13.228 3.68284 13.77 7.55054e-05C13.228 3.68284 15.719 7.26962 19.728 9.21189Z"+ fill="#08C225"+ />+ </svg>+);++const SparkleBottomRight: React.FC = () => (+ <svg+ width="22"+ height="26"+ viewBox="0 0 32 36"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ style={{ position: "absolute", bottom: 0, right: -8 }}+ >+ <path+ d="M31.579 17.9746C23.591 18.7003 17.114 23.1692 15.689 29.722C17.114 23.1692 13.077 16.4145 6.1117 12.438C14.099 11.7122 20.576 7.2434 22.001 0.6902C20.576 7.2434 24.613 13.9981 31.579 17.9746Z"+ fill="#08C225"+ />+ </svg>+);++const SparkleBottomLeft: React.FC = () => (+ <svg+ width="18"+ height="16"+ viewBox="0 0 26 22"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ style={{ position: "absolute", bottom: 8, left: -8 }}+ >+ <path+ d="M25.9639 10.8477C19.9399 13.182 15.9104 18.0874 16.263 23.48C15.9104 18.0874 11.2832 13.7544 4.99991 12.2184C11.0238 9.884 15.0533 4.9787 14.7007 -0.4139C15.0533 4.9787 19.6805 9.3117 25.9639 10.8477Z"+ fill="#08C225"+ />+ </svg>+);++// =============================================================================+// Types+// =============================================================================++type UploaderNameInputProps = ModalVisibilityProps & {+ /**+ * The existing uploader name to prefill.+ */+ uploaderName: string;+ /**+ * Count of the number of files that the uploader is trying to upload.+ */+ uploadFileCount: number;+ /**+ * Callback invoked when the user presses submit after entering a name.+ */+ onSubmit: (name: string) => void | Promise<void>;+};++/**+ * A dialog asking the uploader to a public album to provide their name so that+ * other folks can know who uploaded a given photo in the shared album.+ */+export const UploaderNameInput: React.FC<UploaderNameInputProps> = ({+ open,+ onClose,+ uploaderName,+ uploadFileCount,+ onSubmit,+}) => {+ return (+ <StyledDialog open={open} onClose={onClose}>+ <DialogWrapper>+ <CloseButton onClick={onClose}>+ <CloseIcon sx={{ fontSize: 20 }} />+ </CloseButton>++ <ContentContainer>+ <IllustrationContainer>+ <SparkleTopRight />+ <SparkleBottomRight />+ <SparkleBottomLeft />+ <IllustrationWrapper>+ <HugeiconsIcon+ icon={User03Icon}+ size={28}+ color="#fff"+ strokeWidth={1.8}+ />+ </IllustrationWrapper>+ </IllustrationContainer>++ <TitleSection>+ <Title>{t("enter_name")}</Title>+ <Subtitle>{t("uploader_name_hint")}</Subtitle>+ </TitleSection>++ <UploaderNameInputForm+ {...{+ onClose,+ uploaderName,+ uploadFileCount,+ onSubmit,+ }}+ />+ </ContentContainer>+ </DialogWrapper>+ </StyledDialog>+ );+};++/**+ * The form that obtains the textual input of the uploader name.+ *+ * It is kept as a separate component so that it gets recreated on prop changes+ * (e.g. uploaderName changes).+ */+export const UploaderNameInputForm: React.FC<+ Omit<UploaderNameInputProps, "open">+> = ({ onClose, uploaderName, uploadFileCount, onSubmit }) => {+ const formik = useFormik({+ initialValues: { value: uploaderName },+ onSubmit: async (values, { setFieldError }) => {+ const value = values.value;+ const setValueFieldError = (message: string) =>+ setFieldError("value", message);++ if (!value) {+ setValueFieldError(t("required"));+ return;+ }+ try {+ await onSubmit(value);+ onClose();+ } catch (e) {+ log.error(`Failed to submit input ${value}`, e);+ setValueFieldError(t("generic_error"));+ }+ },+ });++ return (+ <FormContainer onSubmit={formik.handleSubmit}>+ <StyledTextField+ name="value"+ value={formik.values.value}+ onChange={formik.handleChange}+ type="text"+ variant="standard"+ fullWidth+ autoFocus+ hiddenLabel+ aria-label={t("name")}+ placeholder={t("name_placeholder")}+ disabled={formik.isSubmitting}+ error={!!formik.errors.value}+ helperText={formik.errors.value}+ />+ <ButtonsSection>+ <SubmitButton+ type="submit"+ variant="contained"+ disabled={+ formik.isSubmitting || !formik.values.value.trim()+ }+ hasName={!!formik.values.value.trim()}+ >+ {formik.isSubmitting+ ? t("loading")+ : t("add_photos_count", { count: uploadFileCount })}+ </SubmitButton>+ </ButtonsSection>+ </FormContainer>+ );+};++// =============================================================================+// Styled Components+// =============================================================================++const StyledDialog = styled(Dialog)(({ theme }) => ({+ "& .MuiDialog-paper": {+ width: 381,+ maxWidth: "calc(100% - 32px)",+ borderRadius: 28,+ backgroundColor: "#fff",+ padding: 0,+ margin: 16,+ overflow: "visible",+ boxShadow: "none",+ border: "1px solid #E0E0E0",+ ...theme.applyStyles("dark", {+ backgroundColor: "#1b1b1b",+ border: "1px solid rgba(255, 255, 255, 0.18)",+ }),+ },+ "& .MuiBackdrop-root": { backgroundColor: "rgba(0, 0, 0, 0.5)" },+}));++const DialogWrapper = styled(Box)(() => ({+ position: "relative",+ padding: "48px 16px 16px 16px",+}));++const CloseButton = styled(IconButton)(({ theme }) => ({+ position: "absolute",+ top: 11,+ right: 12,+ backgroundColor: "#FAFAFA",+ color: "#000",+ padding: 10,+ "&:hover": { backgroundColor: "#F0F0F0" },+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.12)",+ color: "#fff",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.16)" },+ }),+}));++const ContentContainer = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 16,+}));++const IllustrationContainer = styled(Box)(() => ({+ position: "relative",+ width: 100,+ height: 70,+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ marginBottom: 8,+}));++const IllustrationWrapper = styled(Box)(() => ({+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ width: 52,+ height: 52,+ borderRadius: "50%",+ backgroundColor: "#08C225",+}));++const TitleSection = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 9,+ textAlign: "center",+ marginBottom: 8,+}));++const Title = styled(Typography)(({ theme }) => ({+ fontWeight: 600,+ fontSize: 24,+ lineHeight: "28px",+ letterSpacing: "-0.48px",+ color: "#000",+ ...theme.applyStyles("dark", { color: "#fff" }),+}));++const Subtitle = styled(Typography)(({ theme }) => ({+ fontWeight: 500,+ fontSize: 14,+ lineHeight: "20px",+ color: "#666666",+ maxWidth: "75%",+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.7)" }),+}));++const FormContainer = styled("form")(() => ({+ width: "100%",+ display: "flex",+ flexDirection: "column",+ gap: 16,+}));++const StyledTextField = styled(TextField)(({ theme }) => ({+ "& .MuiInput-root": {+ height: 54,+ backgroundColor: "#FAFAFA",+ borderRadius: 12,+ "&::before": { borderBottom: "1px solid #E0E0E0" },+ "&::after": { borderBottom: "2px solid #08C225" },+ "&:hover:not(.Mui-disabled)::before": {+ borderBottom: "1px solid #BDBDBD",+ },+ },+ "& .MuiInputBase-input": {+ padding: "0 16px",+ height: "100%",+ boxSizing: "border-box",+ fontSize: 16,+ color: "#000",+ "&::placeholder": { color: "#999", opacity: 1 },+ },+ ...theme.applyStyles("dark", {+ "& .MuiInput-root": {+ backgroundColor: "rgba(255, 255, 255, 0.08)",+ "&::before": { borderBottom: "1px solid rgba(255, 255, 255, 0.3)" },+ "&:hover:not(.Mui-disabled)::before": {+ borderBottom: "1px solid rgba(255, 255, 255, 0.5)",+ },+ },+ "& .MuiInputBase-input": {+ color: "#fff",+ "&::placeholder": { color: "rgba(255, 255, 255, 0.5)" },+ },+ }),+}));++const ButtonsSection = styled(Box)(() => ({+ width: "100%",+ display: "flex",+ flexDirection: "row",+ gap: 12,+}));++const SubmitButton = styled(Button)<{ hasName: boolean }>(+ ({ hasName, theme }) => ({+ display: "flex",+ padding: "16px",+ justifyContent: "center",+ alignItems: "center",+ gap: 8,+ flex: 1,+ borderRadius: 20,+ backgroundColor: hasName ? "#08C225" : "rgba(0, 0, 0, 0.04)",+ fontSize: 16,+ fontWeight: 500,+ textTransform: "none",+ color: hasName ? "#fff" : "#999",+ boxShadow: "none",+ "&:hover": {+ backgroundColor: hasName ? "#07A820" : "rgba(0, 0, 0, 0.08)",+ boxShadow: "none",+ },+ ...theme.applyStyles("dark", {+ backgroundColor: hasName ? "#08C225" : "rgba(255, 255, 255, 0.08)",+ color: hasName ? "#fff" : "rgba(255, 255, 255, 0.5)",+ "&:hover": {+ backgroundColor: hasName+ ? "#07A820"+ : "rgba(255, 255, 255, 0.12)",+ },+ }),+ }),+);diff --git a/web/apps/albums/vendor/ente-new/albums/services/public-albums-fdb.ts b/web/apps/albums/vendor/ente-new/albums/services/public-albums-fdb.tsnew file mode 100644index 0000000000..82b6ff5e13--- /dev/null+++ b/web/apps/albums/vendor/ente-new/albums/services/public-albums-fdb.ts@@ -0,0 +1,306 @@+/**+ * @file Public albums app specific files DB. See: [Note: Files DB].+ */++import {+ LocalCollections,+ LocalEnteFiles,+ localForage,+ LocalTimestamp,+ transformFilesIfNeeded,+} from "ente-gallery/services/files-db";+import { type Collection } from "ente-media/collection";+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> =>+ savedPublicCollections().then((cs) =>+ 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([+ collection,+ ...collections.filter((c) => c.id != collection.id),+ ]);+};++/**+ * 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([+ ...collections.filter((c) => c.key != collectionKey),+ ]);+};++/**+ * 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,+) => {+ await localForage.setItem("public-referral-code", referralCode);+};++const LocalSavedPublicCollectionFilesEntry = z.object({+ /**+ * The collection, identified by its access token.+ *+ * See: [Note: Public album access token]+ */+ collectionUID: z.string(),+ files: LocalEnteFiles,+});++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[]> => {+ const entry = (await pcfEntries()).find(+ (e) => e.collectionUID == accessToken,+ );+ 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.+ 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[],+): Promise<void> => {+ await localForage.setItem("public-collection-files", [+ { collectionUID: accessToken, files },+ ...(await pcfEntries()).filter((e) => e.collectionUID != accessToken),+ ]);+};++/**+ * 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> => {+ await localForage.setItem("public-collection-files", [+ ...(await pcfEntries()).filter((e) => e.collectionUID != accessToken),+ ]);+};++/**+ * 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,+) => {+ 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,+) =>+ LocalString.parse(+ 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,+) => {+ 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,+) => {+ await localForage.removeItem(`public-${accessToken}-passkey`);+};++/**+ * 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,+) => {+ await localForage.setItem(+ `public-${accessToken}-uploaderName`,+ uploaderName,+ );+};diff --git a/web/apps/albums/vendor/ente-new/albums/services/public-collection.ts b/web/apps/albums/vendor/ente-new/albums/services/public-collection.tsnew file mode 100644index 0000000000..a6af813495--- /dev/null+++ b/web/apps/albums/vendor/ente-new/albums/services/public-collection.ts@@ -0,0 +1,265 @@+import { deriveKey } from "ente-base/crypto";+import {+ authenticatedPublicAlbumsRequestHeaders,+ ensureOk,+ type PublicAlbumsCredentials,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import {+ decryptRemoteCollection,+ RemoteCollection,+ type Collection,+ type PublicURL,+} from "ente-media/collection";+import {+ decryptRemoteFile,+ FileDiffResponse,+ type EnteFile,+} from "ente-media/file";+import { z } from "zod";+import {+ removePublicCollectionAccessTokenJWT,+ removePublicCollectionFiles,+ removePublicCollectionLastSyncTime,+ savedPublicCollectionFiles,+ savedPublicCollectionLastSyncTime,+ saveLastPublicCollectionReferralCode,+ savePublicCollection,+ savePublicCollectionFiles,+ savePublicCollectionLastSyncTime,+} from "./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,+ accessToken: string,+) => {+ const passwordHash = await deriveKey(+ password,+ // TODO: Fix the types to not require the bang.+ publicURL.nonce!,+ publicURL.opsLimit!,+ publicURL.memLimit!,+ );++ const res = await fetch(+ await apiURL("/public-collection/verify-password"),+ {+ method: "POST",+ headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),+ body: JSON.stringify({ passHash: passwordHash }),+ },+ );+ ensureOk(res);+ 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 "t="+ * query parameter of the public URL.+ *+ * 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 (+ accessToken: string,+ collectionKey: string,+): Promise<{ collection: Collection; referralCode: string }> => {+ const { collection: remoteCollection, referralCode } =+ await getPublicCollectionInfo(accessToken);++ const collection = await decryptRemoteCollection(+ remoteCollection,+ collectionKey,+ );++ await savePublicCollection(collection);+ await saveLastPublicCollectionReferralCode(referralCode);++ return { collection, referralCode };+};++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 (accessToken: string) => {+ const res = await fetch(await apiURL("/public-collection/info"), {+ headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),+ });+ ensureOk(res);+ return PublicCollectionInfo.parse(await res.json());+};++/**+ * 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,+ 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).+ if (sinceTime == collection.updationTime) return;++ const files = await savedPublicCollectionFiles(accessToken);+ const filesByID = new Map(files.map((f) => [f.id, f]));+ let callbackInvoked = false;++ while (true) {+ const { diff, hasMore } = await getPublicCollectionDiff(+ credentials,+ 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)+ if (!callbackInvoked) {+ onSetFiles(files);+ }+ break;+ }+ for (const change of diff) {+ sinceTime = Math.max(sinceTime, change.updationTime);+ if (change.isDeleted) {+ filesByID.delete(change.id);+ } else {+ filesByID.set(+ change.id,+ await decryptRemoteFile(change, collection.key),+ );+ }+ }++ const updatedFiles = [...filesByID.values()];+ await savePublicCollectionFiles(accessToken, updatedFiles);+ await savePublicCollectionLastSyncTime(accessToken, sinceTime);+ onSetFiles(updatedFiles);+ callbackInvoked = true;++ if (!hasMore) break;+ }+};++/**+ * 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,+) => {+ const res = await fetch(+ await apiURL("/public-collection/diff", { sinceTime }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ 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),+ removePublicCollectionLastSyncTime(accessToken),+ removePublicCollectionFiles(accessToken),+ ]);+};diff --git a/web/apps/albums/vendor/ente-new/albums/services/public-comment.ts b/web/apps/albums/vendor/ente-new/albums/services/public-comment.tsnew file mode 100644index 0000000000..8fbbfde51b--- /dev/null+++ b/web/apps/albums/vendor/ente-new/albums/services/public-comment.ts@@ -0,0 +1,203 @@+import { decryptBox, encryptBox } from "ente-base/crypto";+import {+ authenticatedPublicAlbumsRequestHeaders,+ ensureOk,+ type PublicAlbumsCredentials,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { z } from "zod";+import { type AnonIdentity, getStoredAnonIdentity } from "./public-reaction";++/**+ * A decrypted public comment.+ */+export interface PublicComment {+ id: string;+ collectionID: number;+ fileID?: number;+ parentCommentID?: string;+ userID: number;+ anonUserID?: string;+ /** The decrypted comment text. */+ text: string;+ isDeleted: boolean;+ createdAt: number;+ updatedAt: number;+}++/**+ * Add a comment to a file in a public album (as an anonymous user).+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID for looking up stored identity.+ * @param fileID The ID of the file to comment on.+ * @param text The comment text.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @param parentCommentID Optional parent comment ID for replies.+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.+ * @returns The ID of the created comment.+ */+export const addPublicComment = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ fileID: number,+ text: string,+ collectionKey: string,+ parentCommentID?: string,+ anonIdentity?: AnonIdentity,+): Promise<string> => {+ const identity = anonIdentity ?? getStoredAnonIdentity(collectionID);+ if (!identity) {+ throw new Error("No anonymous identity available");+ }++ const { encryptedData: cipher, nonce } = await encryptBox(+ new TextEncoder().encode(text),+ collectionKey,+ );++ const res = await fetch(await apiURL("/public-collection/comments"), {+ method: "POST",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ fileID,+ cipher,+ nonce,+ parentCommentID,+ anonUserID: identity.anonUserID,+ anonToken: identity.token,+ }),+ });+ ensureOk(res);+ const { id } = CreateCommentResponse.parse(await res.json());+ return id;+};++/**+ * Delete a comment from a public album (as an anonymous user).+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID for looking up stored identity.+ * @param commentID The ID of the comment to delete.+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.+ */+export const deletePublicComment = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ commentID: string,+ anonIdentity?: AnonIdentity,+): Promise<void> => {+ const identity = anonIdentity ?? getStoredAnonIdentity(collectionID);+ if (!identity) {+ throw new Error("No anonymous identity available");+ }++ const res = await fetch(+ await apiURL(`/public-collection/comments/${commentID}`),+ {+ method: "DELETE",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ anonUserID: identity.anonUserID,+ anonToken: identity.token,+ }),+ },+ );+ ensureOk(res);+};++/**+ * Get comments for a file in a public album.+ *+ * @param credentials Public album credentials (access token).+ * @param fileID The ID of the file to get comments for.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Array of decrypted comments for the file.+ */+export const getPublicFileComments = async (+ credentials: PublicAlbumsCredentials,+ fileID: number,+ collectionKey: string,+): Promise<PublicComment[]> => {+ const res = await fetch(+ await apiURL("/public-collection/comments/diff", {+ fileID,+ sinceTime: 0,+ limit: 1000,+ }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ const { comments } = GetPublicCommentsResponse.parse(await res.json());++ const decryptedComments: PublicComment[] = [];+ for (const comment of comments) {+ // Include deleted comments with empty text+ if (comment.isDeleted || !comment.cipher || !comment.nonce) {+ decryptedComments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text: "",+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ });+ continue;+ }+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: comment.cipher, nonce: comment.nonce },+ collectionKey,+ );+ const text = new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ );+ decryptedComments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text,+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ });+ } catch {+ // Skip comments that fail to decrypt+ }+ }+ return decryptedComments;+};++const CreateCommentResponse = z.object({ id: z.string() });++const RemotePublicComment = z.object({+ id: z.string(),+ collectionID: z.number(),+ fileID: z.number().nullish(),+ parentCommentID: z.string().nullish(),+ userID: z.number(),+ anonUserID: z.string().nullish(),+ cipher: z.string().nullish(),+ nonce: z.string().nullish(),+ isDeleted: z.boolean(),+ createdAt: z.number(),+ updatedAt: z.number(),+});++const GetPublicCommentsResponse = z.object({+ comments: z.array(RemotePublicComment),+ hasMore: z.boolean(),+});diff --git a/web/apps/albums/vendor/ente-new/albums/services/public-reaction.ts b/web/apps/albums/vendor/ente-new/albums/services/public-reaction.tsnew file mode 100644index 0000000000..3eaffec009--- /dev/null+++ b/web/apps/albums/vendor/ente-new/albums/services/public-reaction.ts@@ -0,0 +1,781 @@+import { decryptBox, encryptBox } from "ente-base/crypto";+import {+ authenticatedPublicAlbumsRequestHeaders,+ ensureOk,+ type PublicAlbumsCredentials,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { z } from "zod";++/**+ * Fixed length for padded reaction types.+ * All reactions are padded to this length before encryption to prevent+ * length-based analysis of the ciphertext.+ * Max emoji name is ~70 chars, so 100 provides a safe buffer.+ */+const paddedReactionLength = 100;++/**+ * Pad a reaction type to a fixed length using null bytes.+ */+const padReaction = (reactionType: string): string =>+ reactionType.padEnd(paddedReactionLength, "\0");++/**+ * Remove null byte padding from a decrypted reaction type.+ */+const unpadReaction = (paddedReaction: string): string =>+ paddedReaction.replace(/\0+$/, "");++/**+ * Anonymous user identity returned when creating an anon identity.+ */+export interface AnonIdentity {+ anonUserID: string;+ token: string;+ expiresAt: number;+}++/**+ * Storage key prefix for anonymous identity in local storage.+ * The full key is `${prefix}_${collectionID}`.+ */+const ANON_IDENTITY_STORAGE_KEY_PREFIX = "ente_anon_identity";++/**+ * Get the storage key for a specific collection's anonymous identity.+ */+const getStorageKey = (collectionID: number): string =>+ `${ANON_IDENTITY_STORAGE_KEY_PREFIX}_${collectionID}`;++/**+ * Get the stored anonymous identity for a specific collection from local storage.+ *+ * Returns undefined if no identity is stored or if the stored identity has expired.+ * Expired identities are automatically cleared from storage.+ *+ * @param collectionID The collection ID to get the identity for.+ */+export const getStoredAnonIdentity = (+ collectionID: number,+): AnonIdentity | undefined => {+ if (typeof window === "undefined") return undefined;+ const stored = localStorage.getItem(getStorageKey(collectionID));+ if (!stored) return undefined;+ try {+ const identity = JSON.parse(stored) as AnonIdentity;+ // Check if the identity has expired.+ // Server returns expiresAt in microseconds, Date.now() returns milliseconds.+ const nowMicroseconds = Date.now() * 1000;+ if (identity.expiresAt && nowMicroseconds > identity.expiresAt) {+ // Clear expired identity so user can create a fresh one+ clearAnonIdentity(collectionID);+ return undefined;+ }+ return identity;+ } catch {+ return undefined;+ }+};++/**+ * Store the anonymous identity for a specific collection in local storage.+ *+ * @param collectionID The collection ID to store the identity for.+ * @param identity The anonymous identity to store.+ */+export const storeAnonIdentity = (+ collectionID: number,+ identity: AnonIdentity,+): void => {+ if (typeof window === "undefined") return;+ localStorage.setItem(getStorageKey(collectionID), JSON.stringify(identity));+};++/**+ * Clear the stored anonymous identity for a specific collection from local storage.+ *+ * @param collectionID The collection ID to clear the identity for.+ */+export const clearAnonIdentity = (collectionID: number): void => {+ if (typeof window === "undefined") return;+ localStorage.removeItem(getStorageKey(collectionID));+};++/**+ * Create an anonymous identity for a public album.+ *+ * The server will return a unique anonymous user ID and a token that can be+ * used to authenticate future requests (reactions, comments) from this+ * anonymous user.+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID this identity is for.+ * @param userName The name entered by the user.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns The anonymous identity containing anonUserID and token.+ */+export const createAnonIdentity = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ userName: string,+ collectionKey: string,+): Promise<AnonIdentity> => {+ // Encrypt the user name using the collection key+ const { encryptedData: cipher, nonce } = await encryptBox(+ new TextEncoder().encode(userName),+ collectionKey,+ );++ const res = await fetch(await apiURL("/public-collection/anon-identity"), {+ method: "POST",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ cipher, nonce }),+ });+ ensureOk(res);+ const identity = AnonIdentityResponse.parse(await res.json());++ // Store the identity for this collection+ storeAnonIdentity(collectionID, identity);++ return identity;+};++const AnonIdentityResponse = z.object({+ anonUserID: z.string(),+ token: z.string(),+ expiresAt: z.number(),+});++/**+ * Add a reaction to a file in a public album (as an anonymous user).+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID for looking up stored identity.+ * @param fileID The ID of the file to react to.+ * @param reactionType The type of reaction (e.g., "green_heart").+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.+ * @returns The ID of the created reaction.+ */+export const addPublicReaction = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ fileID: number,+ reactionType: string,+ collectionKey: string,+ anonIdentity?: AnonIdentity,+): Promise<string> => {+ const identity = anonIdentity ?? getStoredAnonIdentity(collectionID);+ if (!identity) {+ throw new Error("No anonymous identity available");+ }++ const { encryptedData: cipher, nonce } = await encryptBox(+ new TextEncoder().encode(padReaction(reactionType)),+ collectionKey,+ );++ const res = await fetch(await apiURL("/public-collection/reactions"), {+ method: "POST",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ fileID,+ cipher,+ nonce,+ anonUserID: identity.anonUserID,+ anonToken: identity.token,+ }),+ });+ ensureOk(res);+ const { id } = UpsertReactionResponse.parse(await res.json());+ return id;+};++/**+ * Add a reaction to a comment in a public album (as an anonymous user).+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID for looking up stored identity.+ * @param commentID The ID of the comment to react to.+ * @param reactionType The type of reaction (e.g., "green_heart").+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.+ * @param fileID Optional file ID, required for file-scoped comments.+ * @returns The ID of the created reaction.+ */+export const addPublicCommentReaction = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ commentID: string,+ reactionType: string,+ collectionKey: string,+ anonIdentity?: AnonIdentity,+ fileID?: number,+): Promise<string> => {+ const identity = anonIdentity ?? getStoredAnonIdentity(collectionID);+ if (!identity) {+ throw new Error("No anonymous identity available");+ }++ const { encryptedData: cipher, nonce } = await encryptBox(+ new TextEncoder().encode(padReaction(reactionType)),+ collectionKey,+ );++ const res = await fetch(await apiURL("/public-collection/reactions"), {+ method: "POST",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ commentID,+ fileID,+ cipher,+ nonce,+ anonUserID: identity.anonUserID,+ anonToken: identity.token,+ }),+ });+ ensureOk(res);+ const { id } = UpsertReactionResponse.parse(await res.json());+ return id;+};++/**+ * Delete a reaction from a public album (as an anonymous user).+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID for looking up stored identity.+ * @param reactionID The ID of the reaction to delete.+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.+ */+export const deletePublicReaction = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ reactionID: string,+ anonIdentity?: AnonIdentity,+): Promise<void> => {+ const identity = anonIdentity ?? getStoredAnonIdentity(collectionID);+ if (!identity) {+ throw new Error("No anonymous identity available");+ }++ const res = await fetch(+ await apiURL(`/public-collection/reactions/${reactionID}`),+ {+ method: "DELETE",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ anonUserID: identity.anonUserID,+ anonToken: identity.token,+ }),+ },+ );+ ensureOk(res);+};++const UpsertReactionResponse = z.object({ id: z.string() });++/**+ * A decrypted public reaction.+ */+export interface PublicReaction {+ id: string;+ fileID: number;+ commentID?: string;+ reactionType: string;+ userID: number;+ anonUserID?: string;+ isDeleted: boolean;+ createdAt: number;+ updatedAt: number;+}++/**+ * Get reactions for a file in a public album.+ *+ * @param credentials Public album credentials (access token).+ * @param fileID The ID of the file to get reactions for.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Array of decrypted reactions for the file.+ */+export const getPublicFileReactions = async (+ credentials: PublicAlbumsCredentials,+ fileID: number,+ collectionKey: string,+): Promise<PublicReaction[]> => {+ const res = await fetch(+ await apiURL("/public-collection/reactions/diff", {+ fileID,+ sinceTime: 0,+ limit: 100,+ }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ const { reactions } = GetPublicReactionsResponse.parse(await res.json());++ const decryptedReactions: PublicReaction[] = [];+ for (const reaction of reactions) {+ // Skip deleted reactions (they have null cipher/nonce)+ if (reaction.isDeleted || !reaction.cipher || !reaction.nonce) continue;+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: reaction.cipher, nonce: reaction.nonce },+ collectionKey,+ );+ const reactionType = unpadReaction(+ new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ ),+ );+ decryptedReactions.push({+ id: reaction.id,+ fileID: reaction.fileID ?? fileID,+ commentID: reaction.commentID ?? undefined,+ reactionType,+ userID: reaction.userID,+ anonUserID: reaction.anonUserID ?? undefined,+ isDeleted: reaction.isDeleted,+ createdAt: reaction.createdAt,+ updatedAt: reaction.updatedAt,+ });+ } catch {+ // Skip reactions that fail to decrypt+ }+ }+ return decryptedReactions;+};++const RemotePublicReaction = z.object({+ id: z.string(),+ collectionID: z.number(),+ fileID: z.number().nullish(),+ commentID: z.string().nullish(),+ userID: z.number(),+ anonUserID: z.string().nullish(),+ cipher: z.string().nullish(),+ nonce: z.string().nullish(),+ isDeleted: z.boolean(),+ createdAt: z.number(),+ updatedAt: z.number(),+});++const GetPublicReactionsResponse = z.object({+ reactions: z.array(RemotePublicReaction),+ hasMore: z.boolean(),+});++/**+ * An anonymous user profile (encrypted).+ */+export interface AnonProfile {+ anonUserID: string;+ userName: string;+}++/**+ * Get anonymous user profiles for a public album.+ *+ * @param credentials Public album credentials (access token).+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Map of anonUserID to decrypted userName.+ */+export const getPublicAnonProfiles = async (+ credentials: PublicAlbumsCredentials,+ collectionKey: string,+): Promise<Map<string, string>> => {+ const res = await fetch(await apiURL("/public-collection/anon-profiles"), {+ headers: authenticatedPublicAlbumsRequestHeaders(credentials),+ });+ ensureOk(res);+ const { profiles } = GetAnonProfilesResponse.parse(await res.json());++ const anonUserNames = new Map<string, string>();+ for (const profile of profiles) {+ if (!profile.cipher || !profile.nonce) continue;+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: profile.cipher, nonce: profile.nonce },+ collectionKey,+ );+ const userName = new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ );+ if (userName) {+ anonUserNames.set(profile.anonUserID, userName);+ }+ } catch {+ // Skip profiles that fail to decrypt+ }+ }+ return anonUserNames;+};++const RemoteAnonProfile = z.object({+ anonUserID: z.string(),+ collectionID: z.number(),+ cipher: z.string().nullish(),+ nonce: z.string().nullish(),+ createdAt: z.number(),+ updatedAt: z.number(),+});++const GetAnonProfilesResponse = z.object({+ profiles: z+ .array(RemoteAnonProfile)+ .nullish()+ .transform((v) => v ?? []),+});++/**+ * A participant with masked email.+ */+export interface Participant {+ userID: number;+ emailMasked: string;+}++/**+ * Get registered participants' masked emails for a public album.+ *+ * This returns masked emails for registered users (album owner/collaborators)+ * who have interacted with the album (comments/reactions).+ *+ * @param credentials Public album credentials (access token).+ * @returns Map of userID to masked email.+ */+export const getPublicParticipantsMaskedEmails = async (+ credentials: PublicAlbumsCredentials,+): Promise<Map<number, string>> => {+ const res = await fetch(+ await apiURL("/public-collection/participants/masked-emails"),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ const { participants } = GetParticipantsResponse.parse(await res.json());++ const userIDToEmail = new Map<number, string>();+ for (const participant of participants) {+ userIDToEmail.set(participant.userID, participant.emailMasked);+ }+ return userIDToEmail;+};++const RemoteParticipant = z.object({+ userID: z.number(),+ emailMasked: z.string(),+});++const GetParticipantsResponse = z.object({+ participants: z.array(RemoteParticipant),+});++// =============================================================================+// Unified Social Diff+// =============================================================================++/**+ * A decrypted public comment.+ */+export interface PublicComment {+ id: string;+ collectionID: number;+ fileID?: number;+ parentCommentID?: string;+ userID: number;+ anonUserID?: string;+ text: string;+ isDeleted: boolean;+ createdAt: number;+ updatedAt: number;+}++/**+ * Result of fetching unified social diff.+ */+export interface PublicSocialDiff {+ comments: PublicComment[];+ reactions: PublicReaction[];+}++/**+ * Get both comments and reactions for a file in a public album in a single API call.+ *+ * @param credentials Public album credentials (access token).+ * @param fileID The ID of the file to get social data for.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Object containing both decrypted comments and reactions.+ */+export const getPublicSocialDiff = async (+ credentials: PublicAlbumsCredentials,+ fileID: number,+ collectionKey: string,+): Promise<PublicSocialDiff> => {+ const res = await fetch(+ await apiURL("/public-collection/social/diff", {+ fileID,+ sinceTime: 0,+ limit: 1000,+ }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ const data = GetPublicSocialDiffResponse.parse(await res.json());++ // Decrypt comments+ const comments: PublicComment[] = [];+ for (const comment of data.comments) {+ // Include deleted comments with empty text+ if (comment.isDeleted || !comment.cipher || !comment.nonce) {+ comments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text: "",+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ });+ continue;+ }+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: comment.cipher, nonce: comment.nonce },+ collectionKey,+ );+ const text = new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ );+ comments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text,+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ });+ } catch {+ // Skip comments that fail to decrypt+ }+ }++ // Decrypt reactions+ const reactions: PublicReaction[] = [];+ for (const reaction of data.reactions) {+ // Skip deleted reactions (they have null cipher/nonce)+ if (reaction.isDeleted || !reaction.cipher || !reaction.nonce) continue;+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: reaction.cipher, nonce: reaction.nonce },+ collectionKey,+ );+ const reactionType = unpadReaction(+ new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ ),+ );+ reactions.push({+ id: reaction.id,+ fileID: reaction.fileID ?? fileID,+ commentID: reaction.commentID ?? undefined,+ reactionType,+ userID: reaction.userID,+ anonUserID: reaction.anonUserID ?? undefined,+ isDeleted: reaction.isDeleted,+ createdAt: reaction.createdAt,+ updatedAt: reaction.updatedAt,+ });+ } catch {+ // Skip reactions that fail to decrypt+ }+ }++ return { comments, reactions };+};++const RemotePublicComment = z.object({+ id: z.string(),+ collectionID: z.number(),+ fileID: z.number().nullish(),+ parentCommentID: z.string().nullish(),+ userID: z.number(),+ anonUserID: z.string().nullish(),+ cipher: z.string().nullish(),+ nonce: z.string().nullish(),+ isDeleted: z.boolean(),+ createdAt: z.number(),+ updatedAt: z.number(),+});++const GetPublicSocialDiffResponse = z.object({+ comments: z.array(RemotePublicComment),+ reactions: z.array(RemotePublicReaction),+ hasMoreComments: z.boolean(),+ hasMoreReactions: z.boolean(),+});++// =============================================================================+// Public Album Feed+// =============================================================================++/**+ * A public comment extended with isReply flag for feed processing.+ */+export interface PublicFeedComment extends PublicComment {+ /** True if this comment is a reply to another comment. */+ isReply: boolean;+}++/**+ * A public reaction extended with isCommentReply flag for feed processing.+ */+export interface PublicFeedReaction extends PublicReaction {+ /** True if this reaction is on a reply (comment with parent). */+ isCommentReply?: boolean;+}++/**+ * Result of fetching all social data for a public album feed.+ */+export interface PublicAlbumFeed {+ comments: PublicFeedComment[];+ reactions: PublicFeedReaction[];+}++/**+ * Get all comments and reactions for a public album (for the feed).+ *+ * Unlike getPublicSocialDiff which is per-file, this fetches ALL social data+ * for the entire album without filtering by file.+ *+ * @param credentials Public album credentials (access token).+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Object containing all decrypted comments and reactions for the album.+ */+export const getPublicAlbumFeed = async (+ credentials: PublicAlbumsCredentials,+ collectionKey: string,+): Promise<PublicAlbumFeed> => {+ // Fetch all social data without fileID filter+ const res = await fetch(+ await apiURL("/public-collection/social/diff", {+ sinceTime: 0,+ limit: 1000,+ }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ const data = GetPublicSocialDiffResponse.parse(await res.json());++ // Build a map of comment IDs to their parent status for determining isCommentReply+ const commentParentMap = new Map<string, boolean>();++ // Decrypt comments+ const comments: PublicFeedComment[] = [];+ for (const comment of data.comments) {+ const isReply = !!comment.parentCommentID;+ commentParentMap.set(comment.id, isReply);++ // Include deleted comments with empty text+ if (comment.isDeleted || !comment.cipher || !comment.nonce) {+ comments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text: "",+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ isReply,+ });+ continue;+ }+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: comment.cipher, nonce: comment.nonce },+ collectionKey,+ );+ const text = new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ );+ comments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text,+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ isReply,+ });+ } catch {+ // Skip comments that fail to decrypt+ }+ }++ // Decrypt reactions+ const reactions: PublicFeedReaction[] = [];+ for (const reaction of data.reactions) {+ // Skip deleted reactions (they have null cipher/nonce)+ if (reaction.isDeleted || !reaction.cipher || !reaction.nonce) continue;+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: reaction.cipher, nonce: reaction.nonce },+ collectionKey,+ );+ const reactionType = unpadReaction(+ new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ ),+ );++ // Determine if this reaction is on a reply by checking the comment's parent status+ let isCommentReply: boolean | undefined;+ if (reaction.commentID) {+ isCommentReply = commentParentMap.get(reaction.commentID);+ }++ reactions.push({+ id: reaction.id,+ fileID: reaction.fileID ?? 0,+ commentID: reaction.commentID ?? undefined,+ isCommentReply,+ reactionType,+ userID: reaction.userID,+ anonUserID: reaction.anonUserID ?? undefined,+ isDeleted: reaction.isDeleted,+ createdAt: reaction.createdAt,+ updatedAt: reaction.updatedAt,+ });+ } catch {+ // Skip reactions that fail to decrypt+ }+ }++ return { comments, reactions };+};diff --git a/web/apps/albums/vendor/ente-new/photos/components/AssignPersonDialog.tsx b/web/apps/albums/vendor/ente-new/photos/components/AssignPersonDialog.tsxnew file mode 100644index 0000000000..d6c39bf746--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/AssignPersonDialog.tsx@@ -0,0 +1,78 @@+import {+ Dialog,+ DialogContent,+ DialogTitle,+ styled,+ Typography,+ useMediaQuery,+} from "@mui/material";+import { SpacedRow } from "ente-base/components/containers";+import { DialogCloseIconButton } from "ente-base/components/mui/DialogCloseIconButton";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import type { Person } from "ente-new/photos/services/ml/people";+import React from "react";+import { ItemCard, LargeTileButton, LargeTileTextOverlay } from "./Tiles";++export type AssignPersonDialogProps = ModalVisibilityProps & {+ /**+ * Existing named people that can be selected.+ */+ people: Person[];+ /**+ * Title to show on the dialog.+ */+ title: string;+ /**+ * Called when the user selects a person.+ */+ onSelectPerson: (personID: string) => void;+};++/**+ * A dialog that allows selecting an existing person (cgroup) to associate+ * something (e.g. file(s)) with.+ */+export const AssignPersonDialog: React.FC<AssignPersonDialogProps> = ({+ open,+ onClose,+ people,+ title,+ onSelectPerson,+}) => {+ const isFullScreen = useMediaQuery("(max-width: 490px)");++ return (+ <Dialog+ {...{ open, onClose }}+ fullWidth+ fullScreen={isFullScreen}+ slotProps={{ paper: { sx: { maxWidth: "490px" } } }}+ >+ <SpacedRow sx={{ padding: "10px 8px 6px 0" }}>+ <DialogTitle variant="h3">{title}</DialogTitle>+ <DialogCloseIconButton {...{ onClose }} />+ </SpacedRow>+ <DialogContent_>+ {people.map((person) => (+ <ItemCard+ key={person.id}+ TileComponent={LargeTileButton}+ coverFile={person.displayFaceFile}+ coverFaceID={person.displayFaceID}+ onClick={() => onSelectPerson(person.id)}+ >+ <LargeTileTextOverlay>+ <Typography>{person.name ?? ""}</Typography>+ </LargeTileTextOverlay>+ </ItemCard>+ ))}+ </DialogContent_>+ </Dialog>+ );+};++const DialogContent_ = styled(DialogContent)`+ display: flex;+ flex-wrap: wrap;+ gap: 4px;+`;diff --git a/web/apps/albums/vendor/ente-new/photos/components/CollectionMappingChoice.tsx b/web/apps/albums/vendor/ente-new/photos/components/CollectionMappingChoice.tsxnew file mode 100644index 0000000000..45f5f08c1b--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/CollectionMappingChoice.tsx@@ -0,0 +1,80 @@+import FolderIcon from "@mui/icons-material/Folder";+import FolderCopyIcon from "@mui/icons-material/FolderCopy";+import {+ Dialog,+ DialogContent,+ DialogTitle,+ Stack,+ Typography,+} from "@mui/material";+import { SpacedRow } from "ente-base/components/containers";+import { DialogCloseIconButton } from "ente-base/components/mui/DialogCloseIconButton";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import type { CollectionMapping } from "ente-base/types/ipc";+import { t } from "i18next";+import React from "react";++type CollectionMappingChoiceProps = ModalVisibilityProps & {+ /**+ * Callback invoked with the mapping choice selected by the user.+ *+ * The dialog is automatically closed before this callback is invoked.+ */+ onSelect: (mapping: CollectionMapping) => void;+};++/**+ * A {@link Dialog} that allow the user to choose a collection mapping.+ */+export const CollectionMappingChoice: React.FC<+ CollectionMappingChoiceProps+> = ({ open, onClose, onSelect }) => (+ <Dialog+ open={open}+ onClose={onClose}+ fullWidth+ slotProps={{ paper: { sx: { maxWidth: "360px", padding: "12px" } } }}+ >+ <SpacedRow sx={{ pr: "4px" }}>+ <DialogTitle>{t("multi_folder_upload")}</DialogTitle>+ <DialogCloseIconButton {...{ onClose }} />+ </SpacedRow>++ <DialogContent+ sx={{+ display: "flex",+ flexDirection: "column",+ "&&": { paddingBlockStart: "12px" },+ gap: "20px",+ }}+ >+ <Typography sx={{ color: "text.muted" }}>+ {t("upload_to_choice")}+ </Typography>+ <Stack sx={{ gap: "12px" }}>+ <FocusVisibleButton+ color="accent"+ startIcon={<FolderIcon />}+ onClick={() => {+ onClose();+ onSelect("root");+ }}+ >+ {t("upload_to_single_album")}+ </FocusVisibleButton>++ <FocusVisibleButton+ color="accent"+ startIcon={<FolderCopyIcon />}+ onClick={() => {+ onClose();+ onSelect("parent");+ }}+ >+ {t("upload_to_album_per_folder")}+ </FocusVisibleButton>+ </Stack>+ </DialogContent>+ </Dialog>+);diff --git a/web/apps/albums/vendor/ente-new/photos/components/CollectionSelector.tsx b/web/apps/albums/vendor/ente-new/photos/components/CollectionSelector.tsxnew file mode 100644index 0000000000..fd6734a897--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/CollectionSelector.tsx@@ -0,0 +1,519 @@+import CloseIcon from "@mui/icons-material/Close";+import FavoriteIcon from "@mui/icons-material/Favorite";+import PushPinIcon from "@mui/icons-material/PushPin";+import SearchIcon from "@mui/icons-material/Search";+import {+ Box,+ Dialog,+ DialogContent,+ DialogTitle,+ Divider,+ InputAdornment,+ Stack,+ styled,+ TextField,+ Tooltip,+ Typography,+ useMediaQuery,+} from "@mui/material";+import { FilledIconButton } from "ente-base/components/mui";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import type { Collection } from "ente-media/collection";+import { CollectionsSortOptions } from "ente-new/photos/components/CollectionsSortOptions";+import {+ ItemCard,+ LargeTileButton,+ LargeTileCreateNewButton,+ LargeTileTextOverlay,+} from "ente-new/photos/components/Tiles";+import {+ canAddToCollection,+ canMoveToCollection,+ collectionsSortBy,+ sortCollectionSummaries,+ type CollectionsSortBy,+ type CollectionSummaries,+ type CollectionSummary,+} from "ente-new/photos/services/collection-summary";+import { includes } from "ente-utils/type-guards";+import { t } from "i18next";+import React, { useEffect, useMemo, useRef, useState } from "react";++export type CollectionSelectorAction =+ | "upload"+ | "add"+ | "move"+ | "restore"+ | "unhide";++export interface CollectionSelectorAttributes {+ /**+ * The {@link action} modifies the title of the dialog, and also removes+ * some system collections that don't might not make sense for that+ * particular action.+ */+ action: CollectionSelectorAction;+ /**+ * Some actions, like "add" and "move", happen in the context of an existing+ * collection summary.+ *+ * In such cases, the ID of the collection summary can be set as the+ * {@link sourceCollectionID} to omit showing it in the list again.+ */+ sourceCollectionSummaryID?: number;+ /**+ * If set, this collection will be shown first in the list.+ *+ * This is useful for the "upload" action, where the user is viewing a+ * specific collection and might want to upload to it.+ */+ activeCollectionID?: number;+ /**+ * If true, only show hidden albums in the collection selector.+ *+ * This is used when uploading from the hidden albums section.+ */+ showHiddenCollections?: boolean;+ /**+ * Callback invoked when the user selects the option to create a new+ * collection.+ */+ onCreateCollection: () => void;+ /**+ * Callback invoked when the user selects one the existing collections+ * listed in the dialog.+ */+ onSelectCollection: (collection: Collection) => void;+ /**+ * Callback invoked when the user cancels the collection selection dialog.+ */+ onCancel?: () => void;+}++type CollectionSelectorProps = ModalVisibilityProps & {+ /**+ * The same {@link CollectionSelector} can be used for different+ * purposes by customizing the {@link attributes} prop before opening it.+ */+ attributes: CollectionSelectorAttributes | undefined;+ /**+ * The collections to list.+ *+ * The picker does not list all of the collection summaries, it filters+ * these provided list down to values which make sense for the+ * {@link attribute}'s {@link action}.+ *+ * See: [Note: Picking from selectable collection summaries].+ */+ collectionSummaries: CollectionSummaries;+ /**+ * A function to map from a collection summary ID to a {@link Collection}.+ *+ * This is invoked when the user makes a selection, to convert the ID of the+ * selected collection summary into a collection object that can be passed+ * as the {@link callback} property of {@link CollectionSelectorAttributes}.+ *+ * [Note: Picking from selectable collection summaries]+ *+ * In general, not all pseudo collections can be converted into a+ * collection. For example, there is no underlying collection corresponding+ * to the "All" pseudo collection. However, the implementation of+ * {@link CollectionSelector} is such that it filters the provided+ * {@link collectionSummaries} to only show those which, when selected, can+ * be mapped to an (existing or on-demand created) collection.+ */+ collectionForCollectionSummaryID: (+ collectionID: number,+ ) => Promise<Collection>;+};++/**+ * A dialog allowing the user to select one of their existing collections or+ * create a new one.+ */+export const CollectionSelector: React.FC<CollectionSelectorProps> = ({+ open,+ onClose,+ attributes,+ collectionSummaries,+ collectionForCollectionSummaryID,+}) => {+ // Make the dialog fullscreen if the screen is <= the dialog's max width.+ const isFullScreen = useMediaQuery("(max-width: 490px)");++ const [searchTerm, setSearchTerm] = useState("");+ const [sortBy, setSortBy] =+ useCollectionSelectorSortByLocalState("name-asc");++ const [filteredCollections, setFilteredCollections] = useState<+ CollectionSummary[]+ >([]);++ const handleExited = () => {+ setSearchTerm("");+ };++ useEffect(() => {+ if (!attributes || !open) {+ return;+ }++ const activeCollectionID = attributes.activeCollectionID;+ const filteredCollections = [...collectionSummaries.values()].filter(+ (cs) => {+ if (cs.id === attributes.sourceCollectionSummaryID) {+ return false;+ } else if (attributes.action == "add") {+ return canAddToCollection(cs) && cs.type != "userFavorites";+ } else if (attributes.action == "upload") {+ return (+ (canMoveToCollection(cs) ||+ cs.type == "uncategorized") &&+ cs.type != "userFavorites"+ );+ } else if (attributes.action == "restore") {+ return (+ (canMoveToCollection(cs) ||+ cs.type == "uncategorized") &&+ cs.type != "userFavorites"+ );+ } else {+ // "move" and "unhide"+ return (+ canMoveToCollection(cs) && cs.type != "userFavorites"+ );+ }+ },+ );++ const collections = sortCollectionSummaries(filteredCollections, sortBy)+ .sort((a, b) => b.sortPriority - a.sortPriority)+ .sort((a, b) => {+ // Prioritize the active collection (if any) to appear first.+ if (a.id === activeCollectionID) return -1;+ if (b.id === activeCollectionID) return 1;+ return 0;+ });++ if (collections.length === 0) {+ onClose();+ attributes.onCreateCollection();+ }++ setFilteredCollections(collections);+ }, [collectionSummaries, attributes, open, onClose, sortBy]);++ const searchFilteredCollections = useMemo(() => {+ if (!searchTerm.trim()) {+ return filteredCollections;+ }+ const searchLower = searchTerm.toLowerCase();+ return filteredCollections.filter((cs) =>+ cs.name.toLowerCase().includes(searchLower),+ );+ }, [filteredCollections, searchTerm]);++ const showCreateButton = useMemo(() => {+ if (!searchTerm.trim()) {+ return true;+ }+ const searchLower = searchTerm.toLowerCase();+ const createText = t("create_albums").toLowerCase();+ return createText.includes(searchLower);+ }, [searchTerm]);++ if (!filteredCollections.length) {+ return <></>;+ }++ if (!attributes) {+ return <></>;+ }++ const { action, onSelectCollection, onCancel, onCreateCollection } =+ attributes;++ const handleCollectionSummaryClick = async (id: number) => {+ onSelectCollection(await collectionForCollectionSummaryID(id));+ onClose();+ };++ const handleClose = () => {+ onCancel?.();+ onClose();+ };++ return (+ <StyledDialog+ open={open}+ onClose={handleClose}+ fullWidth+ fullScreen={isFullScreen}+ slotProps={{+ paper: {+ sx: {+ maxWidth: "500px",+ "@media (min-width: 491px)": { height: "100%" },+ },+ },+ transition: { onExited: handleExited },+ }}+ >+ <DialogTitle>+ <Stack sx={{ gap: 1.5 }}>+ <Stack direction="row" sx={{ gap: 1.5 }}>+ <Stack sx={{ flex: 1 }}>+ <Box>+ <Typography variant="h5">+ {titleForAction(action)}+ </Typography>+ <Typography+ variant="small"+ sx={{+ color: "text.muted",+ fontWeight: "regular",+ }}+ >+ {searchTerm+ ? `${searchFilteredCollections.length} / ${filteredCollections.length} ${t("albums")}`+ : t("albums_count", {+ count: filteredCollections.length,+ })}+ </Typography>+ </Box>+ </Stack>+ <CollectionsSortOptions+ activeSortBy={sortBy}+ onChangeSortBy={setSortBy}+ nestedInDialog+ />+ <FilledIconButton onClick={handleClose}>+ <CloseIcon />+ </FilledIconButton>+ </Stack>+ <SearchField value={searchTerm} onChange={setSearchTerm} />+ </Stack>+ </DialogTitle>+ <Divider />+ {searchFilteredCollections.length === 0 && !showCreateButton ? (+ <NoResultsContent>+ <Typography color="text.muted">+ {t("no_results")}+ </Typography>+ </NoResultsContent>+ ) : (+ <DialogContent_>+ {showCreateButton && (+ <LargeTileCreateNewButton onClick={onCreateCollection}>+ {t("create_albums")}+ </LargeTileCreateNewButton>+ )}+ {searchFilteredCollections.map((collectionSummary) => (+ <CollectionSummaryButton+ key={collectionSummary.id}+ collectionSummary={collectionSummary}+ onClick={handleCollectionSummaryClick}+ />+ ))}+ </DialogContent_>+ )}+ </StyledDialog>+ );+};++const StyledDialog = styled(Dialog)(({ theme }) => ({+ "& .MuiDialogTitle-root": { padding: theme.spacing(2) },+ "& .MuiDialogContent-root": { padding: theme.spacing(2) },+}));++const DialogContent_ = styled(DialogContent)`+ display: grid;+ grid-template-columns: repeat(auto-fill, 150px);+ gap: 4px;+ align-content: start;++ @media (min-width: 491px) {+ justify-content: center;+ }+`;++const NoResultsContent = styled(DialogContent)`+ display: flex;+ justify-content: center;+ align-items: center;+ min-height: 154px;+`;++const titleForAction = (action: CollectionSelectorAction) => {+ switch (action) {+ case "upload":+ return t("upload_to_album");+ case "add":+ return t("add_to_album");+ case "move":+ return t("move_to_album");+ case "restore":+ return t("restore_to_album");+ case "unhide":+ return t("unhide_to_album");+ }+};++interface CollectionSummaryButtonProps {+ collectionSummary: CollectionSummary;+ onClick: (collectionSummaryID: number) => void;+}++const CollectionSummaryButton: React.FC<CollectionSummaryButtonProps> = ({+ collectionSummary,+ onClick,+}) => {+ const isFavorite = collectionSummary.type === "userFavorites";+ const isPinned = collectionSummary.attributes.has("pinned");++ return (+ <ItemCard+ TileComponent={LargeTileButton}+ coverFile={collectionSummary.coverFile}+ onClick={() => onClick(collectionSummary.id)}+ >+ <LargeTileTextOverlay>+ <Tooltip title={collectionSummary.name} arrow>+ <Typography+ sx={{+ maxWidth: "240px",+ overflow: "hidden",+ textOverflow: "ellipsis",+ display: "-webkit-box",+ WebkitLineClamp: 3,+ WebkitBoxOrient: "vertical",+ }}+ >+ {collectionSummary.name}+ </Typography>+ </Tooltip>+ </LargeTileTextOverlay>+ {(isFavorite || isPinned) && (+ <Box+ sx={{+ position: "absolute",+ bottom: 8,+ right: 8,+ display: "flex",+ gap: 0.5,+ }}+ >+ {isFavorite && (+ <FavoriteIcon sx={{ fontSize: 20, color: "white" }} />+ )}+ {isPinned && (+ <PushPinIcon sx={{ fontSize: 20, color: "white" }} />+ )}+ </Box>+ )}+ </ItemCard>+ );+};++interface SearchFieldProps {+ value: string;+ onChange: (value: string) => void;+}++const SearchField: React.FC<SearchFieldProps> = ({ value, onChange }) => {+ const inputRef = useRef<HTMLInputElement>(null);++ const handleClear = () => {+ onChange("");+ inputRef.current?.focus();+ };++ return (+ <TextField+ inputRef={inputRef}+ fullWidth+ size="small"+ placeholder={t("albums_search_hint")}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ autoFocus+ slotProps={{+ input: {+ startAdornment: (+ <InputAdornment position="start">+ <SearchIcon />+ </InputAdornment>+ ),+ endAdornment: value && (+ <InputAdornment+ position="end"+ sx={{ marginRight: "0 !important" }}+ >+ <CloseIcon+ fontSize="small"+ onClick={handleClear}+ sx={{+ color: "stroke.muted",+ cursor: "pointer",+ "&:hover": { color: "text.base" },+ }}+ />+ </InputAdornment>+ ),+ },+ }}+ sx={{+ "& .MuiOutlinedInput-root": {+ backgroundColor: "background.searchInput",+ borderColor: "transparent",+ "&:hover": { borderColor: "accent.light" },+ "&.Mui-focused": {+ borderColor: "accent.main",+ boxShadow: "none",+ },+ },+ "& .MuiInputBase-input": {+ color: "text.base",+ paddingTop: "8.5px !important",+ paddingBottom: "8.5px !important",+ },+ "& .MuiInputAdornment-root": {+ color: "stroke.muted",+ marginTop: "0 !important",+ marginRight: "8px",+ },+ "& .MuiOutlinedInput-notchedOutline": {+ borderColor: "transparent",+ },+ "& .MuiInputBase-input::placeholder": {+ color: "text.muted",+ opacity: 1,+ },+ }}+ />+ );+};++/**+ * A hook that maintains the collection selector sort order both as in-memory+ * and local storage state.+ */+const useCollectionSelectorSortByLocalState = (+ initialValue: CollectionsSortBy,+) => {+ const key = "collectionSelectorSortBy";++ const [value, setValue] = useState(initialValue);++ useEffect(() => {+ const value = localStorage.getItem(key);+ if (value && includes(collectionsSortBy, value)) setValue(value);+ }, []);++ const setter = (value: CollectionsSortBy) => {+ localStorage.setItem(key, value);+ setValue(value);+ };++ return [value, setter] as const;+};diff --git a/web/apps/albums/vendor/ente-new/photos/components/CollectionsSortOptions.tsx b/web/apps/albums/vendor/ente-new/photos/components/CollectionsSortOptions.tsxnew file mode 100644index 0000000000..980463e24c--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/CollectionsSortOptions.tsx@@ -0,0 +1,249 @@+import { ArrowDown02Icon, ArrowUp02Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import SortIcon from "@mui/icons-material/Sort";+import {+ IconButton,+ MenuItem,+ Stack,+ Typography,+ styled,+ type IconButtonProps,+ type PaperProps,+} from "@mui/material";+import Menu, { type MenuProps } from "@mui/material/Menu";+import type { CollectionsSortBy } from "ente-new/photos/services/collection-summary";+import { t } from "i18next";+import React, { useRef, useState } from "react";++interface CollectionsSortOptionsProps {+ /**+ * The sorting scheme currently active.+ */+ activeSortBy: CollectionsSortBy;+ /**+ * Change the scheme that should be used.+ */+ onChangeSortBy: (by: CollectionsSortBy) => void;+ /**+ * Set this to true if we're being shown inside a dialog, to further+ * increase the elevation of the menu.+ */+ nestedInDialog?: boolean;+ /**+ * Set this to true to disable the background for the icon button that+ * triggers the menu.+ */+ transparentTriggerButtonBackground?: boolean;+}++/** The three sort categories. */+type SortCategory = "name" | "creation-time" | "updation-time";++/** Extract the category from a CollectionsSortBy value. */+const getSortCategory = (sortBy: CollectionsSortBy): SortCategory => {+ if (sortBy.startsWith("name")) return "name";+ if (sortBy.startsWith("creation-time")) return "creation-time";+ return "updation-time";+};++/** Check if the sort is ascending. */+const isAscending = (sortBy: CollectionsSortBy): boolean =>+ sortBy.endsWith("-asc");++/** Get the CollectionsSortBy value for a category and direction. */+const getSortBy = (+ category: SortCategory,+ ascending: boolean,+): CollectionsSortBy => `${category}-${ascending ? "asc" : "desc"}`;++/**+ * A button that shows an overflow menu allowing the user to choose from amongst+ * the {@link CollectionsSortBy} values that should be used for sorting the+ * lists of collections.+ */+export const CollectionsSortOptions: React.FC<CollectionsSortOptionsProps> = ({+ activeSortBy,+ onChangeSortBy,+ nestedInDialog,+ transparentTriggerButtonBackground,+}) => {+ const [anchorEl, setAnchorEl] = useState<MenuProps["anchorEl"]>();+ // Apply sort changes after the menu closes to avoid flicker.+ const pendingSortByRef = useRef<CollectionsSortBy | undefined>(undefined);+ const ariaID = "collection-sort";++ const activeCategory = getSortCategory(activeSortBy);+ const activeAscending = isAscending(activeSortBy);++ const handleCategoryClick = (category: SortCategory) => {+ let nextSortBy: CollectionsSortBy;+ if (category === activeCategory) {+ // Toggle direction if same category+ nextSortBy = getSortBy(category, !activeAscending);+ } else {+ // Select new category with default direction+ const defaultAscending = category === "name"; // Name defaults to A-Z (asc), dates to newest (desc)+ nextSortBy = getSortBy(category, defaultAscending);+ }+ pendingSortByRef.current = nextSortBy;+ setAnchorEl(undefined);+ };++ const triggerButtonSxProps: IconButtonProps["sx"] = [+ transparentTriggerButtonBackground+ ? {}+ : { backgroundColor: "fill.faint" },+ ];++ const menuPaperSxProps: PaperProps["sx"] | undefined = nestedInDialog+ ? { backgroundColor: "background.paper2" }+ : undefined;++ return (+ <>+ <IconButton+ onClick={(event) => setAnchorEl(event.currentTarget)}+ aria-controls={anchorEl ? ariaID : undefined}+ aria-haspopup="true"+ aria-expanded={anchorEl ? "true" : undefined}+ sx={triggerButtonSxProps}+ >+ <SortIcon />+ </IconButton>+ <StyledMenu+ id={ariaID}+ {...(anchorEl && { anchorEl })}+ open={!!anchorEl}+ onClose={() => setAnchorEl(undefined)}+ slotProps={{+ paper: menuPaperSxProps ? { sx: menuPaperSxProps } : {},+ list: { disablePadding: true, "aria-labelledby": ariaID },+ transition: {+ onExited: () => {+ const nextSortBy = pendingSortByRef.current;+ if (nextSortBy) {+ pendingSortByRef.current = undefined;+ onChangeSortBy(nextSortBy);+ }+ },+ },+ }}+ anchorOrigin={{ vertical: "bottom", horizontal: "right" }}+ transformOrigin={{ vertical: "top", horizontal: "right" }}+ >+ <SortCategoryOption+ category="name"+ activeCategory={activeCategory}+ activeAscending={activeAscending}+ onClick={handleCategoryClick}+ label={t("name")}+ ascLabel={t("sort_asc_indicator")}+ descLabel={t("sort_desc_indicator")}+ />+ <SortCategoryOption+ category="creation-time"+ activeCategory={activeCategory}+ activeAscending={activeAscending}+ onClick={handleCategoryClick}+ label={t("created")}+ ascLabel={t("oldest")}+ descLabel={t("newest")}+ />+ <SortCategoryOption+ category="updation-time"+ activeCategory={activeCategory}+ activeAscending={activeAscending}+ onClick={handleCategoryClick}+ label={t("updated")}+ ascLabel={t("oldest")}+ descLabel={t("newest")}+ />+ </StyledMenu>+ </>+ );+};++interface SortCategoryOptionProps {+ category: SortCategory;+ activeCategory: SortCategory;+ activeAscending: boolean;+ onClick: (category: SortCategory) => void;+ label: string;+ ascLabel: string;+ descLabel: string;+}++const SortCategoryOption: React.FC<SortCategoryOptionProps> = ({+ category,+ activeCategory,+ activeAscending,+ onClick,+ label,+ ascLabel,+ descLabel,+}) => {+ const isSelected = category === activeCategory;+ const directionLabel = activeAscending ? ascLabel : descLabel;+ const arrowIcon = activeAscending ? ArrowUp02Icon : ArrowDown02Icon;++ return (+ <StyledMenuItem onClick={() => onClick(category)}>+ <Stack direction="row" sx={{ alignItems: "center" }}>+ <Typography+ sx={{+ color: isSelected ? "text.primary" : "text.secondary",+ }}+ >+ {label}+ </Typography>+ {isSelected && (+ <Stack+ direction="row"+ sx={{+ alignItems: "center",+ ml: 1,+ gap: 0.75,+ color: "text.muted",+ }}+ >+ <Typography>•</Typography>+ <Typography sx={{ fontSize: "0.9rem" }}>+ {directionLabel}+ </Typography>+ <HugeiconsIcon+ icon={arrowIcon}+ size={19}+ color="currentColor"+ />+ </Stack>+ )}+ </Stack>+ </StyledMenuItem>+ );+};++const StyledMenu = styled(Menu)(({ theme }) => ({+ "& .MuiPaper-root": {+ backgroundColor: theme.vars.palette.background.elevatedPaper,+ minWidth: 220,+ width: 220,+ borderRadius: 12,+ boxShadow: theme.vars.palette.boxShadow.menu,+ marginTop: 6,+ },+ "& .MuiList-root": { padding: theme.spacing(1) },+}));++const StyledMenuItem = styled(MenuItem)(({ theme }) => ({+ display: "flex",+ alignItems: "center",+ gap: 12,+ padding: theme.spacing(1.5, 2),+ borderRadius: 8,+ color: theme.vars.palette.text.base,+ fontSize: 15,+ "&:hover": { backgroundColor: theme.vars.palette.fill.faintHover },+ "& .MuiListItemIcon-root": { minWidth: 0, color: "inherit" },+ "& .MuiListItemText-root": { margin: 0 },+ "& .MuiListItemText-primary": { color: "inherit", fontSize: "inherit" },+}));diff --git a/web/apps/albums/vendor/ente-new/photos/components/EditLocationDialog.tsx b/web/apps/albums/vendor/ente-new/photos/components/EditLocationDialog.tsxnew file mode 100644index 0000000000..4536baecd4--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/EditLocationDialog.tsx@@ -0,0 +1,826 @@+import AddIcon from "@mui/icons-material/Add";+import ArrowForwardIcon from "@mui/icons-material/ArrowForward";+import CloseIcon from "@mui/icons-material/Close";+import DoneIcon from "@mui/icons-material/Done";+import RemoveIcon from "@mui/icons-material/Remove";+import SearchIcon from "@mui/icons-material/Search";+import {+ Box,+ Button,+ CircularProgress,+ ClickAwayListener,+ Dialog,+ IconButton,+ InputBase,+ Stack,+ styled,+ Typography,+} from "@mui/material";+import { useIsSmallWidth } from "ente-base/components/utils/hooks";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import { haveWindow } from "ente-base/env";+import type { Location } from "ente-base/types";+import type { EnteFile } from "ente-media/file";+import { fileLocation } from "ente-media/file-metadata";+import { t } from "i18next";+import React, { useEffect, useMemo, useRef, useState } from "react";++import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.webpack.css";+import "leaflet/dist/leaflet.css";+// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-unused-expressions+haveWindow() && require("leaflet-defaulticon-compatibility");+const leaflet = haveWindow()+ ? // eslint-disable-next-line @typescript-eslint/no-require-imports+ (require("leaflet") as typeof import("leaflet"))+ : null;++export interface EditLocationDialogProps extends ModalVisibilityProps {+ /**+ * The files whose location we want to edit.+ */+ files: EnteFile[];+ /**+ * Called when the user confirms the location update.+ *+ * @param location The new location to set for all selected files.+ * @returns A promise that resolves when the update is complete.+ */+ onConfirm: (location: Location) => Promise<void>;+}++/**+ * A full-screen dialog with an interactive map where users can drop a pin to+ * set the location for one or more photos.+ */+export const EditLocationDialog: React.FC<EditLocationDialogProps> = ({+ open,+ onClose,+ files,+ onConfirm,+}) => {+ const fullScreen = useIsSmallWidth();+ const [selectedLocation, setSelectedLocation] = useState<+ Location | undefined+ >(undefined);+ const [isLoading, setIsLoading] = useState(false);+ const [isSuccess, setIsSuccess] = useState(false);++ // Get initial location only if a single file is selected+ const initialLocation = useMemo(() => {+ if (files.length !== 1) return undefined;+ const file = files[0];+ return file ? fileLocation(file) : undefined;+ }, [files]);++ // Capture whether we're adding (vs editing) when dialog opens+ const [isAddingLocation, setIsAddingLocation] = useState(false);++ // Reset selected location and states only when dialog opens+ const prevOpenRef = useRef(false);+ useEffect(() => {+ if (open && !prevOpenRef.current) {+ setSelectedLocation(initialLocation);+ setIsLoading(false);+ setIsSuccess(false);+ // Determine add vs edit based on whether any file has location at open time+ setIsAddingLocation(!files.some((file) => fileLocation(file)));+ }+ prevOpenRef.current = open;+ }, [open, initialLocation, files]);++ const hasLocationChanged = useMemo(() => {+ if (!selectedLocation) return false;+ if (!initialLocation) return true;+ return (+ selectedLocation.latitude !== initialLocation.latitude ||+ selectedLocation.longitude !== initialLocation.longitude+ );+ }, [selectedLocation, initialLocation]);++ // Reset success state when user selects a new location+ const prevSelectedLocationRef = useRef(selectedLocation);+ useEffect(() => {+ const prevLoc = prevSelectedLocationRef.current;+ const currLoc = selectedLocation;+ const locationChanged =+ prevLoc?.latitude !== currLoc?.latitude ||+ prevLoc?.longitude !== currLoc?.longitude;++ if (isSuccess && locationChanged) {+ setIsSuccess(false);+ }+ prevSelectedLocationRef.current = selectedLocation;+ }, [isSuccess, selectedLocation]);++ const handleConfirm = async () => {+ if (selectedLocation && hasLocationChanged && !isLoading) {+ setIsLoading(true);+ setIsSuccess(false);+ try {+ await onConfirm(selectedLocation);+ setIsSuccess(true);+ } finally {+ setIsLoading(false);+ }+ }+ };++ useEffect(() => {+ if (!open || !isSuccess) return;+ const timeoutId = setTimeout(() => {+ onClose();+ }, 1000);+ return () => clearTimeout(timeoutId);+ }, [open, isSuccess, onClose]);++ return (+ <Dialog+ {...{ open, onClose, fullScreen }}+ maxWidth={false}+ slotProps={{+ paper: {+ sx: !fullScreen+ ? {+ width: "min(900px, calc(100vw - 64px))",+ height: "min(700px, calc(100vh - 64px))",+ }+ : undefined,+ },+ }}+ >+ <Stack sx={{ height: "100%", width: "100%" }}>+ <TitleBar+ onClose={onClose}+ onConfirm={handleConfirm}+ canConfirm={hasLocationChanged}+ isLoading={isLoading}+ isSuccess={isSuccess}+ isAddingLocation={isAddingLocation}+ />+ <Box sx={{ flex: 1, position: "relative" }}>+ <EditableMap+ open={open}+ initialLocation={initialLocation}+ selectedLocation={selectedLocation}+ onLocationSelect={setSelectedLocation}+ />+ </Box>+ </Stack>+ </Dialog>+ );+};++interface TitleBarProps {+ onClose: () => void;+ onConfirm: () => void;+ canConfirm: boolean;+ isLoading: boolean;+ isSuccess: boolean;+ isAddingLocation: boolean;+}++const TitleBar: React.FC<TitleBarProps> = ({+ onClose,+ onConfirm,+ canConfirm,+ isLoading,+ isSuccess,+ isAddingLocation,+}) => (+ <Stack+ direction="row"+ sx={{+ alignItems: "center",+ gap: 1,+ p: 1,+ borderBottom: "1px solid",+ borderColor: "divider",+ }}+ >+ <IconButton onClick={onClose} aria-label={t("close")} color="secondary">+ <CloseIcon />+ </IconButton>+ <Typography variant="h6" sx={{ flex: 1 }}>+ {t(isAddingLocation ? "add_location" : "edit_location")}+ </Typography>+ {isLoading ? (+ <Box+ sx={{+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ px: 2,+ }}+ >+ <CircularProgress size={24} />+ </Box>+ ) : isSuccess ? (+ <Box+ sx={{+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ px: 2,+ color: "success.main",+ }}+ >+ <DoneIcon />+ </Box>+ ) : (+ <Button+ onClick={onConfirm}+ disabled={!canConfirm}+ variant="contained"+ color="accent"+ >+ {t("save_location")}+ </Button>+ )}+ </Stack>+);++interface EditableMapProps {+ open: boolean;+ initialLocation: Location | undefined;+ selectedLocation: Location | undefined;+ onLocationSelect: (location: Location) => void;+}++interface NominatimResult {+ place_id: number;+ display_name: string;+ lat: string;+ lon: string;+}++const EditableMap: React.FC<EditableMapProps> = ({+ open,+ initialLocation,+ selectedLocation,+ onLocationSelect,+}) => {+ const mapContainerRef = useRef<HTMLDivElement>(null);+ const mapRef = useRef<L.Map | null>(null);+ const markerRef = useRef<L.Marker | null>(null);+ const prevOpenRef = useRef(open);+ // Capture initial location at mount time to avoid map reset on file updates+ const initialLocationRef = useRef(initialLocation);++ // Search state+ const [searchQuery, setSearchQuery] = useState("");+ const [searchResults, setSearchResults] = useState<NominatimResult[]>([]);+ const [showResults, setShowResults] = useState(false);+ const [isSearching, setIsSearching] = useState(false);+ const searchInputRef = useRef<HTMLInputElement>(null);+ const searchRequestIdRef = useRef(0);+ const searchAbortRef = useRef<AbortController | null>(null);++ // Manual coordinate input state+ const [manualLat, setManualLat] = useState<string | null>(null);+ const [manualLon, setManualLon] = useState<string | null>(null);++ // Reset manual inputs when dialog opens or selectedLocation changes+ useEffect(() => {+ setManualLat(null);+ setManualLon(null);+ }, [open, selectedLocation]);++ const handleSearchChange = (query: string) => {+ setSearchQuery(query);+ if (searchAbortRef.current) {+ searchAbortRef.current.abort();+ searchAbortRef.current = null;+ }+ setIsSearching(false);+ setSearchResults([]);+ setShowResults(false);+ };++ const handleSearchSubmit = async (+ e?: React.FormEvent<HTMLFormElement> | React.MouseEvent,+ ) => {+ e?.preventDefault();++ const query =+ searchInputRef.current?.value.trim() ?? searchQuery.trim();+ if (query.length < 3 || isSearching) {+ if (query.length < 3) {+ setSearchResults([]);+ setShowResults(false);+ }+ return;+ }++ setSearchQuery(query);++ if (searchAbortRef.current) {+ searchAbortRef.current.abort();+ }++ const requestId = searchRequestIdRef.current + 1;+ searchRequestIdRef.current = requestId;+ const abortController = new AbortController();+ searchAbortRef.current = abortController;+ setIsSearching(true);++ try {+ await new Promise((resolve) => setTimeout(resolve, 750));+ if (+ searchRequestIdRef.current !== requestId ||+ abortController.signal.aborted+ ) {+ return;+ }++ const response = await fetch(+ `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}&limit=5`,+ {+ headers: { "Accept-Language": "en" },+ signal: abortController.signal,+ },+ );+ const data = (await response.json()) as NominatimResult[];+ if (searchRequestIdRef.current !== requestId) return;+ setSearchResults(data);+ setShowResults(data.length > 0);+ } catch (error) {+ if (abortController.signal.aborted) return;+ if (searchRequestIdRef.current !== requestId) return;+ console.error("Search failed:", error);+ setSearchResults([]);+ setShowResults(false);+ } finally {+ if (searchRequestIdRef.current === requestId) {+ setIsSearching(false);+ }+ }+ };++ const handleSelectResult = (result: NominatimResult) => {+ const lat = parseFloat(result.lat);+ const lng = parseFloat(result.lon);+ onLocationSelect({ latitude: lat, longitude: lng });++ // Update map view+ if (mapRef.current) {+ mapRef.current.setView([lat, lng], 12);++ // Update or create marker+ if (markerRef.current) {+ markerRef.current.setLatLng([lat, lng]);+ } else if (leaflet) {+ const marker = leaflet+ .marker([lat, lng], { draggable: true })+ .addTo(mapRef.current);+ markerRef.current = marker;++ marker.on("dragend", () => {+ const pos = marker.getLatLng();+ onLocationSelect({ latitude: pos.lat, longitude: pos.lng });+ });+ }+ }++ setSearchQuery("");+ setSearchResults([]);+ setShowResults(false);+ };++ const handleManualCoordinates = () => {+ const latStr = manualLat ?? selectedLocation?.latitude.toFixed(6) ?? "";+ const lonStr =+ manualLon ?? selectedLocation?.longitude.toFixed(6) ?? "";+ const lat = parseFloat(latStr);+ const lon = parseFloat(lonStr);+ if (isNaN(lat) || isNaN(lon)) return;+ if (lat < -90 || lat > 90 || lon < -180 || lon > 180) return;++ onLocationSelect({ latitude: lat, longitude: lon });++ if (mapRef.current) {+ mapRef.current.setView([lat, lon], 12);++ if (markerRef.current) {+ markerRef.current.setLatLng([lat, lon]);+ } else if (leaflet) {+ const marker = leaflet+ .marker([lat, lon], { draggable: true })+ .addTo(mapRef.current);+ markerRef.current = marker;++ marker.on("dragend", () => {+ const pos = marker.getLatLng();+ onLocationSelect({ latitude: pos.lat, longitude: pos.lng });+ });+ }+ }++ setManualLat(null);+ setManualLon(null);+ };++ const urlTemplate = "https://tile.openstreetmap.org/{z}/{x}/{y}.png";+ const attribution =+ '© <a target="_blank" rel="noopener" href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';++ useEffect(() => {+ return () => {+ if (searchAbortRef.current) {+ searchAbortRef.current.abort();+ }+ };+ }, []);++ useEffect(() => {+ if (!open) return;+ const timeoutId = setTimeout(() => {+ searchInputRef.current?.focus();+ }, 0);+ return () => clearTimeout(timeoutId);+ }, [open]);++ useEffect(() => {+ const mapContainer = mapContainerRef.current;+ if (!mapContainer || !leaflet) return;++ // Don't recreate map if it already exists+ if (mapRef.current) return;++ // Use the captured initial location from mount time+ const initLoc = initialLocationRef.current;+ const initialLat = initLoc?.latitude;+ const initialLng = initLoc?.longitude;++ // Determine initial view+ const defaultCenter: L.LatLngTuple = [20, 0]; // World view+ const defaultZoom = 2;++ const hasInitialLocation =+ initialLat !== undefined && initialLng !== undefined;+ const center: L.LatLngTuple = hasInitialLocation+ ? [initialLat, initialLng]+ : defaultCenter;+ const zoom = hasInitialLocation ? 6 : defaultZoom;++ // Create map with zoom control disabled (we add custom controls)+ const map = leaflet+ .map(mapContainer, { zoomControl: false })+ .setView(center, zoom);+ leaflet.tileLayer(urlTemplate, { attribution }).addTo(map);+ mapRef.current = map;++ // Add initial marker if location exists+ if (hasInitialLocation) {+ const marker = leaflet+ .marker([initialLat, initialLng], { draggable: true })+ .addTo(map);+ markerRef.current = marker;++ marker.on("dragend", () => {+ const pos = marker.getLatLng();+ onLocationSelect({ latitude: pos.lat, longitude: pos.lng });+ });+ }++ // Handle map clicks to place/move marker+ map.on("click", (e: L.LeafletMouseEvent) => {+ const { lat, lng } = e.latlng;+ onLocationSelect({ latitude: lat, longitude: lng });++ if (markerRef.current) {+ markerRef.current.setLatLng([lat, lng]);+ } else {+ const marker = leaflet+ .marker([lat, lng], { draggable: true })+ .addTo(map);+ markerRef.current = marker;++ marker.on("dragend", () => {+ const pos = marker.getLatLng();+ onLocationSelect({ latitude: pos.lat, longitude: pos.lng });+ });+ }+ });++ return () => {+ if (mapRef.current) {+ mapRef.current.remove();+ mapRef.current = null;+ markerRef.current = null;+ }+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ // Sync marker when selection changes; recenter only when the dialog opens.+ useEffect(() => {+ const wasOpen = prevOpenRef.current;+ prevOpenRef.current = open;+ if (!open || !mapRef.current || !leaflet) return;+ const didOpen = !wasOpen;+ const nextLocation = selectedLocation ?? initialLocation;+ if (!nextLocation) return;+ const position: L.LatLngTuple = [+ nextLocation.latitude,+ nextLocation.longitude,+ ];++ if (markerRef.current) {+ markerRef.current.setLatLng(position);+ } else {+ const marker = leaflet+ .marker(position, { draggable: true })+ .addTo(mapRef.current);+ markerRef.current = marker;++ marker.on("dragend", () => {+ const pos = marker.getLatLng();+ onLocationSelect({ latitude: pos.lat, longitude: pos.lng });+ });+ }+ if (didOpen) {+ mapRef.current.setView(position, mapRef.current.getZoom());+ }+ }, [open, initialLocation, selectedLocation, onLocationSelect]);++ const handleZoomIn = (e: React.MouseEvent) => {+ e.stopPropagation();+ mapRef.current?.zoomIn();+ };+ const handleZoomOut = (e: React.MouseEvent) => {+ e.stopPropagation();+ mapRef.current?.zoomOut();+ };++ return (+ <MapWrapper>+ <MapContainer ref={mapContainerRef} />+ <SearchContainer>+ <ClickAwayListener onClickAway={() => setShowResults(false)}>+ <Box+ component="form"+ onSubmit={handleSearchSubmit}+ sx={{ position: "relative", width: "100%" }}+ >+ <SearchInputWrapper>+ <InputBase+ placeholder={t("search_location")}+ value={searchQuery}+ onChange={(e) =>+ handleSearchChange(e.target.value)+ }+ onFocus={() =>+ searchResults.length > 0 &&+ setShowResults(true)+ }+ inputRef={searchInputRef}+ sx={{ flex: 1 }}+ inputProps={{+ style: { padding: 0, paddingLeft: 8 },+ }}+ />+ <IconButton+ type="submit"+ size="small"+ disabled={+ isSearching || searchQuery.trim().length < 3+ }+ aria-label={t("search_location")}+ sx={(theme) => ({+ ml: 1,+ p: 0,+ width: 32,+ height: 32,+ backgroundColor:+ theme.vars.palette.fill.faint,+ color: theme.vars.palette.text.base,+ transition:+ "background-color 0.2s ease, transform 0.2s ease",+ "&:hover": {+ backgroundColor:+ theme.vars.palette.fill.faintHover,+ },+ "&:active": {+ backgroundColor:+ theme.vars.palette.fill.faintHover,+ transform: "scale(0.96)",+ },+ "&.Mui-disabled": {+ backgroundColor:+ theme.vars.palette.background+ .elevatedPaper,+ color: theme.vars.palette.text.faint,+ },+ })}+ >+ {isSearching ? (+ <CircularProgress+ size={18}+ thickness={5}+ sx={{+ display: "block",+ color: "inherit",+ }}+ />+ ) : (+ <SearchIcon+ sx={{ color: "inherit", fontSize: 20 }}+ />+ )}+ </IconButton>+ </SearchInputWrapper>+ {showResults && (+ <SearchResultsList>+ {searchResults.map((result) => (+ <SearchResultItem+ key={result.place_id}+ onClick={() =>+ handleSelectResult(result)+ }+ >+ <Typography+ variant="body"+ sx={{+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ }}+ >+ {result.display_name}+ </Typography>+ </SearchResultItem>+ ))}+ </SearchResultsList>+ )}+ </Box>+ </ClickAwayListener>+ </SearchContainer>+ <CoordinateControls>+ <CoordinateInputWrapper>+ <CoordinateInput+ placeholder="Lat"+ value={+ manualLat ??+ selectedLocation?.latitude.toFixed(6) ??+ ""+ }+ onChange={(e) => setManualLat(e.target.value)}+ type="number"+ inputProps={{ step: "any" }}+ />+ </CoordinateInputWrapper>+ <CoordinateInputWrapper>+ <CoordinateInput+ placeholder="Lon"+ value={+ manualLon ??+ selectedLocation?.longitude.toFixed(6) ??+ ""+ }+ onChange={(e) => setManualLon(e.target.value)}+ type="number"+ inputProps={{ step: "any" }}+ />+ </CoordinateInputWrapper>+ <GoToLocationButton+ onClick={handleManualCoordinates}+ disabled={+ manualLat === null &&+ manualLon === null &&+ !selectedLocation+ }+ >+ <ArrowForwardIcon sx={{ fontSize: 16 }} />+ </GoToLocationButton>+ </CoordinateControls>+ <ZoomControls>+ <ZoomButton onClick={handleZoomIn} aria-label={t("zoom_in")}>+ <AddIcon />+ </ZoomButton>+ <ZoomButton onClick={handleZoomOut} aria-label={t("zoom_out")}>+ <RemoveIcon />+ </ZoomButton>+ </ZoomControls>+ </MapWrapper>+ );+};++const MapWrapper = styled("div")({+ height: "100%",+ width: "100%",+ position: "relative",+});++const MapContainer = styled("div")({ height: "100%", width: "100%" });++const CoordinateControls = styled("div")(({ theme }) => ({+ position: "absolute",+ bottom: theme.spacing(2),+ left: theme.spacing(2),+ zIndex: 1000,+ display: "flex",+ alignItems: "center",+ gap: theme.spacing(1),+}));++const CoordinateInputWrapper = styled("div")(({ theme }) => ({+ display: "flex",+ alignItems: "center",+ backgroundColor: theme.vars.palette.background.paper,+ padding: theme.spacing(1, 1.5),+ borderRadius: "9999px",+ boxShadow: theme.shadows[4],+}));++const CoordinateInput = styled(InputBase)(({ theme }) => ({+ "& input": {+ width: 82,+ padding: 0,+ fontSize: "0.875rem",+ textAlign: "left",+ "&::placeholder": { color: theme.vars.palette.text.muted, opacity: 1 },+ "&::-webkit-outer-spin-button, &::-webkit-inner-spin-button": {+ WebkitAppearance: "none",+ margin: 0,+ },+ MozAppearance: "textfield",+ },+}));++const GoToLocationButton = styled(IconButton)(({ theme }) => ({+ backgroundColor: theme.vars.palette.background.paper,+ color: theme.vars.palette.text.base,+ width: 36,+ height: 36,+ boxShadow: theme.shadows[4],+ "&:hover": { backgroundColor: theme.vars.palette.background.elevatedPaper },+ "&.Mui-disabled": {+ backgroundColor: theme.vars.palette.background.elevatedPaper,+ color: theme.vars.palette.text.faint,+ },+}));++const ZoomControls = styled(Stack)(({ theme }) => ({+ position: "absolute",+ right: theme.spacing(3),+ bottom: theme.spacing(5),+ zIndex: 1000,+ gap: theme.spacing(1),+}));++const ZoomButton = styled(IconButton)(({ theme }) => ({+ backgroundColor: theme.vars.palette.background.paper,+ boxShadow: theme.shadows[4],+ width: 32,+ height: 32,+ borderRadius: 12,+ transition: "transform 0.2s ease-out",+ "&:hover": {+ backgroundColor: theme.vars.palette.background.paper,+ transform: "scale(1.05)",+ },+}));++const SearchContainer = styled("div")(({ theme }) => ({+ position: "absolute",+ top: theme.spacing(2),+ left: theme.spacing(2),+ right: theme.spacing(2),+ zIndex: 1001,+ display: "flex",+ justifyContent: "center",+}));++const SearchInputWrapper = styled("div")(({ theme }) => ({+ display: "inline-flex",+ alignItems: "center",+ width: "min(100%, 360px)",+ backgroundColor: theme.vars.palette.background.paper,+ padding: theme.spacing(1),+ borderRadius: "9999px",+ boxShadow: theme.shadows[4],+}));++const SearchResultsList = styled("div")(({ theme }) => ({+ position: "absolute",+ top: "100%",+ left: 0,+ right: 0,+ maxWidth: 280,+ marginTop: theme.spacing(1),+ backgroundColor: theme.vars.palette.background.paper,+ borderRadius: theme.spacing(1),+ overflow: "hidden",+ maxHeight: 250,+ overflowY: "auto",+ boxShadow: theme.shadows[4],+}));++const SearchResultItem = styled("div")(({ theme }) => ({+ padding: theme.spacing(1.5, 2),+ cursor: "pointer",+ "&:hover": { backgroundColor: theme.vars.palette.action.hover },+ "&:not(:last-child)": {+ borderBottom: `1px solid ${theme.vars.palette.divider}`,+ },+}));diff --git a/web/apps/albums/vendor/ente-new/photos/components/FileContextMenu.tsx b/web/apps/albums/vendor/ente-new/photos/components/FileContextMenu.tsxnew file mode 100644index 0000000000..f46ecae0d8--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/FileContextMenu.tsx@@ -0,0 +1,207 @@+import {+ AddSquareIcon,+ ArrowRight02Icon,+ Clock02Icon,+ Delete02Icon,+ Download01Icon,+ Download05Icon,+ Location01Icon,+ Navigation03Icon,+ RemoveCircleIcon,+ StarOffIcon,+ Time04Icon,+ Unarchive03Icon,+ UserAdd02Icon,+ ViewIcon,+ ViewOffSlashIcon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";+import {+ ListItemIcon,+ ListItemText,+ Menu,+ MenuItem,+ styled,+} from "@mui/material";+import { StarBorderIcon } from "ente-new/photos/components/icons/StarIcon";+import type { FileContextAction } from "ente-new/photos/utils/file-actions";+import { t } from "i18next";+import React, { memo, useCallback, useMemo } from "react";++/**+ * Position for anchoring the context menu.+ */+export interface ContextMenuPosition {+ top: number;+ left: number;+}++interface FileContextMenuProps {+ /** Whether the menu is open. */+ open: boolean;+ /** The position to anchor the menu at. */+ anchorPosition: ContextMenuPosition | undefined;+ /** Callback when the menu should close. */+ onClose: () => void;+ /** The actions to display in the menu. */+ actions: FileContextAction[];+ /** Callback when an action is selected. */+ onAction: (action: FileContextAction) => void;+ /** Number of files currently selected. */+}++interface ActionConfig {+ label: string;+ Icon: React.ReactNode;+ isDestructive?: boolean;+}++const hugeIcon = (icon: IconSvgElement, size = 20) => (+ <HugeiconsIcon icon={icon} size={size} />+);++const actionConfigs: Record<FileContextAction, ActionConfig> = {+ sendLink: { label: "Send link", Icon: hugeIcon(Navigation03Icon) },+ download: { label: "download", Icon: hugeIcon(Download01Icon) },+ fixTime: { label: "fix_creation_time", Icon: hugeIcon(Time04Icon) },+ editLocation: { label: "edit_location", Icon: hugeIcon(Location01Icon) },+ favorite: { label: "favorite", Icon: <StarBorderIcon fontSize="small" /> },+ unfavorite: { label: "un_favorite", Icon: hugeIcon(StarOffIcon) },+ archive: { label: "archive", Icon: hugeIcon(Download05Icon) },+ unarchive: { label: "unarchive", Icon: hugeIcon(Unarchive03Icon) },+ hide: { label: "hide", Icon: hugeIcon(ViewOffSlashIcon) },+ unhide: { label: "unhide", Icon: hugeIcon(ViewIcon) },+ trash: {+ label: "delete",+ Icon: hugeIcon(Delete02Icon),+ isDestructive: true,+ },+ deletePermanently: {+ label: "delete_permanently",+ Icon: hugeIcon(Delete02Icon),+ isDestructive: true,+ },+ restore: { label: "restore", Icon: hugeIcon(Clock02Icon) },+ addToAlbum: { label: "add", Icon: hugeIcon(AddSquareIcon) },+ moveToAlbum: { label: "move", Icon: hugeIcon(ArrowRight02Icon) },+ removeFromAlbum: { label: "remove", Icon: hugeIcon(RemoveCircleIcon) },+ addPerson: { label: "add_a_person", Icon: hugeIcon(UserAdd02Icon) },+};++/**+ * Context menu for file operations, displayed on right-click of file+ * thumbnails.+ *+ * This component renders a single Menu instance that is positioned based on+ * mouse coordinates. It should be rendered once at the FileList level, not per+ * thumbnail.+ */+export const FileContextMenu: React.FC<FileContextMenuProps> = memo(+ ({ open, anchorPosition, onClose, actions, onAction }) => {+ const handleActionClick = useCallback(+ (action: FileContextAction) => {+ onClose();+ onAction(action);+ },+ [onClose, onAction],+ );++ // Separate primary and destructive actions in a single pass+ const [primaryActions, destructiveActions] = useMemo(() => {+ const primary: FileContextAction[] = [];+ const destructive: FileContextAction[] = [];+ for (const action of actions) {+ if (actionConfigs[action].isDestructive) {+ destructive.push(action);+ } else {+ primary.push(action);+ }+ }+ return [primary, destructive];+ }, [actions]);++ return (+ <StyledMenu+ open={open}+ onClose={onClose}+ disableAutoFocusItem+ anchorReference="anchorPosition"+ anchorPosition={anchorPosition}+ slotProps={{+ root: {+ onContextMenu: (e: React.MouseEvent) =>+ e.preventDefault(),+ },+ }}+ >+ {primaryActions.map((action) => {+ const { label, Icon } = actionConfigs[action];+ return (+ <StyledMenuItem+ key={action}+ onClick={() => handleActionClick(action)}+ >+ <ListItemIcon>{Icon}</ListItemIcon>+ <ListItemText>{t(label)}</ListItemText>+ </StyledMenuItem>+ );+ })}++ {destructiveActions.map((action) => {+ const { label, Icon } = actionConfigs[action];+ return (+ <StyledMenuItem+ key={action}+ onClick={() => handleActionClick(action)}+ sx={{+ color: "critical.main",+ "&:hover": {+ backgroundColor: "critical.main",+ color: "#fff",+ },+ }}+ >+ <ListItemIcon sx={{ color: "inherit" }}>+ {Icon}+ </ListItemIcon>+ <ListItemText>{t(label)}</ListItemText>+ </StyledMenuItem>+ );+ })}+ </StyledMenu>+ );+ },+);++FileContextMenu.displayName = "FileContextMenu";++const StyledMenu = styled(Menu)(({ theme }) => ({+ "& .MuiPaper-root": {+ backgroundColor: "#1f1f1f",+ minWidth: 220,+ borderRadius: 12,+ boxShadow: "0 8px 24px rgba(0, 0, 0, 0.35)",+ marginTop: 6,+ },+ "& .MuiList-root": { padding: theme.spacing(1) },+ ...theme.applyStyles("dark", {+ "& .MuiPaper-root": {+ backgroundColor: "#161616",+ boxShadow: "0 8px 24px rgba(0, 0, 0, 0.6)",+ },+ }),+}));++const StyledMenuItem = styled(MenuItem)(({ theme }) => ({+ display: "flex",+ alignItems: "center",+ gap: 12,+ padding: theme.spacing(1.5, 2),+ borderRadius: 10,+ color: "#f5f5f5",+ fontSize: 15,+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.08)" },+ "& .MuiListItemIcon-root": { minWidth: 0, color: "inherit" },+ "& .MuiListItemText-root": { margin: 0 },+ "& .MuiListItemText-primary": { color: "inherit", fontSize: "inherit" },+}));diff --git a/web/apps/albums/vendor/ente-new/photos/components/FileDateTimePicker.tsx b/web/apps/albums/vendor/ente-new/photos/components/FileDateTimePicker.tsxnew file mode 100644index 0000000000..de1e3740c8--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/FileDateTimePicker.tsx@@ -0,0 +1,151 @@+import {+ LocalizationProvider,+ MobileDateTimePicker,+} from "@mui/x-date-pickers";+import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";+import dayjs, { Dayjs } from "dayjs";+import { useIsSmallWidth } from "ente-base/components/utils/hooks";+import type { ParsedMetadataDate } from "ente-media/file-metadata";+import React, { useState } from "react";++interface FileDateTimePickerProps {+ /**+ * The initial date to preselect in the date/time picker.+ *+ * If not provided, the current date/time is used.+ */+ initialValue?: Date;+ /**+ * Callback invoked when the user makes and confirms a date/time.+ */+ onAccept: (date: ParsedMetadataDate) => void;+ /**+ * Optional callback invoked when the picker has been closed.+ *+ * > Note: This is only informational, for the caller to update their state.+ * > The picker has already been closed at this point.+ */+ onDidClose?: () => void;+}++/**+ * A customized version of MUI DateTimePicker suitable for use in selecting and+ * modifying the date/time for a photo.+ *+ * On success, it returns a {@link ParsedMetadataDate} which contains the a+ * local date/time string representation of the selected date, the current UTC+ * offset, and an epoch timestamp. The idea is that the user is picking a+ * date/time in the hypothetical timezone of where the photo was taken.+ *+ * We return local (current) UTC offset, but this might be different from what+ * the user is imagining when they're picking a date. So it should be taken as+ * an advisory, and only used if the photo does not already have an associated+ * UTC offset. For more discussion of the caveats and nuances around this, see+ * [Note: Photos are always in local date/time].+ */+export const FileDateTimePicker: React.FC<FileDateTimePickerProps> = ({+ initialValue,+ onAccept,+ onDidClose,+}) => {+ const [open, setOpen] = useState(true);+ const [value, setValue] = useState<Dayjs | null>(dayjs(initialValue));++ const isSmallWidth = useIsSmallWidth();++ const handleAccept = (d: Dayjs | null) => {+ if (!dayjs.isDayjs(d))+ throw new Error(`Unexpected non-dayjs result ${typeof d}`);+ onAccept(parseMetadataDateFromDayjs(d));+ };++ const handleClose = () => {+ setOpen(false);+ onDidClose?.();+ };++ return (+ <LocalizationProvider dateAdapter={AdapterDayjs}>+ <MobileDateTimePicker+ value={value}+ onChange={(d) => setValue(d)}+ open={open}+ onClose={handleClose}+ onOpen={() => setOpen(true)}+ disableFuture={true}+ timeSteps={{ minutes: 1 }}+ /* The dialog grows too big on the default portrait mode with+ our theme customizations. So we instead use the landscape+ layout if the screen is large enough. */+ orientation={isSmallWidth ? "portrait" : "landscape"}+ onAccept={handleAccept}+ slots={{ field: EmptyField }}+ slotProps={{+ /* The time picker has a smaller height than the calendar,+ which causes an ungainly layout shift. Prevent this by+ giving a minimum height to the picker.++ The constant 336px will likely change in the future when+ MUI gets updated, so this solution is fragile. However+ MUI is anyways intending to replace the TimeClock with a+ DigitalTimePicker that has a better UX. */+ layout: {+ sx: { ".MuiTimeClock-root": { minHeight: "336px" } },+ },+ }}+ />+ </LocalizationProvider>+ );+};++/**+ * We don't wish to render any UI for the MUI DateTimePicker when it is closed,+ * and instead only wish to use it as a dialog that we trigger ourselves.+ *+ * To achieve this we provide this nop-DOM element as the "field" slot to the+ * date/time picker.+ *+ * See: https://mui.com/x/react-date-pickers/custom-field/+ */+const EmptyField: React.FC = () => <></>;++/**+ * A variant of {@link parseMetadataDate} that does the same thing, but for+ * {@link Dayjs} instances.+ */+const parseMetadataDateFromDayjs = (d: Dayjs): ParsedMetadataDate => {+ // `Dayjs.format` returns an ISO 8601 string of the form+ // 2020-04-02T08:02:17-05:00'.+ //+ // https://day.js.org/docs/en/display/format+ //+ // This is different from the JavaScript `Date.toISOString` which also+ // returns an ISO 8601 string, but with the time zone descriptor always set+ // to UTC Zulu ("Z").+ //+ // The behaviour of Dayjs.format is more convenient for us, since it does+ // both things we wish for:+ // - Display the date in the local timezone+ // - Include the timezone offset.++ const s = d.format();++ let dateTime: string;+ let offset: string | undefined;++ // Check to see if there is a time-zone descriptor of the form "Z" or+ // "±05:30" or "±0530" at the end of s.+ const m = /Z|[+-]\d\d:?\d\d$/.exec(s);+ if (m?.index) {+ dateTime = s.substring(0, m.index);+ offset = s.substring(m.index);+ } else {+ throw new Error(+ `Dayjs.format returned a string "${s}" without a timezone offset`,+ );+ }++ const timestamp = d.valueOf() * 1000;++ return { dateTime, offset, timestamp };+};diff --git a/web/apps/albums/vendor/ente-new/photos/components/ImageEditorOverlay.tsx b/web/apps/albums/vendor/ente-new/photos/components/ImageEditorOverlay.tsxnew file mode 100644index 0000000000..62e0b7b2aa--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/ImageEditorOverlay.tsx@@ -0,0 +1,1361 @@+/* TODO: Audit this file.+ All the bangs shouldn't be needed with better types / restructuring. */+/* eslint-disable @typescript-eslint/no-floating-promises */+/* eslint-disable @typescript-eslint/no-unnecessary-condition */+/* eslint-disable react-hooks/exhaustive-deps */+/* eslint-disable @typescript-eslint/prefer-promise-reject-errors */+/* eslint-disable @typescript-eslint/no-unnecessary-type-assertion */++import ChevronRightIcon from "@mui/icons-material/ChevronRight";+import CloseIcon from "@mui/icons-material/Close";+import CloudUploadIcon from "@mui/icons-material/CloudUpload";+import CropIcon from "@mui/icons-material/Crop";+import Crop169Icon from "@mui/icons-material/Crop169";+import Crop32Icon from "@mui/icons-material/Crop32";+import CropOriginalIcon from "@mui/icons-material/CropOriginal";+import CropSquareIcon from "@mui/icons-material/CropSquare";+import DownloadIcon from "@mui/icons-material/Download";+import FlipIcon from "@mui/icons-material/Flip";+import MenuIcon from "@mui/icons-material/Menu";+import RotateLeftIcon from "@mui/icons-material/RotateLeft";+import RotateRightIcon from "@mui/icons-material/RotateRight";+import {+ Backdrop,+ Box,+ Button,+ CircularProgress,+ IconButton,+ Slider,+ Stack,+ styled,+ Tab,+ Tabs,+ Typography,+} from "@mui/material";+import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";+import { SidebarDrawer } from "ente-base/components/mui/SidebarDrawer";+import {+ RowButton,+ RowButtonDivider,+ RowButtonGroup,+ RowButtonGroupTitle,+ RowSwitch,+} from "ente-base/components/RowButton";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import { useBaseContext } from "ente-base/context";+import { nameAndExtension } from "ente-base/file-name";+import log from "ente-base/log";+import { saveAsFileAndRevokeObjectURL } from "ente-base/utils/web";+import { downloadManager } from "ente-gallery/services/download";+import type { Collection } from "ente-media/collection";+import type { EnteFile } from "ente-media/file";+import { fileFileName } from "ente-media/file-metadata";+import { t } from "i18next";+import React, {+ forwardRef,+ Fragment,+ useEffect,+ useRef,+ useState,+ type Ref,+ type RefObject,+} from "react";+import { savedCollections } from "../services/photos-fdb";++export type ImageEditorOverlayProps = ModalVisibilityProps & {+ /**+ * The (Ente) file to edit.+ */+ file: EnteFile;+ /**+ * Called when the user activates the button to save a copy of the given+ * {@link enteFile} to their Ente account with the edits they have made.+ *+ * @param editedFile A Web {@link File} containing the edited contents.+ * @param collection The collection to which the edited file should be+ * added.+ * @param enteFile The original {@link EnteFile}.+ */+ onSaveEditedCopy: (+ editedFile: File,+ collection: Collection,+ enteFile: EnteFile,+ ) => void;+};++const filterDefaultValues = {+ brightness: 100,+ contrast: 100,+ blur: 0,+ saturation: 100,+ invert: false,+};++type OperationTab = "crop" | "transform" | "colors";++interface CropBoxProps {+ x: number;+ y: number;+ width: number;+ height: number;+}++export const ImageEditorOverlay: React.FC<ImageEditorOverlayProps> = ({+ open,+ onClose,+ file,+ onSaveEditedCopy,+}) => {+ const { showMiniDialog } = useBaseContext();++ const canvasRef = useRef<HTMLCanvasElement | null>(null);+ const originalSizeCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const parentRef = useRef<HTMLDivElement | null>(null);++ const [fileURL, setFileURL] = useState<string | undefined>(undefined);+ // The MIME type of the original file that we are editing.+ //+ // It should generally be present, but it is not guaranteed to be.+ const [mimeType, setMIMEType] = useState<string | undefined>(undefined);++ const [currentRotationAngle, setCurrentRotationAngle] = useState(0);++ const [currentTab, setCurrentTab] = useState<OperationTab>("transform");++ const [brightness, setBrightness] = useState(+ filterDefaultValues.brightness,+ );+ const [contrast, setContrast] = useState(filterDefaultValues.contrast);+ const [blur, setBlur] = useState(filterDefaultValues.blur);+ const [saturation, setSaturation] = useState(+ filterDefaultValues.saturation,+ );+ const [invert, setInvert] = useState(filterDefaultValues.invert);++ const [transformationPerformed, setTransformationPerformed] =+ useState(false);+ const [coloursAdjusted, setColoursAdjusted] = useState(false);++ const [canvasLoading, setCanvasLoading] = useState(false);++ const [showControlsDrawer, setShowControlsDrawer] = useState(true);++ const [previewCanvasScale, setPreviewCanvasScale] = useState(0);++ const [cropBox, setCropBox] = useState<CropBoxProps>({+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ });++ const [startX, setStartX] = useState(0);+ const [startY, setStartY] = useState(0);++ const [beforeGrowthHeight, setBeforeGrowthHeight] = useState(0);+ const [beforeGrowthWidth, setBeforeGrowthWidth] = useState(0);++ const [isDragging, setIsDragging] = useState(false);+ const [isGrowing, setIsGrowing] = useState(false);++ const cropBoxRef = useRef<HTMLDivElement>(null);++ const getCanvasBoundsOffsets = () => {+ const canvasBounds = {+ height: canvasRef.current!.height,+ width: canvasRef.current!.width,+ };+ const parentBounds = parentRef.current!.getBoundingClientRect();++ // calculate the offset created by centering the canvas in its parent+ const offsetX = (parentBounds.width - canvasBounds.width) / 2;+ const offsetY = (parentBounds.height - canvasBounds.height) / 2;++ return { offsetY, offsetX, canvasBounds, parentBounds };+ };++ const handleDragStart: React.MouseEventHandler = (e) => {+ if (currentTab != "crop") return;++ const rect = cropBoxRef.current!.getBoundingClientRect();+ const offsetX = e.pageX - rect.left - rect.width / 2;+ const offsetY = e.pageY - rect.top - rect.height / 2;++ // The threshold near the corners of the crop box in which dragging is+ // assumed as not the intention.+ const cornerThreshold = 20;++ // check if the cursor is near the corners of the box+ const isNearLeftOrRightEdge =+ e.pageX < rect.left + cornerThreshold ||+ e.pageX > rect.right - cornerThreshold;+ const isNearTopOrBottomEdge =+ e.pageY < rect.top + cornerThreshold ||+ e.pageY > rect.bottom - cornerThreshold;++ if (isNearLeftOrRightEdge && isNearTopOrBottomEdge) {+ // cursor is near a corner, do not initiate dragging+ setIsGrowing(true);+ setStartX(e.pageX);+ setStartY(e.pageY);+ setBeforeGrowthWidth(cropBox.width);+ setBeforeGrowthHeight(cropBox.height);+ return;+ }++ setIsDragging(true);+ setStartX(e.pageX - offsetX);+ setStartY(e.pageY - offsetY);+ };++ const handleDrag: React.MouseEventHandler = (e) => {+ if (!isDragging && !isGrowing) return;++ // d- variables are the delta change between start and now+ const dx = e.pageX - startX;+ const dy = e.pageY - startY;++ const { offsetX, offsetY, canvasBounds } = getCanvasBoundsOffsets();++ if (isGrowing) {+ setCropBox((prev) => {+ const newWidth = Math.min(+ beforeGrowthWidth + dx,+ canvasBounds.width - prev.x + offsetX,+ );+ const newHeight = Math.min(+ beforeGrowthHeight + dy,+ canvasBounds.height - prev.y + offsetY,+ );++ return { ...prev, width: newWidth, height: newHeight };+ });+ } else {+ setCropBox((prev) => {+ let newX = prev.x + dx;+ let newY = prev.y + dy;++ // constrain the new position to the canvas boundaries, accounting for the offset+ newX = Math.max(+ offsetX,+ Math.min(newX, offsetX + canvasBounds.width - prev.width),+ );+ newY = Math.max(+ offsetY,+ Math.min(newY, offsetY + canvasBounds.height - prev.height),+ );++ return { ...prev, x: newX, y: newY };+ });+ setStartX(e.pageX);+ setStartY(e.pageY);+ }+ };++ const handleDragEnd: React.MouseEventHandler = () => {+ setStartX(0);+ setStartY(0);++ setIsGrowing(false);+ setIsDragging(false);+ };++ const resetCropBox = () => {+ setCropBox((prev) => {+ const { offsetX, offsetY, canvasBounds } = getCanvasBoundsOffsets();++ return {+ ...prev,+ x: offsetX,+ y: offsetY,+ height: canvasBounds.height,+ width: canvasBounds.width,+ };+ });+ };++ useEffect(() => {+ if (!canvasRef.current) {+ return;+ }+ try {+ applyFilters([canvasRef.current, originalSizeCanvasRef.current!]);+ setColoursAdjusted(+ brightness !== filterDefaultValues.brightness ||+ contrast !== filterDefaultValues.contrast ||+ blur !== filterDefaultValues.blur ||+ saturation !== filterDefaultValues.saturation ||+ invert !== filterDefaultValues.invert,+ );+ } catch (e) {+ log.error("Error applying filters", e);+ }+ }, [brightness, contrast, blur, saturation, invert, canvasRef, fileURL]);++ useEffect(() => {+ if (currentTab != "crop") return;+ resetCropBox();+ setShowControlsDrawer(false);+ }, [currentTab]);++ const applyFilters = async (canvases: HTMLCanvasElement[]) => {+ try {+ for (const canvas of canvases) {+ const blurSizeRatio =+ Math.min(canvas.width, canvas.height) /+ Math.min(+ canvasRef.current!.width,+ canvasRef.current!.height,+ );+ const blurRadius = blurSizeRatio * blur;+ const filterString = `brightness(${brightness}%) contrast(${contrast}%) blur(${blurRadius}px) saturate(${saturation}%) invert(${+ invert ? 1 : 0+ })`;+ const ctx = canvas.getContext("2d")!;+ ctx.imageSmoothingEnabled = false;++ ctx.filter = filterString;++ const image = new Image();+ image.src = fileURL!;++ await new Promise((resolve, reject) => {+ image.onload = () => {+ try {+ ctx.clearRect(0, 0, canvas.width, canvas.height);+ ctx.save();+ ctx.drawImage(+ image,+ 0,+ 0,+ canvas.width,+ canvas.height,+ );+ ctx.restore();+ resolve(true);+ } catch (e) {+ reject(e);+ }+ };+ });+ }+ } catch (e) {+ log.error("Error applying filters", e);+ throw e;+ }+ };++ useEffect(() => {+ if (currentRotationAngle >= 360 || currentRotationAngle <= -360) {+ // set back to 0+ setCurrentRotationAngle(0);+ }+ }, [currentRotationAngle]);++ const resetFilters = () => {+ setBrightness(100);+ setContrast(100);+ setBlur(0);+ setSaturation(100);+ setInvert(false);+ };++ const loadCanvas = async () => {+ try {+ if (+ !canvasRef.current ||+ !parentRef.current ||+ !originalSizeCanvasRef.current+ ) {+ return;+ }++ setCanvasLoading(true);++ resetFilters();+ setCurrentRotationAngle(0);++ const img = new Image();+ const ctx = canvasRef.current.getContext("2d")!;+ ctx.imageSmoothingEnabled = false;+ if (!fileURL) {+ const sourceURLs =+ await downloadManager.renderableSourceURLs(file);+ if (sourceURLs.type != "image") {+ throw new Error("Image editor invoked for non-image file");+ }+ img.src = sourceURLs.imageURL;+ setFileURL(sourceURLs.imageURL);+ setMIMEType(sourceURLs.mimeType);+ } else {+ img.src = fileURL;+ }++ await new Promise((resolve, reject) => {+ img.onload = () => {+ try {+ const scale = Math.min(+ parentRef.current!.clientWidth / img.width,+ parentRef.current!.clientHeight / img.height,+ );+ setPreviewCanvasScale(scale);++ const width = img.width * scale;+ const height = img.height * scale;+ canvasRef.current!.width = width;+ canvasRef.current!.height = height;++ ctx?.drawImage(img, 0, 0, width, height);++ originalSizeCanvasRef.current!.width = img.width;+ originalSizeCanvasRef.current!.height = img.height;++ const oSCtx =+ originalSizeCanvasRef.current!.getContext("2d");++ oSCtx?.drawImage(img, 0, 0, img.width, img.height);++ setTransformationPerformed(false);+ setColoursAdjusted(false);++ setCanvasLoading(false);++ resetCropBox();+ setStartX(0);+ setStartY(0);+ setIsDragging(false);+ setIsGrowing(false);++ resolve(true);+ } catch (e) {+ reject(e);+ }+ };+ img.onerror = (e) => {+ reject(e);+ };+ });+ } catch (e) {+ log.error("Error loading canvas", e);+ }+ };++ useEffect(() => {+ if (!open || !file) return;+ void loadCanvas();+ }, [open, file]);++ const handleClose = () => {+ setFileURL(undefined);+ onClose();+ };++ const handleCloseWithConfirmation = () => {+ if (transformationPerformed || coloursAdjusted) {+ showMiniDialog(confirmEditorCloseDialogAttributes(handleClose));+ } else {+ handleClose();+ }+ };++ if (!open) {+ return <></>;+ }++ const getEditedFile = async () => {+ const originalSizeCanvas = originalSizeCanvasRef.current!;+ const originalFileName = fileFileName(file);+ return canvasToFile(originalSizeCanvas, originalFileName, mimeType);+ };++ const downloadEditedPhoto = async () => {+ if (!canvasRef.current) return;++ const f = await getEditedFile();+ saveAsFileAndRevokeObjectURL(URL.createObjectURL(f), f.name);+ };++ const saveCopyToEnte = async () => {+ if (!canvasRef.current) return;+ try {+ const collections = await savedCollections();+ const collection = collections.find(+ (c) => c.id == file.collectionID,+ );+ onSaveEditedCopy(await getEditedFile(), collection!, file);+ setFileURL(undefined);+ } catch (e) {+ log.error("Error saving copy to ente", e);+ }+ };++ const applyCrop = () => {+ if (!cropBoxRef.current || !canvasRef.current) return;++ const { x1, x2, y1, y2 } = getCropRegionArgs(+ cropBoxRef.current,+ canvasRef.current,+ );+ setCanvasLoading(true);+ setTransformationPerformed(true);+ cropRegionOfCanvas(canvasRef.current, x1, y1, x2, y2);+ cropRegionOfCanvas(+ originalSizeCanvasRef.current!,+ x1 / previewCanvasScale,+ y1 / previewCanvasScale,+ x2 / previewCanvasScale,+ y2 / previewCanvasScale,+ );+ resetCropBox();+ setCanvasLoading(false);++ setCurrentTab("transform");+ };++ const menuProps = {+ originalSizeCanvasRef,+ canvasRef,+ setCanvasLoading,+ canvasLoading,+ setTransformationPerformed,+ setCurrentTab,+ };++ return (+ <Backdrop+ sx={{+ backgroundColor: "background.default" /* Opaque */,+ width: "100%",+ zIndex: "var(--mui-zIndex-modal)",+ }}+ open+ >+ <Box sx={{ padding: "1rem", width: "100%", height: "100%" }}>+ <Stack+ direction="row"+ sx={{+ justifyContent: "space-between",+ alignItems: "center",+ }}+ >+ <Typography variant="h2" sx={{ fontWeight: "medium" }}>+ {t("photo_editor")}+ </Typography>+ <IconButton+ onClick={() => {+ setShowControlsDrawer(true);+ }}+ >+ <MenuIcon />+ </IconButton>+ </Stack>+ <Stack+ direction="row"+ onMouseUp={handleDragEnd}+ onMouseMove={isDragging ? handleDrag : undefined}+ onMouseDown={handleDragStart}+ sx={{+ width: "100%",+ height: "100%",+ overflow: "hidden",+ boxSizing: "border-box",+ alignItems: "center",+ justifyContent: "center",+ position: "relative",+ }}+ >+ <Box+ sx={{+ position: "relative",+ width: "100%",+ height: "100%",+ }}+ >+ <Stack+ ref={parentRef}+ direction="row"+ sx={{+ height: "88%",+ width: "100%",+ alignItems: "center",+ justifyContent: "center",+ position: "relative",+ }}+ >+ {(!fileURL || canvasLoading) && (+ <CircularProgress />+ )}++ <canvas+ ref={canvasRef}+ style={{+ objectFit: "contain",+ display:+ !fileURL || canvasLoading+ ? "none"+ : "block",+ position: "absolute",+ }}+ />+ <canvas+ ref={originalSizeCanvasRef}+ style={{ display: "none" }}+ />++ {currentTab == "crop" && (+ <FreehandCropRegion+ cropBox={cropBox}+ ref={cropBoxRef}+ setIsDragging={setIsDragging}+ />+ )}+ </Stack>+ {currentTab == "crop" && (+ <Stack sx={{ mt: 2, alignItems: "center" }}>+ <Button+ color="accent"+ startIcon={<CropIcon />}+ onClick={applyCrop}+ >+ {t("apply_crop")}+ </Button>+ </Stack>+ )}+ </Box>+ </Stack>+ </Box>+ <SidebarDrawer+ variant="persistent"+ anchor="right"+ open={showControlsDrawer}+ onClose={handleCloseWithConfirmation}+ >+ <Stack direction="row" sx={{ justifyContent: "space-between" }}>+ <IconButton+ onClick={() => {+ setShowControlsDrawer(false);+ }}+ >+ <ChevronRightIcon />+ </IconButton>+ <IconButton onClick={handleCloseWithConfirmation}>+ <CloseIcon />+ </IconButton>+ </Stack>+ <Stack+ direction="row"+ sx={{ gap: "0.5rem", marginBottom: "1rem" }}+ >+ <Tabs+ value={currentTab}+ onChange={(_, value) => {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument+ setCurrentTab(value);+ }}+ >+ <Tab label={t("crop")} value="crop" />+ <Tab label={t("transform")} value="transform" />+ <Tab+ label={t("colors")}+ value="colors"+ disabled={transformationPerformed}+ />+ </Tabs>+ </Stack>+ <RowButtonGroupTitle>{t("reset")}</RowButtonGroupTitle>+ <RowButtonGroup sx={{ mb: "0.5rem" }}>+ <RowButton+ disabled={canvasLoading}+ startIcon={<CropOriginalIcon />}+ label={t("restore_original")}+ onClick={() => void loadCanvas()}+ />+ </RowButtonGroup>+ {currentTab == "crop" && (+ <CropMenu+ {...menuProps}+ previewScale={previewCanvasScale}+ cropBoxProps={cropBox}+ cropBoxRef={cropBoxRef}+ resetCropBox={resetCropBox}+ />+ )}+ {currentTab == "transform" && <TransformMenu {...menuProps} />}+ {currentTab == "colors" && (+ <ColoursMenu+ brightness={brightness}+ contrast={contrast}+ saturation={saturation}+ blur={blur}+ invert={invert}+ setBrightness={setBrightness}+ setContrast={setContrast}+ setSaturation={setSaturation}+ setBlur={setBlur}+ setInvert={setInvert}+ />+ )}+ <RowButtonGroupTitle>{t("export_data")}</RowButtonGroupTitle>+ <RowButtonGroup>+ <RowButton+ disabled={!transformationPerformed && !coloursAdjusted}+ startIcon={<DownloadIcon />}+ label={t("download_edited")}+ onClick={downloadEditedPhoto}+ />+ <RowButtonDivider />+ <RowButton+ disabled={!transformationPerformed && !coloursAdjusted}+ startIcon={<CloudUploadIcon />}+ label={t("save_a_copy_to_ente")}+ onClick={saveCopyToEnte}+ />+ </RowButtonGroup>+ </SidebarDrawer>+ </Backdrop>+ );+};++const confirmEditorCloseDialogAttributes = (+ onConfirm: () => void,+): MiniDialogAttributes => ({+ title: t("discard_changes"),+ message: t("discard_changes_message"),+ continue: { text: t("discard"), color: "critical", action: onConfirm },+});++/**+ * Create a new {@link File} with the contents of the given canvas.+ *+ * @param canvas A {@link HTMLCanvasElement} whose contents we want to download+ * as a file.+ *+ * @param originalFileName The name of the original file which was used to seed+ * the canvas. This will be used as a base name for the generated file (with an+ * "-edited" suffix).+ *+ * @param originalMIMEType The MIME type of the original file which was used to+ * seed the canvas. When possible, we try to download a file in the same format,+ * but this is not guaranteed and depends on browser support. If the original+ * MIME type can not be preserved, a PNG file will be downloaded.+ */+const canvasToFile = async (+ canvas: HTMLCanvasElement,+ originalFileName: string,+ originalMIMEType?: string,+): Promise<File> => {+ const image = new Image();+ image.src = canvas.toDataURL();++ // Browsers are required to support "image/png". They may also support+ // "image/jpeg" and "image/webp". Potentially they may even support more+ // formats, but to keep this scoped we limit to these three.+ let [mimeType, extension] = ["image/png", "png"];+ switch (originalMIMEType) {+ case "image/jpeg":+ mimeType = originalMIMEType;+ extension = "jpeg";+ break;+ case "image/webp":+ mimeType = originalMIMEType;+ extension = "webp";+ break;+ default:+ break;+ }++ const blob = (await new Promise<Blob>((resolve) =>+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ // @ts-ignore+ canvas.toBlob(resolve, mimeType),+ ))!;++ const [originalName] = nameAndExtension(originalFileName);+ const fileName = `${originalName}-edited.${extension}`;++ log.debug(() => ["canvas => file", { blob, type: blob.type, mimeType }]);++ return new File([blob], fileName);+};++interface CommonMenuProps {+ canvasRef: RefObject<HTMLCanvasElement | null>;+ originalSizeCanvasRef: RefObject<HTMLCanvasElement | null>;+ setTransformationPerformed: (v: boolean) => void;+ canvasLoading: boolean;+ setCanvasLoading: (v: boolean) => void;+ setCurrentTab: (tab: OperationTab) => void;+}++type CropMenuProps = CommonMenuProps & {+ previewScale: number;+ cropBoxProps: CropBoxProps;+ cropBoxRef: RefObject<HTMLDivElement | null>;+ resetCropBox: () => void;+};++const CropMenu: React.FC<CropMenuProps> = (props) => {+ const {+ canvasRef,+ originalSizeCanvasRef,+ canvasLoading,+ setCanvasLoading,+ setTransformationPerformed,+ setCurrentTab,+ } = props;++ return (+ <>+ <RowButtonGroupTitle>{t("freehand")}</RowButtonGroupTitle>+ <RowButtonGroup sx={{ mb: "0.5rem" }}>+ <RowButton+ disabled={canvasLoading}+ startIcon={<CropIcon />}+ label={t("apply_crop")}+ onClick={() => {+ if (!props.cropBoxRef.current || !canvasRef.current)+ return;++ const { x1, x2, y1, y2 } = getCropRegionArgs(+ props.cropBoxRef.current,+ canvasRef.current,+ );+ setCanvasLoading(true);+ setTransformationPerformed(true);+ cropRegionOfCanvas(canvasRef.current, x1, y1, x2, y2);+ cropRegionOfCanvas(+ originalSizeCanvasRef.current!,+ x1 / props.previewScale,+ y1 / props.previewScale,+ x2 / props.previewScale,+ y2 / props.previewScale,+ );+ props.resetCropBox();+ setCanvasLoading(false);++ setCurrentTab("transform");+ }}+ />+ </RowButtonGroup>+ </>+ );+};++const cropRegionOfCanvas = (+ canvas: HTMLCanvasElement,+ topLeftX: number,+ topLeftY: number,+ bottomRightX: number,+ bottomRightY: number,+ scale = 1,+) => {+ const context = canvas.getContext("2d");+ if (!context || !canvas) return;+ context.imageSmoothingEnabled = false;++ const width = (bottomRightX - topLeftX) * scale;+ const height = (bottomRightY - topLeftY) * scale;++ const img = new Image();+ img.src = canvas.toDataURL();+ img.onload = () => {+ context.clearRect(0, 0, canvas.width, canvas.height);++ canvas.width = width;+ canvas.height = height;++ context.drawImage(+ img,+ topLeftX,+ topLeftY,+ width,+ height,+ 0,+ 0,+ width,+ height,+ );+ };+};++const getCropRegionArgs = (+ cropBoxEle: HTMLDivElement,+ canvasEle: HTMLCanvasElement,+) => {+ // get the bounding rectangle of the crop box+ const cropBoxRect = cropBoxEle.getBoundingClientRect();+ // Get the bounding rectangle of the canvas+ const canvasRect = canvasEle.getBoundingClientRect();++ // calculate the scale of the canvas display relative to its actual dimensions+ const displayScale = canvasEle.width / canvasRect.width;++ // calculate the coordinates of the crop box relative to the canvas and adjust for any scrolling by adding scroll offsets+ const x1 =+ (cropBoxRect.left - canvasRect.left + window.scrollX) * displayScale;+ const y1 =+ (cropBoxRect.top - canvasRect.top + window.scrollY) * displayScale;+ const x2 = x1 + cropBoxRect.width * displayScale;+ const y2 = y1 + cropBoxRect.height * displayScale;++ return { x1, x2, y1, y2 };+};++interface FreehandCropRegionProps {+ cropBox: CropBoxProps;+ setIsDragging: (v: boolean) => void;+}++const FreehandCropRegion = forwardRef(+ (+ { cropBox, setIsDragging }: FreehandCropRegionProps,+ ref: Ref<HTMLDivElement>,+ ) => {+ return (+ <>+ {/* Top overlay */}+ <CropOverlayRegionTemplate+ // Height up to the top of the crop box.+ sx={{ top: 0, left: 0, right: 0, height: `${cropBox.y}px` }}+ />++ {/* Bottom overlay */}+ <CropOverlayRegionTemplate+ // Height from the bottom of the crop box to the bottom of+ // the canvas.+ sx={{+ bottom: 0,+ left: 0,+ right: 0,+ height: `calc(100% - ${cropBox.y + cropBox.height}px)`,+ }}+ />++ {/* Left overlay */}+ <CropOverlayRegionTemplate+ sx={{+ top: `${cropBox.y}px`,+ left: 0,+ // Width up to the left side of the crop box.+ width: `${cropBox.x}px`,+ // Same height as the crop box.+ height: `${cropBox.height}px`,+ }}+ />++ {/* Right overlay */}+ <CropOverlayRegionTemplate+ sx={{+ top: `${cropBox.y}px`,+ right: 0,+ // Width from the right side of the crop box to the+ // right side of the canvas.+ width: `calc(100% - ${cropBox.x + cropBox.width}px)`,+ // Same height as the crop box.+ height: `${cropBox.height}px`,+ }}+ />++ <div+ style={{+ display: "grid",+ position: "absolute",+ left: `${cropBox.x}px`,+ top: `${cropBox.y}px`,+ width: `${cropBox.width}px`,+ height: `${cropBox.height}px`,+ border: "1px solid white",+ gridTemplateColumns: "1fr 1fr 1fr",+ gridTemplateRows: "1fr 1fr 1fr",+ gap: "0px",+ }}+ ref={ref}+ >+ {Array.from({ length: 9 }).map((_, index) => (+ <Box+ key={index}+ sx={{+ border: "1px solid",+ borderColor: "white",+ boxSizing: "border-box",+ pointerEvents: "none",+ }}+ ></Box>+ ))}++ <Box+ sx={{+ position: "absolute",+ height: "10px",+ width: "10px",+ backgroundColor: "white",+ border: "1px solid",+ borderColor: "black",+ right: "-5px",+ bottom: "-5px",+ cursor: "se-resize",+ }}+ onMouseDown={(e) => {+ e.preventDefault();+ setIsDragging(true);+ }}+ ></Box>+ </div>+ </>+ );+ },+);++const CropOverlayRegionTemplate = styled("div")({+ position: "absolute",+ backgroundColor: "rgba(0 0 0 / 0.5)",+ pointerEvents: "none",+});++const presetAspectRatios = [+ { width: 16, height: 9, icon: <CropSquareIcon /> },+ { width: 3, height: 2, icon: <Crop32Icon /> },+ { width: 16, height: 10, icon: <Crop169Icon /> },+];++const TransformMenu: React.FC<CommonMenuProps> = ({+ canvasRef,+ originalSizeCanvasRef,+ canvasLoading,+ setCanvasLoading,+ setTransformationPerformed,+}) => {+ // Crops the canvas according to originalHeight and originalWidth without compounding+ const cropCanvas = (+ canvas: HTMLCanvasElement,+ widthRatio: number,+ heightRatio: number,+ ) => {+ const context = canvas.getContext("2d");++ const aspectRatio = widthRatio / heightRatio;++ if (!context || !canvas) return;+ context.imageSmoothingEnabled = false;++ const img = new Image();+ img.src = canvas.toDataURL();+ img.onload = () => {+ const sourceWidth = img.width;+ const sourceHeight = img.height;++ let sourceX = 0;+ let sourceY = 0;++ if (sourceWidth / sourceHeight > aspectRatio) {+ sourceX = (sourceWidth - sourceHeight * aspectRatio) / 2;+ } else {+ sourceY = (sourceHeight - sourceWidth / aspectRatio) / 2;+ }++ const newWidth = sourceWidth - 2 * sourceX;+ const newHeight = sourceHeight - 2 * sourceY;++ context.clearRect(0, 0, canvas.width, canvas.height);++ canvas.width = newWidth;+ canvas.height = newHeight;++ context.drawImage(+ img,+ sourceX,+ sourceY,+ newWidth,+ newHeight,+ 0,+ 0,+ newWidth,+ newHeight,+ );+ };+ };++ const flipCanvas = (+ canvas: HTMLCanvasElement,+ direction: "vertical" | "horizontal",+ ) => {+ const context = canvas.getContext("2d");+ if (!context || !canvas) return;+ context.resetTransform();+ context.imageSmoothingEnabled = false;+ const img = new Image();+ img.src = canvas.toDataURL();++ img.onload = () => {+ context.clearRect(0, 0, canvas.width, canvas.height);++ context.save();++ if (direction == "horizontal") {+ context.translate(canvas.width, 0);+ context.scale(-1, 1);+ } else {+ context.translate(0, canvas.height);+ context.scale(1, -1);+ }++ context.drawImage(img, 0, 0, canvas.width, canvas.height);++ context.restore();+ };+ };++ const rotateCanvas = (canvas: HTMLCanvasElement, angle: number) => {+ const context = canvas?.getContext("2d");+ if (!context || !canvas) return;+ context.imageSmoothingEnabled = false;++ const image = new Image();+ image.src = canvas.toDataURL();++ image.onload = () => {+ context.clearRect(0, 0, canvas.width, canvas.height);++ context.save();++ const radians = (angle * Math.PI) / 180;+ const sin = Math.sin(radians);+ const cos = Math.cos(radians);+ const newWidth =+ Math.abs(image.width * cos) + Math.abs(image.height * sin);+ const newHeight =+ Math.abs(image.width * sin) + Math.abs(image.height * cos);++ canvas.width = newWidth;+ canvas.height = newHeight;++ context.translate(canvas.width / 2, canvas.height / 2);+ context.rotate(radians);++ context.drawImage(+ image,+ -image.width / 2,+ -image.height / 2,+ image.width,+ image.height,+ );++ context.restore();+ };+ };++ const createCropHandler =+ (widthRatio: number, heightRatio: number) => () => {+ try {+ setCanvasLoading(true);+ cropCanvas(canvasRef.current!, widthRatio, heightRatio);+ cropCanvas(+ originalSizeCanvasRef.current!,+ widthRatio,+ heightRatio,+ );+ setCanvasLoading(false);+ setTransformationPerformed(true);+ } catch (e) {+ log.error(+ `crop handler failed - ${JSON.stringify({+ widthRatio,+ heightRatio,+ })}`,+ e,+ );+ }+ };+ const createRotationHandler = (rotation: "left" | "right") => () => {+ try {+ setCanvasLoading(true);+ rotateCanvas(canvasRef.current!, rotation == "left" ? -90 : 90);+ rotateCanvas(+ originalSizeCanvasRef.current!,+ rotation == "left" ? -90 : 90,+ );+ setCanvasLoading(false);+ setTransformationPerformed(true);+ } catch (e) {+ log.error(`rotation handler (${rotation}) failed`, e);+ }+ };++ const createFlipCanvasHandler =+ (direction: "vertical" | "horizontal") => () => {+ try {+ setCanvasLoading(true);+ flipCanvas(canvasRef.current!, direction);+ flipCanvas(originalSizeCanvasRef.current!, direction);+ setCanvasLoading(false);+ setTransformationPerformed(true);+ } catch (e) {+ log.error(`flip handler ${direction} failed`, e);+ }+ };++ return (+ <>+ <RowButtonGroupTitle>{t("aspect_ratio")}</RowButtonGroupTitle>+ <RowButtonGroup sx={{ mb: "0.5rem" }}>+ <RowButton+ disabled={canvasLoading}+ startIcon={<CropSquareIcon />}+ label={t("square") + " (1:1)"}+ onClick={createCropHandler(1, 1)}+ />+ </RowButtonGroup>+ <RowButtonGroup sx={{ mb: "1rem" }}>+ {presetAspectRatios.map((ratio, index) => (+ <Fragment key={index}>+ <RowButton+ disabled={canvasLoading}+ startIcon={ratio.icon}+ label={`${ratio.width}:${ratio.height}`}+ onClick={createCropHandler(+ ratio.width,+ ratio.height,+ )}+ />+ {index !== presetAspectRatios.length - 1 && (+ <RowButtonDivider />+ )}+ </Fragment>+ ))}+ </RowButtonGroup>+ <RowButtonGroup sx={{ mb: "1rem" }}>+ {presetAspectRatios.map((ratio, index) => (+ <Fragment key={index}>+ <RowButton+ key={index}+ disabled={canvasLoading}+ startIcon={ratio.icon}+ label={`${ratio.height}:${ratio.width}`}+ onClick={createCropHandler(+ ratio.height,+ ratio.width,+ )}+ />+ {index !== presetAspectRatios.length - 1 && (+ <RowButtonDivider />+ )}+ </Fragment>+ ))}+ </RowButtonGroup>+ <RowButtonGroupTitle>{t("rotation")}</RowButtonGroupTitle>+ <RowButtonGroup sx={{ mb: "1rem" }}>+ <RowButton+ disabled={canvasLoading}+ startIcon={<RotateLeftIcon />}+ label={t("rotate_left") + " 90˚"}+ onClick={createRotationHandler("left")}+ />+ <RowButtonDivider />+ <RowButton+ disabled={canvasLoading}+ startIcon={<RotateRightIcon />}+ label={t("rotate_right") + " 90˚"}+ onClick={createRotationHandler("right")}+ />+ </RowButtonGroup>+ <RowButtonGroupTitle>{t("flip")}</RowButtonGroupTitle>+ <RowButtonGroup sx={{ mb: "1rem" }}>+ <RowButton+ disabled={canvasLoading}+ startIcon={+ <FlipIcon style={{ transform: "rotateZ(90deg)" }} />+ }+ label={t("flip_vertically")}+ onClick={createFlipCanvasHandler("vertical")}+ />+ <RowButtonDivider />+ <RowButton+ disabled={canvasLoading}+ startIcon={<FlipIcon />}+ label={t("flip_horizontally")}+ onClick={createFlipCanvasHandler("horizontal")}+ />+ </RowButtonGroup>+ </>+ );+};++interface ColoursMenuProps {+ brightness: number;+ contrast: number;+ saturation: number;+ blur: number;+ invert: boolean;+ setBrightness: (v: number) => void;+ setContrast: (v: number) => void;+ setSaturation: (v: number) => void;+ setBlur: (v: number) => void;+ setInvert: (v: boolean) => void;+}++const ColoursMenu: React.FC<ColoursMenuProps> = (props) => (+ <>+ <Box sx={{ px: "8px" }}>+ <RowButtonGroupTitle>{t("brightness")}</RowButtonGroupTitle>+ <Slider+ min={0}+ max={200}+ defaultValue={100}+ step={10}+ valueLabelDisplay="auto"+ value={props.brightness}+ marks={[{ value: 100, label: "100%" }]}+ onChange={(_, value) => {+ props.setBrightness(value as number);+ }}+ />+ <RowButtonGroupTitle>{t("contrast")}</RowButtonGroupTitle>+ <Slider+ min={0}+ max={200}+ defaultValue={100}+ step={10}+ valueLabelDisplay="auto"+ value={props.contrast}+ onChange={(_, value) => {+ props.setContrast(value as number);+ }}+ marks={[{ value: 100, label: "100%" }]}+ />+ <RowButtonGroupTitle>{t("blur")}</RowButtonGroupTitle>+ <Slider+ min={0}+ max={10}+ defaultValue={0}+ step={1}+ valueLabelDisplay="auto"+ value={props.blur}+ onChange={(_, value) => {+ props.setBlur(value as number);+ }}+ />+ <RowButtonGroupTitle>{t("saturation")}</RowButtonGroupTitle>+ <Slider+ min={0}+ max={200}+ defaultValue={100}+ step={10}+ valueLabelDisplay="auto"+ value={props.saturation}+ onChange={(_, value) => {+ props.setSaturation(value as number);+ }}+ marks={[{ value: 100, label: "100%" }]}+ />+ </Box>+ <RowButtonGroup sx={{ mb: "0.5rem" }}>+ <RowSwitch+ checked={props.invert}+ label={t("invert_colors")}+ onClick={() => {+ props.setInvert(!props.invert);+ }}+ />+ </RowButtonGroup>+ </>+);diff --git a/web/apps/albums/vendor/ente-new/photos/components/Notification.tsx b/web/apps/albums/vendor/ente-new/photos/components/Notification.tsxnew file mode 100644index 0000000000..7e4f199052--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/Notification.tsx@@ -0,0 +1,273 @@+import CloseIcon from "@mui/icons-material/Close";+import InfoIcon from "@mui/icons-material/InfoOutlined";+import {+ IconButton,+ Snackbar,+ Stack,+ Typography,+ type ButtonProps,+ type SxProps,+ type Theme,+} from "@mui/material";+import { EllipsizedTypography } from "ente-base/components/Typography";+import { RippleDisabledButton } from "ente-base/components/mui/FocusVisibleButton";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import { isSxArray } from "ente-base/components/utils/sx";+import React from "react";++/**+ * Customize the contents of an {@link Notification}.+ */+export interface NotificationAttributes {+ /**+ * If set, then the caption is shown first, then the title.+ *+ * Default is to show the title first, then the caption.+ */+ captionFirst?: boolean;+ /**+ * The color of the notification.+ */+ color: ButtonProps["color"];+ /**+ * Optional override to the default InfoIcon shown at the leading edge of+ * the notification.+ *+ * Default: InfoIcon+ */+ startIcon?: React.ReactNode;+ /**+ * The primary textual content of the notification.+ */+ title: React.ReactNode;+ /**+ * The secondary textual content of the notification.+ *+ * It will be ellipsized if it does not fit into a single line.+ */+ caption?: React.ReactNode;+ /**+ * Callback invoked (if provided) when the user clicks on the notification+ * (anywhere except the close button).+ *+ * The notification is closed when this happens, unless the+ * {@link keepOpenOnClick} property is set on the notification instance.+ */+ onClick?: () => void;+ /**+ * Optional override to the default CloseIcon shown at the trailing edge of+ * the notification.+ *+ * Unlike {@link startIcon} which is not interactable, setting this replaces+ * the close button with a icon button showing the given {@link endIcon},+ * and on clicking that icon {@link onClick} would be called instead of+ * {@link onClose} (which would've been called on clicking the default close+ * button in this position).+ */+ endIcon?: React.ReactNode;+ /**+ * Optional handler when {@link endIcon} is clicked.+ *+ * If not provided, clicks on the end icon behave the same as clicking the+ * notification body.+ */+ onEndIconClick?: () => void;+}++type NotificationProps = ModalVisibilityProps & {+ /**+ * Attributes that customize the contents of the notification, and the+ * actions that happen on clicking it.+ */+ attributes: NotificationAttributes | undefined;+ /**+ * If `true`, then the notification is not closed when it is clicked, and+ * should be closed by pressing the close icon button it contains.+ */+ keepOpenOnClick?: boolean;+ /**+ * Horizontal positioning of the notification.+ *+ * Default: "right".+ */+ horizontal?: "left" | "right";+ /**+ * Vertical positioning of the notification.+ *+ * Default: "bottom".+ */+ vertical?: "top" | "bottom";+ /**+ * Optional time in milliseconds after which the notification closes.+ */+ autoHideDuration?: number;+ /**+ * sx props to customize the appearance of the underlying MUI+ * {@link Snackbar}.+ */+ sx?: SxProps<Theme>;+};++/**+ * A small notification popup shown on some edge of the screen to notify the+ * user of some asynchronous update or error.+ *+ * In Material UI terms, this is a custom "Snackbar".+ *+ * A single Notification component can be shared by multiple sources of+ * notifications (which means that there can't be multiple of them outstanding+ * at the same time from the same source). The source can customize the actual+ * contents and appearance of this notification by providing appropriate+ * {@link NotificationAttributes}.+ */+export const Notification: React.FC<NotificationProps> = ({+ open,+ onClose,+ horizontal,+ vertical,+ autoHideDuration,+ sx,+ attributes,+ keepOpenOnClick,+}) => {+ if (!attributes) return <></>;++ const {+ captionFirst,+ color,+ startIcon,+ title,+ caption,+ endIcon,+ onClick,+ onEndIconClick,+ } = attributes;++ const handleClose: React.MouseEventHandler = (event) => {+ onClose();+ event.stopPropagation();+ };++ const handleClick = () => {+ onClick?.();+ if (!keepOpenOnClick) onClose();+ };++ const handleEndIconClick: React.MouseEventHandler = (event) => {+ event.stopPropagation();+ if (onEndIconClick) {+ onEndIconClick();+ } else {+ handleClick();+ }+ };++ return (+ <Snackbar+ open={open}+ autoHideDuration={autoHideDuration}+ onClose={(_, reason) => {+ if (reason === "timeout") onClose();+ }}+ anchorOrigin={{+ horizontal: horizontal ?? "right",+ vertical: vertical ?? "bottom",+ }}+ sx={[+ (theme) => ({+ width: "min(320px, 100vw)",+ // If the `color` of the button is a translucent one, e.g.+ // "secondary", then the notification becomes opaque, which+ // is not what we want. So give the entire snackbar a solid+ // background color.+ backgroundColor: "background.default",+ boxShadow: theme.vars.palette.boxShadow.menu,+ }),+ ...(sx ? (isSxArray(sx) ? sx : [sx]) : []),+ ]}+ >+ <RippleDisabledButton+ color={color}+ onClick={handleClick}+ sx={{+ flex: "1",+ padding: "12px 8px 12px 14px",+ borderRadius: "8px",+ }}+ >+ <Stack+ direction="row"+ sx={{+ gap: 2,+ alignItems: "center",+ // Necessary to get the ellipsizing to work.+ width: "100%",+ }}+ >+ <Stack sx={{ svg: { fontSize: "36px" } }}>+ {startIcon ?? <InfoIcon />}+ </Stack>++ <Stack+ sx={{+ flex: 1,+ gap: 0.5,+ // Undo the center alignment done by the button.+ textAlign: "left",+ // This is necessary to trigger the ellipsizing of the+ // text in children.+ overflow: "hidden",+ }}+ >+ {captionFirst ? (+ <>+ {caption && (+ <EllipsizedTypography variant="small">+ {caption}+ </EllipsizedTypography>+ )}+ <Typography sx={{ fontWeight: "medium" }}>+ {title}+ </Typography>+ </>+ ) : (+ <>+ <Typography sx={{ fontWeight: "medium" }}>+ {title}+ </Typography>+ {caption && (+ <EllipsizedTypography variant="small">+ {caption}+ </EllipsizedTypography>+ )}+ </>+ )}+ </Stack>++ {endIcon ? (+ <IconButton+ component="div"+ onClick={handleEndIconClick}+ sx={{ fontSize: "36px", bgcolor: "fill.faint" }}+ >+ {endIcon}+ </IconButton>+ ) : (+ <IconButton+ // Buttons cannot be nested in buttons, so we use a div+ // here instead.+ component="div"+ // Inherit the color of the parent button instead of+ // using the IconButton defaults.+ color="inherit"+ onClick={handleClose}+ sx={{ bgcolor: "fill.faint" }}+ >+ <CloseIcon />+ </IconButton>+ )}+ </Stack>+ </RippleDisabledButton>+ </Snackbar>+ );+};diff --git a/web/apps/albums/vendor/ente-new/photos/components/PeopleList.tsx b/web/apps/albums/vendor/ente-new/photos/components/PeopleList.tsxnew file mode 100644index 0000000000..bdf51a1934--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/PeopleList.tsx@@ -0,0 +1,319 @@+import PersonAddIcon from "@mui/icons-material/PersonAdd";+import { Skeleton, styled, Typography } from "@mui/material";+import { useIsSmallWidth } from "ente-base/components/utils/hooks";+import type { EnteFile } from "ente-media/file";+import { faceCrop, type AnnotatedFaceID } from "ente-new/photos/services/ml";+import type {+ Person,+ PreviewableFace,+} from "ente-new/photos/services/ml/people";+import React, { useEffect, useState } from "react";+import { UnstyledButton } from "./UnstyledButton";++export interface SearchPeopleListProps {+ people: Person[];+ onSelectPerson: (personID: string) => void;+}++/**+ * Shows a list of {@link Person}s in the empty state of the search bar.+ */+export const SearchPeopleList: React.FC<SearchPeopleListProps> = ({+ people,+ onSelectPerson,+}) => {+ const isSmallWidth = useIsSmallWidth();+ return (+ <SearchPeopleContainer+ sx={[+ people.length > 3+ ? { justifyContent: "center" }+ : { justifyContent: "start" },+ ]}+ >+ {people.slice(0, isSmallWidth ? 6 : 7).map((person) => (+ <SearchPersonButton+ key={person.id}+ onClick={() => onSelectPerson(person.id)}+ >+ <FaceCropImageView+ faceID={person.displayFaceID}+ file={person.displayFaceFile}+ placeholderDimension={87}+ />+ </SearchPersonButton>+ ))}+ </SearchPeopleContainer>+ );+};++const SearchPeopleContainer = styled("div")`+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 5px;+ margin-block-start: 12px;+ margin-block-end: 15px;+`;++const SearchPersonButton = styled(UnstyledButton)(+ ({ theme }) => `+ width: 87px;+ height: 87px;+ border-radius: 50%;+ overflow: hidden;+ & > img {+ width: 100%;+ height: 100%;+ }+ :hover {+ outline: 1px solid ${theme.vars.palette.stroke.faint};+ outline-offset: 2px;+ }+`,+);++export interface FilePeopleListProps {+ /**+ * The {@link EnteFile} whose information we are showing.+ */+ file: EnteFile;+ /**+ * The list of faces in the file that are associated with a person.+ */+ annotatedFaceIDs: AnnotatedFaceID[];+ /**+ * Called when the user selects a face in the list.+ */+ onSelectFace: (annotatedFaceID: AnnotatedFaceID) => void;+ /**+ * People that were manually associated with the file, and should be shown+ * in addition to detected faces.+ */+ manuallyAssignedPeople?: Person[];+ /**+ * Called when the user selects a person (used for manually assigned people).+ */+ onSelectPerson?: (personID: string) => void;+ /**+ * If set, show an option to manually associate the file with a person.+ */+ onAddPerson?: () => void;+ /**+ * Title/tooltip for the "add person" button (if shown).+ */+ addPersonTitle?: string;+ /**+ * Label shown under the "add person" button (if shown).+ */+ addPersonLabel?: string;+}++/**+ * Show the list of faces in the given file that are associated with a specific+ * person.+ */+export const FilePeopleList: React.FC<FilePeopleListProps> = ({+ file,+ annotatedFaceIDs,+ onSelectFace,+ manuallyAssignedPeople,+ onSelectPerson,+ onAddPerson,+ addPersonTitle,+ addPersonLabel,+}) => (+ <FilePeopleList_>+ {annotatedFaceIDs.map((annotatedFaceID) => (+ <AnnotatedFaceButton+ key={annotatedFaceID.faceID}+ onClick={() => onSelectFace(annotatedFaceID)}+ >+ <FaceCropImageView+ faceID={annotatedFaceID.faceID}+ file={file}+ placeholderDimension={65}+ />+ <Typography variant="small" sx={{ color: "text.muted" }}>+ {annotatedFaceID.personName}+ </Typography>+ </AnnotatedFaceButton>+ ))}+ {manuallyAssignedPeople?.map((person) => (+ <ManuallyAssignedPersonButton+ key={person.id}+ onClick={() => onSelectPerson?.(person.id)}+ >+ <FaceCropImageView+ faceID={person.displayFaceID}+ file={person.displayFaceFile}+ placeholderDimension={65}+ />+ <Typography variant="small" sx={{ color: "text.muted" }}>+ {person.name}+ </Typography>+ </ManuallyAssignedPersonButton>+ ))}+ {onAddPerson && (+ <AddPersonButton+ onClick={onAddPerson}+ title={addPersonTitle}+ aria-label={addPersonTitle}+ >+ <AddPersonAvatar>+ <PersonAddIcon />+ </AddPersonAvatar>+ <Typography variant="small" sx={{ color: "text.muted" }}>+ {addPersonLabel}+ </Typography>+ </AddPersonButton>+ )}+ </FilePeopleList_>+);++const FilePeopleList_ = styled("div")`+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ margin-block-end: 5px;+`;++const AnnotatedFaceButton = styled(UnstyledButton)(+ ({ theme }) => `+ width: 65px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ & > img {+ width: 100%;+ aspect-ratio: 1;+ border-radius: 50%;+ overflow: hidden;+ }+ & > img:hover {+ outline: 1px solid ${theme.vars.palette.stroke.faint};+ outline-offset: 2px;+ }+`,+);++const ManuallyAssignedPersonButton = AnnotatedFaceButton;++const AddPersonButton = styled(UnstyledButton)(+ ({ theme }) => `+ width: 65px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ & > div {+ width: 100%;+ aspect-ratio: 1;+ border-radius: 50%;+ overflow: hidden;+ }+ & > div:hover {+ outline: 1px solid ${theme.vars.palette.stroke.faint};+ outline-offset: 2px;+ }+`,+);++const AddPersonAvatar = styled("div")(+ ({ theme }) => `+ display: flex;+ align-items: center;+ justify-content: center;+ color: ${theme.vars.palette.text.muted};+ border: 1px dashed ${theme.vars.palette.stroke.faint};+`,+);++export interface SuggestionFaceListProps {+ /**+ * Faces, each annotated with the corresponding {@link EnteFile}, to show in+ * the list.+ */+ faces: PreviewableFace[];+}++/**+ * Show the sampling of faces from a given cluster that is being offered as a+ * suggestion to the user.+ */+export const SuggestionFaceList: React.FC<SuggestionFaceListProps> = ({+ faces,+}) => {+ return (+ <SuggestionFaceList_>+ {faces.map(({ file, faceID }) => (+ <SuggestionFace key={faceID}>+ <FaceCropImageView+ placeholderDimension={87}+ {...{ file, faceID }}+ />+ </SuggestionFace>+ ))}+ </SuggestionFaceList_>+ );+};++const SuggestionFaceList_ = styled("div")`+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+`;++const SuggestionFace = styled("div")`+ width: 87px;+ height: 87px;+ border-radius: 50%;+ overflow: hidden;+ & > img {+ width: 100%;+ height: 100%;+ }+`;++type FaceCropImageViewProps = PreviewableFace & {+ /** Width and height for the placeholder. */+ placeholderDimension: number;+};++/**+ * An image view showing the face crop for the given face.+ *+ * The image is read from the "face-crops" {@link BlobCache}, regenerating it if+ * needed (which is why also need to pass the associated file).+ *+ * While the image is being fetched or regenerated, or if it doesn't exist, a+ * placeholder is shown.+ */+const FaceCropImageView: React.FC<FaceCropImageViewProps> = ({+ faceID,+ file,+ placeholderDimension,+}) => {+ const [url, setURL] = useState<string | undefined>();++ useEffect(() => {+ let didCancel = false;++ void faceCrop(faceID, file).then((url) => !didCancel && setURL(url));++ return () => {+ didCancel = true;+ };+ }, [faceID, file]);++ return url ? (+ <img style={{ objectFit: "cover" }} src={url} />+ ) : (+ <Skeleton+ variant="circular"+ animation="wave"+ sx={{ backgroundColor: "background.paper2" }}+ width={placeholderDimension}+ height={placeholderDimension}+ />+ );+};diff --git a/web/apps/albums/vendor/ente-new/photos/components/PlaceholderThumbnails.tsx b/web/apps/albums/vendor/ente-new/photos/components/PlaceholderThumbnails.tsxnew file mode 100644index 0000000000..95a4684fd9--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/PlaceholderThumbnails.tsx@@ -0,0 +1,53 @@+import PhotoOutlinedIcon from "@mui/icons-material/PhotoOutlined";+import PlayCircleOutlineOutlinedIcon from "@mui/icons-material/PlayCircleOutlineOutlined";+import { styled } from "@mui/material";+import { Overlay } from "ente-base/components/containers";+import { FileType } from "ente-media/file-type";+import React from "react";++/**+ * A thumbnail shown when we're loading the thumbnail for a file.+ * @returns+ */+export const LoadingThumbnail = () => (+ <Overlay sx={{ backgroundColor: "fill.faint", borderRadius: "4px" }} />+);++interface StaticThumbnailProps {+ /**+ * The type of the file for which we're showing the placeholder thumbnail.+ *+ * Expected to be one of {@link FileType}.+ */+ fileType: number;+}++/**+ * A thumbnail shown when a file does not have a thumbnail.+ */+export const StaticThumbnail: React.FC<StaticThumbnailProps> = ({+ fileType,+}) => (+ <CenteredOverlay+ sx={{+ backgroundColor: "fill.faint",+ borderWidth: "1px",+ borderStyle: "solid",+ borderColor: "stroke.faint",+ borderRadius: "4px",+ "& > svg": { color: "stroke.muted", fontSize: "50px" },+ }}+ >+ {fileType != FileType.video ? (+ <PhotoOutlinedIcon />+ ) : (+ <PlayCircleOutlineOutlinedIcon />+ )}+ </CenteredOverlay>+);++const CenteredOverlay = styled(Overlay)`+ display: flex;+ justify-content: center;+ align-items: center;+`;diff --git a/web/apps/albums/vendor/ente-new/photos/components/SelectedFileOptions.tsx b/web/apps/albums/vendor/ente-new/photos/components/SelectedFileOptions.tsxnew file mode 100644index 0000000000..b272fa5ede--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/SelectedFileOptions.tsx@@ -0,0 +1,674 @@+import {+ AddSquareIcon,+ ArrowRight02Icon,+ Clock02Icon,+ Delete02Icon,+ Download01Icon,+ Download05Icon,+ Location01Icon,+ Navigation03Icon,+ RemoveCircleIcon,+ Time04Icon,+ Unarchive03Icon,+ UserAdd02Icon,+ ViewIcon,+ ViewOffSlashIcon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import CheckCircleIcon from "@mui/icons-material/CheckCircle";+import CheckCircleOutlineIcon from "@mui/icons-material/CheckCircleOutline";+import CloseIcon from "@mui/icons-material/Close";+import { Box, Button, IconButton, Tooltip, Typography } from "@mui/material";+import { SpacedRow } from "ente-base/components/containers";+import type { ButtonishProps } from "ente-base/components/mui";+import { useBaseContext } from "ente-base/context";+import type { Collection } from "ente-media/collection";+import type { CollectionSelectorAttributes } from "ente-new/photos/components/CollectionSelector";+import type { GalleryBarMode } from "ente-new/photos/components/gallery/reducer";+import { StarBorderIcon } from "ente-new/photos/components/icons/StarIcon";+import { StarOffIcon } from "ente-new/photos/components/icons/StarOffIcon";+import {+ PseudoCollectionID,+ type CollectionSummary,+} from "ente-new/photos/services/collection-summary";+import { t } from "i18next";++/**+ * Operations on selected files.+ */+export type FileOp =+ | "sendLink"+ | "download"+ | "fixTime"+ | "favorite"+ | "unfavorite"+ | "archive"+ | "unarchive"+ | "hide"+ | "trash"+ | "deletePermanently";++/**+ * Operations on selected files that also have an associated collection.+ */+export type CollectionOp = "add" | "move" | "restore" | "unhide";++interface SelectedFileOptionsProps {+ barMode?: GalleryBarMode;+ isInSearchMode: boolean;+ selectedCollection?: Collection;+ /**+ * If {@link collectionSummary} is set and is not a pseudo-collection, then+ * this will be set to the corresponding {@link Collection}.+ */+ collection: Collection | undefined;+ /**+ * The collection summary in whose context the selection happened.+ *+ * This will not be set if we are in the people section, or if we are+ * showing search results.+ */+ collectionSummary: CollectionSummary | undefined;+ /**+ * The total number of files selected by the user.+ */+ selectedFileCount: number;+ /**+ * The subset of {@link selectedFileCount} that are also owned by the user.+ */+ selectedOwnFileCount: number;+ /**+ * The number of selected files that are currently favorited.+ */+ selectedFavoriteCount: number;+ /**+ * Called when the user clears the selection by pressing the cancel button+ * on the selection bar.+ */+ onClearSelection: () => void;+ /**+ * Called when the user wants to remove the selected files from the given+ * {@link collection}.+ */+ onRemoveFilesFromCollection: (collection: Collection) => void;+ /**+ * Callback to open a dialog where the user can choose a collection.+ *+ * The reason for opening the dialog and other properties are passed as the+ * {@link attributes} argument.+ */+ onOpenCollectionSelector: (+ attributes: CollectionSelectorAttributes,+ ) => void;+ /**+ * A function called to obtain a new album creation handler for the provided+ * {@link op}.+ *+ * This function will be passed the operation to be be performed. It will+ * return a new function G can be used as the {@link onCreateCollection}+ * attribute for {@link onOpenCollectionSelector}.+ *+ * Once the user enters the name and a new album with that name gets+ * created, the newly created collection will be passed to G.+ *+ * @param op The operation that should be performed on the selected files+ * using the newly created collection.+ *+ * @returns A function that can be called with to create a new collection+ * and then perform {@link op} on successful creation of the new collection.+ */+ createOnCreateForCollectionOp: (op: CollectionOp) => () => void;+ /**+ * A function called to obtain an existing album selection handler for the+ * provided {@link op}.+ *+ * This function will be passed the operation to be be performed. It will+ * return a new function G can be used as the {@link onSelectCollection}+ * attribute for {@link onOpenCollectionSelector}.+ *+ * Once the user selects a collection, then the selected collection will be+ * passed to G.+ *+ * @param op The operation that should be performed on the selected files,+ * using the selected collection.+ *+ * @returns A function that can be called with a selected collection.+ */+ createOnSelectForCollectionOp: (+ op: CollectionOp,+ ) => (selectedCollection: Collection) => void;+ /**+ * A function called to obtain a handler for the provided {@link op}.+ *+ * This function will be passed the file operation to be performed. It will+ * return a new function G that can be used as a {@link onClick} handler for+ * the button. Calling G will trigger the operation on the selected files.+ *+ * @param op The operation that should be performed on the selected files.+ * @returns+ */+ createFileOpHandler: (op: FileOp) => () => void;+ /**+ * Callback to show the assign person dialog.+ *+ * Similar to {@link onOpenCollectionSelector}, this opens a shared dialog+ * defined in the parent component where the user can select a person to+ * associate with the selected files.+ *+ * If not set, the "Add Person" option will not be shown.+ */+ onShowAssignPersonDialog?: () => void;++ /**+ * Called when the user wants to edit the location of the selected files.+ *+ * Only shown when at least one owned file is selected.+ */+ onEditLocation?: () => void;+ /**+ * Called when the user wants to select all files.+ */+ onSelectAll: () => void;+ /**+ * If true, all files in the current view are selected.+ */+ isAllSelected: boolean;+}++/**+ * The selection bar shown at the top of the viewport when the user has selected+ * one or more files in the photos app gallery.+ */+export const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({+ barMode,+ isInSearchMode,+ collection,+ collectionSummary,+ selectedFileCount,+ selectedOwnFileCount,+ selectedFavoriteCount,+ onClearSelection,+ onRemoveFilesFromCollection,+ onOpenCollectionSelector,+ createOnCreateForCollectionOp,+ createOnSelectForCollectionOp,+ createFileOpHandler,+ onShowAssignPersonDialog,+ onEditLocation,+ onSelectAll,+ isAllSelected,+}) => {+ const { showMiniDialog } = useBaseContext();++ const isUserFavorites =+ !!collectionSummary?.attributes.has("userFavorites");++ const handleFavorite = createFileOpHandler("favorite");+ const handleUnfavorite = createFileOpHandler("unfavorite");++ const handleFixTime = createFileOpHandler("fixTime");++ const handleDownload = createFileOpHandler("download");+ const handleSendLink = createFileOpHandler("sendLink");++ const handleArchive = createFileOpHandler("archive");++ const handleUnarchive = createFileOpHandler("unarchive");++ const handleDelete = () =>+ showMiniDialog({+ title: t("trash_files_title"),+ message: t("trash_files_message"),+ continue: {+ text: t("move_to_trash"),+ color: "critical",+ action: createFileOpHandler("trash"),+ },+ });++ const handleRestore = () =>+ onOpenCollectionSelector({+ action: "restore",+ onCreateCollection: createOnCreateForCollectionOp("restore"),+ onSelectCollection: createOnSelectForCollectionOp("restore"),+ });++ const handleDeletePermanently = () =>+ showMiniDialog({+ title: t("delete_files_title"),+ message: t("delete_files_message"),+ continue: {+ text: t("delete"),+ color: "critical",+ action: createFileOpHandler("deletePermanently"),+ },+ });++ const handleAddToCollection = () =>+ onOpenCollectionSelector({+ action: "add",+ sourceCollectionSummaryID: collectionSummary?.id,+ onCreateCollection: createOnCreateForCollectionOp("add"),+ onSelectCollection: createOnSelectForCollectionOp("add"),+ });++ const isSharedIncoming =+ collectionSummary?.attributes.has("sharedIncoming");+ const isSharedOutgoing =+ collectionSummary?.attributes.has("sharedOutgoing");+ const isRemovingOthers = selectedFileCount != selectedOwnFileCount;+ const favoriteAction =+ selectedFavoriteCount === 0+ ? "favorite"+ : selectedFavoriteCount === selectedFileCount+ ? "unfavorite"+ : "none";+ const favoriteActionButton =+ favoriteAction === "favorite" ? (+ <FavoriteButton onClick={handleFavorite} />+ ) : favoriteAction === "unfavorite" ? (+ <UnfavoriteButton onClick={handleUnfavorite} />+ ) : null;++ const handleRemoveFromCollection = () => {+ if (!collection) return;+ const remove = () => onRemoveFilesFromCollection(collection);++ if (isSharedIncoming) {+ if (isRemovingOthers) {+ showMiniDialog({+ title: t("remove_from_album"),+ message: t("remove_from_album_others_message"),+ continue: {+ text: t("remove"),+ color: "critical",+ action: remove,+ },+ cancel: t("cancel"),+ });+ } else {+ remove();+ }+ return;+ }++ if (isSharedOutgoing && isRemovingOthers) {+ showMiniDialog({+ title: t("remove_from_album"),+ message: t("remove_from_album_others_message"),+ continue: {+ text: t("remove"),+ color: "critical",+ action: remove,+ },+ });+ return;+ }++ const onlyUserFiles = !isRemovingOthers;+ showMiniDialog({+ title: t("remove_from_album"),+ message: onlyUserFiles+ ? t("confirm_remove_message")+ : t("confirm_remove_incl_others_message"),+ continue: {+ text: t("yes_remove"),+ color: onlyUserFiles ? "primary" : "critical",+ action: remove,+ },+ });+ };++ const handleMoveToCollection = () => {+ onOpenCollectionSelector({+ action: "move",+ sourceCollectionSummaryID: collectionSummary?.id,+ onCreateCollection: createOnCreateForCollectionOp("move"),+ onSelectCollection: createOnSelectForCollectionOp("move"),+ });+ };++ const handleHide = createFileOpHandler("hide");++ const handleUnhide = () => {+ onOpenCollectionSelector({+ action: "unhide",+ onCreateCollection: createOnCreateForCollectionOp("unhide"),+ onSelectCollection: createOnSelectForCollectionOp("unhide"),+ });+ };++ return (+ <>+ <SpacedRow sx={{ flex: 1, gap: 1, flexWrap: "wrap" }}>+ <IconButton onClick={onClearSelection}>+ <CloseIcon />+ </IconButton>+ <Typography>+ {selectedFileCount == selectedOwnFileCount+ ? t("selected_count", { selected: selectedFileCount })+ : t("selected_and_yours_count", {+ selected: selectedFileCount,+ yours: selectedOwnFileCount,+ })}+ </Typography>+ <SelectAllToggleButton+ isAllSelected={isAllSelected}+ onClick={isAllSelected ? onClearSelection : onSelectAll}+ />++ <Box sx={{ mr: "auto" }} />++ {isInSearchMode ? (+ <>+ {selectedOwnFileCount > 0 && (+ <SendLinkButton onClick={handleSendLink} />+ )}+ {favoriteActionButton}+ <FixTimeButton onClick={handleFixTime} />+ {onEditLocation && selectedOwnFileCount > 0 && (+ <EditLocationButton onClick={onEditLocation} />+ )}+ <DownloadButton onClick={handleDownload} />+ <AddToCollectionButton+ onClick={handleAddToCollection}+ />+ {!!onShowAssignPersonDialog && (+ <AddPersonButton+ onClick={onShowAssignPersonDialog}+ />+ )}+ <ArchiveButton onClick={handleArchive} />+ <HideButton onClick={handleHide} />+ <DeleteButton onClick={handleDelete} />+ </>+ ) : barMode == "people" ? (+ <>+ {selectedOwnFileCount > 0 && (+ <SendLinkButton onClick={handleSendLink} />+ )}+ {favoriteActionButton}+ <DownloadButton onClick={handleDownload} />+ <AddToCollectionButton+ onClick={handleAddToCollection}+ />+ {!!onShowAssignPersonDialog && (+ <AddPersonButton+ onClick={onShowAssignPersonDialog}+ />+ )}+ <ArchiveButton onClick={handleArchive} />+ <HideButton onClick={handleHide} />+ <DeleteButton onClick={handleDelete} />+ </>+ ) : collectionSummary?.id == PseudoCollectionID.trash ? (+ <>+ <RestoreButton onClick={handleRestore} />+ <DeletePermanentlyButton+ onClick={handleDeletePermanently}+ />+ </>+ ) : collectionSummary?.attributes.has("uncategorized") ? (+ <>+ {selectedOwnFileCount > 0 && (+ <SendLinkButton onClick={handleSendLink} />+ )}+ <DownloadButton onClick={handleDownload} />+ {!!onShowAssignPersonDialog && (+ <AddPersonButton+ onClick={onShowAssignPersonDialog}+ />+ )}+ <MoveToCollectionButton+ onClick={handleMoveToCollection}+ />+ <DeleteButton onClick={handleDelete} />+ </>+ ) : collectionSummary?.attributes.has("sharedIncoming") ? (+ <>+ {selectedOwnFileCount > 0 && (+ <SendLinkButton onClick={handleSendLink} />+ )}+ <DownloadButton onClick={handleDownload} />+ {!!onShowAssignPersonDialog && (+ <AddPersonButton+ onClick={onShowAssignPersonDialog}+ />+ )}+ <RemoveFromCollectionButton+ onClick={handleRemoveFromCollection}+ />+ </>+ ) : barMode == "hidden-albums" ? (+ <>+ {selectedOwnFileCount > 0 && (+ <SendLinkButton onClick={handleSendLink} />+ )}+ <DownloadButton onClick={handleDownload} />+ {!!onShowAssignPersonDialog && (+ <AddPersonButton+ onClick={onShowAssignPersonDialog}+ />+ )}+ <UnhideButton onClick={handleUnhide} />+ <DeleteButton onClick={handleDelete} />+ </>+ ) : (+ <>+ {selectedOwnFileCount > 0 && (+ <SendLinkButton onClick={handleSendLink} />+ )}+ {collectionSummary?.id !=+ PseudoCollectionID.archiveItems &&+ favoriteActionButton}+ <FixTimeButton onClick={handleFixTime} />+ {onEditLocation && selectedOwnFileCount > 0 && (+ <EditLocationButton onClick={onEditLocation} />+ )}+ <DownloadButton onClick={handleDownload} />+ <AddToCollectionButton+ onClick={handleAddToCollection}+ />+ {!!onShowAssignPersonDialog && (+ <AddPersonButton+ onClick={onShowAssignPersonDialog}+ />+ )}+ {collectionSummary?.id === PseudoCollectionID.all ? (+ <ArchiveButton onClick={handleArchive} />+ ) : collectionSummary?.id ==+ PseudoCollectionID.archiveItems ? (+ <UnarchiveButton onClick={handleUnarchive} />+ ) : (+ !isUserFavorites && (+ <>+ <MoveToCollectionButton+ onClick={handleMoveToCollection}+ />+ <RemoveFromCollectionButton+ onClick={handleRemoveFromCollection}+ />+ </>+ )+ )}+ <HideButton onClick={handleHide} />+ <DeleteButton onClick={handleDelete} />+ </>+ )}+ </SpacedRow>+ </>+ );+};++const DownloadButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("download")}>+ <IconButton {...{ onClick }}>+ <HugeiconsIcon icon={Download01Icon} />+ </IconButton>+ </Tooltip>+);++const SendLinkButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title="Send link">+ <IconButton {...{ onClick }} aria-label="Send link">+ <HugeiconsIcon icon={Navigation03Icon} />+ </IconButton>+ </Tooltip>+);++const FavoriteButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("favorite")}>+ <IconButton {...{ onClick }}>+ <StarBorderIcon fontSize="small" />+ </IconButton>+ </Tooltip>+);++const UnfavoriteButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("un_favorite")}>+ <IconButton {...{ onClick }}>+ <StarOffIcon fontSize="small" />+ </IconButton>+ </Tooltip>+);++const ArchiveButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("archive")}>+ <IconButton {...{ onClick }}>+ <HugeiconsIcon icon={Download05Icon} />+ </IconButton>+ </Tooltip>+);++const UnarchiveButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("unarchive")}>+ <IconButton {...{ onClick }}>+ <HugeiconsIcon icon={Unarchive03Icon} />+ </IconButton>+ </Tooltip>+);++const HideButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("hide")}>+ <IconButton {...{ onClick }}>+ <HugeiconsIcon icon={ViewOffSlashIcon} />+ </IconButton>+ </Tooltip>+);++const UnhideButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("unhide")}>+ <IconButton {...{ onClick }}>+ <HugeiconsIcon icon={ViewIcon} />+ </IconButton>+ </Tooltip>+);++const DeleteButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("delete")}>+ <IconButton {...{ onClick }} sx={{ color: "critical.main" }}>+ <HugeiconsIcon icon={Delete02Icon} />+ </IconButton>+ </Tooltip>+);++const RestoreButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("restore")}>+ <IconButton {...{ onClick }}>+ <HugeiconsIcon icon={Clock02Icon} />+ </IconButton>+ </Tooltip>+);++const DeletePermanentlyButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("delete_permanently")}>+ <IconButton {...{ onClick }} sx={{ color: "critical.main" }}>+ <HugeiconsIcon icon={Delete02Icon} />+ </IconButton>+ </Tooltip>+);++const FixTimeButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("fix_creation_time")}>+ <IconButton {...{ onClick }}>+ <HugeiconsIcon icon={Time04Icon} />+ </IconButton>+ </Tooltip>+);++const EditLocationButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("edit_location")}>+ <IconButton {...{ onClick }}>+ <HugeiconsIcon icon={Location01Icon} />+ </IconButton>+ </Tooltip>+);++const AddToCollectionButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("add")}>+ <IconButton {...{ onClick }}>+ <HugeiconsIcon icon={AddSquareIcon} />+ </IconButton>+ </Tooltip>+);++const AddPersonButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("add_a_person")}>+ <IconButton {...{ onClick }}>+ <HugeiconsIcon icon={UserAdd02Icon} />+ </IconButton>+ </Tooltip>+);++const MoveToCollectionButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("move")}>+ <IconButton {...{ onClick }}>+ <HugeiconsIcon icon={ArrowRight02Icon} />+ </IconButton>+ </Tooltip>+);++const RemoveFromCollectionButton: React.FC<ButtonishProps> = ({ onClick }) => (+ <Tooltip title={t("remove")}>+ <IconButton {...{ onClick }}>+ <HugeiconsIcon icon={RemoveCircleIcon} />+ </IconButton>+ </Tooltip>+);++interface SelectAllToggleButtonProps {+ isAllSelected: boolean;+ onClick: () => void;+}++const SelectAllToggleButton: React.FC<SelectAllToggleButtonProps> = ({+ isAllSelected,+ onClick,+}) => (+ <Tooltip title={isAllSelected ? t("deselect_all") : t("select_all")}>+ <Button+ onClick={onClick}+ size="small"+ color="secondary"+ sx={{+ textTransform: "none",+ minWidth: "auto",+ px: 2,+ ml: 2,+ borderRadius: 9999,+ }}+ endIcon={+ isAllSelected ? (+ <CheckCircleIcon fontSize="small" />+ ) : (+ <CheckCircleOutlineIcon+ fontSize="small"+ sx={{ color: "text.muted" }}+ />+ )+ }+ >+ {t("all")}+ </Button>+ </Tooltip>+);diff --git a/web/apps/albums/vendor/ente-new/photos/components/ThemedLoadingBar.tsx b/web/apps/albums/vendor/ente-new/photos/components/ThemedLoadingBar.tsxnew file mode 100644index 0000000000..96ad8afbdb--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/ThemedLoadingBar.tsx@@ -0,0 +1,16 @@+import { useTheme } from "@mui/material";+import React from "react";+import LoadingBar, { type LoadingBarRef } from "react-top-loading-bar";++interface ThemedLoadingBarProps {+ ref: React.Ref<LoadingBarRef>;+}+/**+ * A wrapper over the {@link LoadingBar} library component that sets it to use+ * the main accent color from the theme.+ */+export const ThemedLoadingBar: React.FC<ThemedLoadingBarProps> = ({ ref }) => {+ const theme = useTheme();++ return <LoadingBar color={theme.vars.palette.accent.main} ref={ref} />;+};diff --git a/web/apps/albums/vendor/ente-new/photos/components/Tiles.tsx b/web/apps/albums/vendor/ente-new/photos/components/Tiles.tsxnew file mode 100644index 0000000000..f2b4e83286--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/Tiles.tsx@@ -0,0 +1,269 @@+import AddIcon from "@mui/icons-material/Add";+import { Stack, styled, Typography } from "@mui/material";+import { CenteredFill, Overlay } from "ente-base/components/containers";+import type { ButtonishProps } from "ente-base/components/mui";+import log from "ente-base/log";+import { downloadManager } from "ente-gallery/services/download";+import { type EnteFile } from "ente-media/file";+import {+ LoadingThumbnail,+ StaticThumbnail,+} from "ente-new/photos/components/PlaceholderThumbnails";+import React, { useEffect, useState } from "react";+import { faceCrop } from "../services/ml";+import { UnstyledButton } from "./UnstyledButton";++interface ItemCardProps {+ /**+ * One of the *Tile components to use as the top level element.+ */+ TileComponent: React.FC<React.PropsWithChildren>;+ /**+ * Optional file whose thumbnail (if any) should be should be shown.+ */+ coverFile?: EnteFile | undefined;+ /**+ * Optional ID of a specific face within {@link coverFile} to show.+ *+ * Precondition: {@link faceID} must be an ID of a face that belongs to the+ * given {@link coverFile}.+ */+ coverFaceID?: string | undefined;+ /**+ * Optional boolean indicating if the user is currently scrolling.+ *+ * This is used as a hint by the file downloader to prioritize downloads.+ */+ isScrolling?: boolean;+ /**+ * Optional click handler.+ */+ onClick?: () => void;+}++/**+ * A generic card that can be be used to represent collections, files, people -+ * anything that (usually) has an associated "cover photo".+ *+ * Usually, we provide it a {@link coverFile} prop to set the file whose+ * thumbnail should be shown in the card. However, an additional+ * {@link coverFaceID} prop can be used to show the face crop for that specific+ * face within the cover file.+ *+ * Note that while the common use case is to use this with a cover photo (and an+ * additional cover faceID), both of these are optional and the item card can+ * also be used as a static component without an associated cover image by+ * covering it with an opaque overlay.+ */+export const ItemCard: React.FC<React.PropsWithChildren<ItemCardProps>> = ({+ TileComponent,+ coverFile,+ coverFaceID,+ isScrolling,+ onClick,+ children,+}) => {+ const [coverImageURL, setCoverImageURL] = useState<string | undefined>();++ useEffect(() => {+ if (!coverFile) return undefined;++ let didCancel = false;++ if (coverFaceID) {+ void faceCrop(coverFaceID, coverFile).then(+ (url) => !didCancel && setCoverImageURL(url),+ );+ } else {+ void downloadManager+ .renderableThumbnailURL(coverFile, isScrolling)+ .then((url) => !didCancel && setCoverImageURL(url))+ .catch((e: unknown) => {+ log.warn("Failed to fetch thumbnail", e);+ });+ }++ return () => {+ didCancel = true;+ };+ }, [coverFile, coverFaceID, isScrolling]);++ return (+ <TileComponent {...{ onClick }}>+ {coverFile?.metadata.hasStaticThumbnail ? (+ <StaticThumbnail fileType={coverFile.metadata.fileType} />+ ) : coverImageURL ? (+ <img src={coverImageURL} />+ ) : (+ <LoadingThumbnail />+ )}+ {children}+ </TileComponent>+ );+};++/**+ * A generic "base" tile, meant to be used (after setting dimensions) as the+ * {@link TileComponent} provided to an {@link ItemCard}.+ *+ * Use {@link Overlay} (usually via one of its presets) to overlay content on+ * top of the tile.+ */+const BaseTile = styled("div")`+ display: flex;+ /* Act as container for the absolutely positioned 'Overlay's. */+ position: relative;+ border-radius: 4px;+ overflow: hidden;+ cursor: pointer;+ & > img {+ object-fit: cover;+ width: 100%;+ height: 100%;+ pointer-events: none;+ }+ user-select: none;+`;++/**+ * A 48x48 TileComponent used in search result dropdown's preview files and+ * other places.+ */+export const PreviewItemTile = styled(BaseTile)`+ width: 48px;+ height: 48px;+`;++/**+ * A rectangular, TV-ish tile used in the gallery bar.+ */+export const BarItemTile = styled(BaseTile)`+ width: 90px;+ height: 64px;+ color: white;+`;++/**+ * A square tile used on the duplicates listing.+ */+export const DuplicateItemTile = styled(BaseTile)`+ /* The thumbnails are not interactable, reset the pointer */+ cursor: initial;+`;++/**+ * A variant of {@link BaseTile} meant for use when the tile is interactable.+ */+export const BaseTileButton = styled(UnstyledButton)`+ /* Buttons reset this to the special token buttontext */+ color: inherit;+ /* Buttons reset this to center */+ text-align: inherit;++ /* Rest of this is mostly verbatim from BaseTile ... */++ display: flex;+ /* Act as container for the absolutely positioned 'Overlay's. */+ position: relative;+ border-radius: 4px;+ overflow: hidden;+ & > img {+ object-fit: cover;+ width: 100%;+ height: 100%;+ pointer-events: none;+ }+`;++/**+ * A large 150x150 TileComponent used when, for example, when showing the list+ * of collections in the all collections view and in the collection selector.+ */+export const LargeTileButton = styled(BaseTileButton)`+ width: 150px;+ height: 150px;+`;++/**+ * An {@link Overlay} suitable for hosting textual content at the top left of+ * small and medium sized tiles.+ */+export const TileTextOverlay = styled(Overlay)`+ padding: 4px;+ background: linear-gradient(+ 0deg,+ rgba(0, 0, 0, 0.1) 0%,+ rgba(0, 0, 0, 0.5) 86.46%+ );+`;++/**+ * A variation of {@link TileTextOverlay} for use with larger tiles like the+ * {@link CollectionTile}.+ */+export const LargeTileTextOverlay = styled(Overlay)`+ padding: 8px;+ color: white;+ background: linear-gradient(+ -10deg,+ rgba(0, 0, 0, 0.1) 0%,+ rgba(0, 0, 0, 0.2) 50%,+ rgba(0, 0, 0, 0.4) 60%,+ rgba(0, 0, 0, 0.6) 100%+ );+`;++/**+ * A {@link LargeTileButton} suitable for use as the trigger for creating a new+ * entry (e.g. creating new album, or a new person).+ *+ * It is styled to go well with other {@link LargeTileButton}s that display+ * existing entries, except this one can allow the user to create a new item.+ *+ * The child is expected to be a text, it'll be wrapped in a {@link Typography}+ * and shown at the top left of the button.+ */+export const LargeTileCreateNewButton: React.FC<+ React.PropsWithChildren<ButtonishProps>+> = ({ onClick, children }) => (+ <LargeTileButton onClick={onClick}>+ <Stack+ sx={{+ flex: 1,+ height: "100%",+ border: "1px dashed",+ borderColor: "stroke.muted",+ borderRadius: "4px",+ padding: 1,+ }}+ >+ <Typography>{children}</Typography>+ <CenteredFill>+ <AddIcon />+ </CenteredFill>+ </Stack>+ </LargeTileButton>+);++/**+ * An {@link Overlay} suitable for showing text at the bottom center of the+ * tile. Used by the tiles in trash (for showing the days until deletion) and+ * duplicate listing (for showing the collection name).+ */+export const TileBottomTextOverlay = styled(Overlay)`+ display: flex;+ justify-content: center;+ align-items: flex-end;+ padding: 6px;+ background: linear-gradient(transparent 30%, 80%, rgba(0 0 0 / 0.7));+ color: white;+`;++/**+ * An {@link Overlay} for use with large file tiles, providing a container+ * for selection indicators and file size labels.+ */+export const LargeFileTileOverlay = styled(Overlay)`+ display: flex;+ pointer-events: none;+`;diff --git a/web/apps/albums/vendor/ente-new/photos/components/UnstyledButton.tsx b/web/apps/albums/vendor/ente-new/photos/components/UnstyledButton.tsxnew file mode 100644index 0000000000..d3d5d6f590--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/UnstyledButton.tsx@@ -0,0 +1,45 @@+import { styled } from "@mui/material";++/**+ * An "unstyled" button.+ *+ * There are cases where we semantically (and functionally) want a button, but+ * don't want the browser's default styling. This component is meant to act as a+ * base for such cases.+ *+ * Contrary to its name, it does add a bit of styling, to make these buttons fit+ * in with the rest of our theme.+ */+export const UnstyledButton = styled("button")`+ /* Reset some button defaults that are affecting us */+ background: transparent;+ border: 0;+ padding: 0;++ font: inherit;+ /* We customized the letter spacing in the theme. Need to tell the button to+ inherit that customization also. */+ letter-spacing: inherit;++ /* Default cursor on mouse over of a button is not a hand pointer */+ cursor: pointer;+`;++/**+ * A variant of {@link UnstyledButton} that modifying the keyboard focus and+ * activation states to match the styling of {@link FocusVisibleButton}.+ */+export const FocusVisibleUnstyledButton = styled(UnstyledButton)(+ ({ theme }) => `+ &:focus-visible {+ outline: 1px solid ${theme.vars.palette.stroke.base};+ outline-offset: 2px;+ border-radius: 2px;+ }+ &:active {+ outline: 1px solid ${theme.vars.palette.stroke.faint};+ outline-offset: 1px;+ border-radius: 2px;+ }+`,+);diff --git a/web/apps/albums/vendor/ente-new/photos/components/gallery/ListHeader.tsx b/web/apps/albums/vendor/ente-new/photos/components/gallery/ListHeader.tsxnew file mode 100644index 0000000000..1979ff5fe5--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/gallery/ListHeader.tsx@@ -0,0 +1,88 @@+import {+ Box,+ Stack,+ styled,+ Typography,+ type TypographyProps,+} from "@mui/material";+import { t } from "i18next";+import React from "react";++interface GalleryItemsSummaryProps {+ /**+ * The name / title for the items that are being shown.+ */+ name: string;+ /**+ * Optional extra props to pass to the {@link Typography} component that+ * shows {@link name}+ */+ nameProps?: TypographyProps;+ /**+ * The number of items being shown.+ */+ fileCount: number;+ /**+ * An optional element, usually an icon, placed after the file count.+ */+ endIcon?: React.ReactNode;+ /**+ * An optional click handler for the name.+ *+ * Note: Do not use this as the primary / only mechanism for the+ * corresponding functionality to be invoked, since this click handler will+ * be accessible only to sighted mouse users. However, it is fine to use it+ * as an alternate means of invoking some function.+ */+ onNameClick?: () => void;+}++/**+ * A component suitable for being used as a summary displayed on top of the of a+ * list of photos (or other items) shown in the gallery.+ */+export const GalleryItemsSummary: React.FC<GalleryItemsSummaryProps> = ({+ name,+ nameProps,+ fileCount,+ endIcon,+ onNameClick,+}) => (+ <div>+ <Typography variant="h3" {...(nameProps ?? {})} onClick={onNameClick}>+ {name}+ </Typography>++ <Stack+ direction="row"+ sx={{+ gap: 1.5,+ // Keep height the same even when there is no endIcon+ minHeight: "24px",+ }}+ >+ <Typography variant="small" sx={{ color: "text.muted" }}>+ {t("photos_count", { count: fileCount })}+ </Typography>+ {endIcon && (+ <Box sx={{ svg: { fontSize: "17px", color: "text.muted" } }}>+ {endIcon}+ </Box>+ )}+ </Stack>+ </div>+);++/**+ * A component suitable for wrapping a component which is acting like a gallery+ * items header so that it fills the entire width (and acts like a "header")+ * when it is displayed in the gallery view.+ *+ * The header view (e.g. a {@link GalleryItemsSummary}) is displayed as part of+ * the gallery items list itself so that it scrolls alongwith the items. This+ * wrapper makes it take the full width of the "row" that it occupies.+ */+export const GalleryItemsHeaderAdapter = styled("div")`+ width: 100%;+ margin-bottom: 12px;+`;diff --git a/web/apps/albums/vendor/ente-new/photos/components/gallery/index.tsx b/web/apps/albums/vendor/ente-new/photos/components/gallery/index.tsxnew file mode 100644index 0000000000..22f2de3b43--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/gallery/index.tsx@@ -0,0 +1,368 @@+/**+ * @file code that really belongs to pages/gallery.tsx itself (or related+ * files), but it written here in a separate file so that we can write in this+ * package that has TypeScript strict mode enabled.+ *+ * Once the original gallery.tsx is strict mode, this code can be inlined back+ * there.+ */++import AddPhotoAlternateIcon from "@mui/icons-material/AddPhotoAlternateOutlined";+import CheckIcon from "@mui/icons-material/Check";+import FolderIcon from "@mui/icons-material/FolderOutlined";+import SortIcon from "@mui/icons-material/Sort";+import {+ IconButton,+ Menu,+ Paper,+ Stack,+ styled,+ Tooltip,+ Typography,+} from "@mui/material";+import { CenteredFill, SpacedRow } from "ente-base/components/containers";+import { EnteLogo } from "ente-base/components/EnteLogo";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { OverflowMenuOption } from "ente-base/components/OverflowMenu";+import { useModalVisibility } from "ente-base/components/utils/modal";+import { type UploadTypeSelectorIntent } from "ente-gallery/components/Upload";+import type { SearchSuggestion } from "ente-new/photos/services/search/types";+import { t } from "i18next";+import React, { useRef, useState } from "react";+import { Trans } from "react-i18next";+import { enableML } from "../../services/ml";+import { EnableML, FaceConsent } from "../sidebar/MLSettings";+import { useMLStatusSnapshot } from "../utils/use-snapshot";+import { useWrapAsyncOperation } from "../utils/use-wrap-async";+import { GalleryItemsHeaderAdapter, GalleryItemsSummary } from "./ListHeader";++/**+ * Options to customize the behaviour of the remote pull that gets triggered on+ * various actions within the gallery and its descendants.+ */+export interface RemotePullOpts {+ /**+ * Perform the pull without showing a global loading bar+ *+ * Default: `false`.+ */+ silent?: boolean;+}+/**+ * The context in which a selection was made.+ *+ * This allows us to reset the selection if user moves to a different context+ * and starts a new selection.+ * */+export type SelectionContext =+ | { mode: "albums" | "hidden-albums"; collectionID: number }+ | { mode: "people"; personID: string };++interface SearchResultsHeaderProps {+ searchSuggestion: SearchSuggestion;+ fileCount: number;+ /**+ * Current sort order.+ * - `undefined`: No sort selected (keeps original order, e.g. CLIP relevance)+ * - `true`: Ascending (oldest first)+ * - `false`: Descending (newest first)+ */+ sortAsc: boolean | undefined;+ /**+ * Called when the user changes the sort order.+ * Pass `undefined` to reset to the original order (e.g., CLIP relevance).+ */+ onSortOrderChange: (asc: boolean | undefined) => void;+}++export const SearchResultsHeader: React.FC<SearchResultsHeaderProps> = ({+ searchSuggestion,+ fileCount,+ sortAsc,+ onSortOrderChange,+}) => {+ const sortButtonRef = useRef<HTMLButtonElement | null>(null);+ const { show: showSortOrderMenu, props: sortOrderMenuVisibilityProps } =+ useModalVisibility();++ const isClipSearch = searchSuggestion.type === "clip";++ const handleRelevanceClick = () => {+ onSortOrderChange(undefined);+ };++ const handleAscClick = () => {+ onSortOrderChange(true);+ };++ const handleDescClick = () => {+ onSortOrderChange(false);+ };++ return (+ <GalleryItemsHeaderAdapter>+ <Typography+ variant="h6"+ sx={{ fontWeight: "regular", color: "text.muted" }}+ >+ {t("search_results")}+ </Typography>+ <SpacedRow>+ <GalleryItemsSummary+ name={searchSuggestion.label}+ fileCount={fileCount}+ />+ {fileCount > 0 && (+ <Tooltip title={t("sort_by")}>+ <IconButton+ ref={sortButtonRef}+ onClick={showSortOrderMenu}+ >+ <SortIcon />+ </IconButton>+ </Tooltip>+ )}+ </SpacedRow>+ <SearchSortOrderMenu+ {...sortOrderMenuVisibilityProps}+ sortButtonRef={sortButtonRef}+ sortAsc={sortAsc}+ isClipSearch={isClipSearch}+ onRelevanceClick={handleRelevanceClick}+ onAscClick={handleAscClick}+ onDescClick={handleDescClick}+ />+ </GalleryItemsHeaderAdapter>+ );+};++interface SearchSortOrderMenuProps {+ open: boolean;+ onClose: () => void;+ sortButtonRef: React.RefObject<HTMLButtonElement | null>;+ sortAsc: boolean | undefined;+ /** Whether the current search is a CLIP (magic) search. */+ isClipSearch: boolean;+ /** Called when the user selects "Most Relevant" (only shown for CLIP searches). */+ onRelevanceClick: () => void;+ onAscClick: () => void;+ onDescClick: () => void;+}++const SearchSortOrderMenu: React.FC<SearchSortOrderMenuProps> = ({+ open,+ onClose,+ sortButtonRef,+ sortAsc,+ isClipSearch,+ onRelevanceClick,+ onAscClick,+ onDescClick,+}) => {+ const handleRelevanceClick = () => {+ onRelevanceClick();+ onClose();+ };++ const handleAscClick = () => {+ onAscClick();+ onClose();+ };++ const handleDescClick = () => {+ onDescClick();+ onClose();+ };++ return (+ <Menu+ id="search-results-sort"+ anchorEl={sortButtonRef.current}+ open={open}+ onClose={onClose}+ slotProps={{+ list: {+ disablePadding: true,+ "aria-labelledby": "search-results-sort",+ },+ }}+ anchorOrigin={{ vertical: "bottom", horizontal: "right" }}+ transformOrigin={{ vertical: "top", horizontal: "right" }}+ >+ {isClipSearch && (+ <OverflowMenuOption+ onClick={handleRelevanceClick}+ endIcon={sortAsc === undefined ? <CheckIcon /> : undefined}+ >+ {t("most_relevant")}+ </OverflowMenuOption>+ )}+ <OverflowMenuOption+ onClick={handleDescClick}+ endIcon={sortAsc === false ? <CheckIcon /> : undefined}+ >+ {t("newest_first")}+ </OverflowMenuOption>+ <OverflowMenuOption+ onClick={handleAscClick}+ endIcon={sortAsc === true ? <CheckIcon /> : undefined}+ >+ {t("oldest_first")}+ </OverflowMenuOption>+ </Menu>+ );+};++interface GalleryEmptyStateProps {+ /**+ * If `true`, then an upload is already in progress (the empty state will+ * then disable the prompts for uploads).+ */+ isUploadInProgress: boolean;+ /**+ * Called when the user selects one of the upload buttons. It is passed the+ * "intent" of the user.+ */+ onUpload: (intent: UploadTypeSelectorIntent) => void;+}++export const GalleryEmptyState: React.FC<GalleryEmptyStateProps> = ({+ isUploadInProgress,+ onUpload,+}) => (+ <Stack sx={{ alignItems: "center" }}>+ <Stack+ sx={{+ alignItems: "center",+ textAlign: "center",+ paddingBlock: "12px 32px",+ userSelect: "none",+ }}+ >+ <Typography+ variant="h3"+ sx={{+ color: "text.muted",+ mb: 1,+ svg: {+ color: "text.base",+ verticalAlign: "middle",+ mb: "2px",+ },+ }}+ >+ <Trans+ i18nKey="welcome_to_ente_title"+ components={{ a: <EnteLogo /> }}+ />+ </Typography>+ <Typography variant="h2">+ {t("welcome_to_ente_subtitle")}+ </Typography>+ </Stack>+ <NonDraggableImage+ height={287.57}+ alt=""+ src="/images/empty-state/ente_duck.png"+ srcSet="/images/empty-state/[email protected], /images/empty-state/[email protected]"+ />+ <Stack sx={{ py: 3, width: 320, gap: 1 }}>+ <FocusVisibleButton+ color="accent"+ onClick={() => onUpload("upload")}+ disabled={isUploadInProgress}+ sx={{ p: 1 }}+ >+ <Stack direction="row" sx={{ gap: 1, alignItems: "center" }}>+ <AddPhotoAlternateIcon />+ {t("upload_first_photo")}+ </Stack>+ </FocusVisibleButton>+ <FocusVisibleButton+ onClick={() => onUpload("import")}+ disabled={isUploadInProgress}+ sx={{ p: 1 }}+ >+ <Stack direction="row" sx={{ gap: 1, alignItems: "center" }}>+ <FolderIcon />+ {t("import_your_folders")}+ </Stack>+ </FocusVisibleButton>+ </Stack>+ </Stack>+);++/**+ * Prevent the image from being selected _and_ dragged, since dragging it+ * triggers the our dropdown selector overlay.+ */+const NonDraggableImage = styled("img")`+ pointer-events: none;+ user-select: none;+`;++export const PeopleEmptyState: React.FC = () => {+ const mlStatus = useMLStatusSnapshot();++ switch (mlStatus?.phase) {+ case "disabled":+ return <PeopleEmptyStateDisabled />;+ case "done":+ return (+ <PeopleEmptyStateMessage>+ {t("people_empty_too_few")}+ </PeopleEmptyStateMessage>+ );+ default:+ return (+ <PeopleEmptyStateMessage>+ {t("syncing_wait")}+ </PeopleEmptyStateMessage>+ );+ }+};++export const PeopleEmptyStateMessage: React.FC<React.PropsWithChildren> = ({+ children,+}) => (+ <CenteredFill>+ <Typography+ sx={{+ color: "text.muted",+ mx: 1,+ // Approximately compensate for the hidden section bar (86px),+ // and then add a bit extra padding so that the message appears+ // visually off the center, towards the top.+ paddingBlockEnd: "126px",+ }}+ >+ {children}+ </Typography>+ </CenteredFill>+);++export const PeopleEmptyStateDisabled: React.FC = () => {+ const [showConsent, setShowConsent] = useState(false);++ const handleConsent = useWrapAsyncOperation(async () => {+ await enableML();+ });++ return (+ <Stack sx={{ alignItems: "center", flex: 1, overflow: "auto" }}>+ <Paper+ // Top margin is to prevent clipping of the shadow.+ sx={{ maxWidth: "390px", padding: "4px", mt: 1, mb: "2rem" }}+ >+ {!showConsent ? (+ <EnableML onEnable={() => setShowConsent(true)} />+ ) : (+ <FaceConsent+ onConsent={handleConsent}+ onCancel={() => setShowConsent(false)}+ />+ )}+ </Paper>+ </Stack>+ );+};diff --git a/web/apps/albums/vendor/ente-new/photos/components/gallery/reducer.ts b/web/apps/albums/vendor/ente-new/photos/components/gallery/reducer.tsnew file mode 100644index 0000000000..dddbaf75bd--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/gallery/reducer.ts@@ -0,0 +1,2082 @@+import { type LocalUser } from "ente-accounts/services/user";+import {+ groupFilesByCollectionID,+ sortFiles,+ uniqueFilesByID,+} from "ente-gallery/utils/file";+import {+ CollectionOrder,+ collectionTypes,+ type Collection,+} from "ente-media/collection";+import type { EnteFile } from "ente-media/file";+import {+ isArchivedFile,+ type FilePrivateMagicMetadataData,+} from "ente-media/file-metadata";+import type { MagicMetadata } from "ente-media/magic-metadata";+import {+ createCollectionNameByID,+ isArchivedCollection,+ isHiddenCollection,+} from "ente-new/photos/services/collection";+import { sortTrashItems, type TrashItem } from "ente-new/photos/services/trash";+import { splitByPredicate } from "ente-utils/array";+import { includes } from "ente-utils/type-guards";+import { t } from "i18next";+import React, { useReducer } from "react";+import {+ findDefaultHiddenCollectionIDs,+ isDefaultHiddenCollection,+} from "../../services/collection";+import {+ CollectionSummarySortPriority,+ PseudoCollectionID,+ type CollectionSummary,+ type CollectionSummaryAttribute,+ type CollectionSummaryType,+} from "../../services/collection-summary";+import type { PeopleState, Person } from "../../services/ml/people";+import type { SearchSuggestion } from "../../services/search/types";+import type { FamilyData, UserDetails } from "../../services/user-details";++/**+ * Specifies what the bar at the top of the gallery is displaying currently.+ *+ * TODO: Deprecated(?). Use GalleryView instead. Deprecated if it can be used in+ * all cases where the bar mode was in use.+ */+export type GalleryBarMode = "albums" | "hidden-albums" | "people";++/**+ * Specifies what the gallery is currently displaying.+ *+ * This can be overridden by the display of search results.+ */+export type GalleryView =+ | {+ /**+ * We're either in the "Albums" or "Hidden albums" section.+ */+ type: "albums" | "hidden-albums";+ activeCollectionSummaryID: number;+ /**+ * If the active collection ID is for a collection and not a+ * pseudo-collection, this property will be set to the corresponding+ * {@link Collection}.+ *+ * It is guaranteed that this will be one of the {@link collections}+ * or {@link hiddenCollections}.+ */+ activeCollection: Collection | undefined;+ /**+ * The currently active collection summary.+ */+ activeCollectionSummary: CollectionSummary;+ }+ | {+ /**+ * We're in the "People" section.+ */+ type: "people";+ /**+ * The list of people to show in the gallery bar.+ *+ * Note that this can be different from the underlying list of+ * visiblePeople in the {@link peopleState}, and can temporarily+ * include a person from outside that list.+ */+ visiblePeople: Person[];+ /**+ * The currently selected person in the gallery bar, if any.+ *+ * It is guaranteed that when it is set, {@link activePerson} will be+ * one of the objects from among {@link people}.+ */+ activePerson: Person | undefined;+ };++/**+ * Derived UI state backing the gallery.+ *+ * This might be different from the actual different from the actual underlying+ * state since there might be unsynced data (hidden or deleted that have not yet+ * been synced with remote) that should be temporarily taken into account for+ * the UI state until the operation completes.+ */+export interface GalleryState {+ /*--< Mostly static state >--*/++ /**+ * The logged in {@link LocalUser}.+ *+ * This is expected to be undefined only for a brief duration until the code+ * for the initial "mount" runs (If we're not logged in, then the gallery+ * will redirect the user to an appropriate authentication page).+ */+ user: LocalUser | undefined;+ /**+ * Family plan related information for the logged in {@link LocalUser}.+ */+ familyData: FamilyData | undefined;++ /*--< Primary state: Files, collections, people >--*/++ /**+ * The user's collections.+ */+ collections: Collection[];+ /**+ * The user's files, without any unsynced modifications applied to them.+ *+ * The list is sorted so that newer files are first.+ *+ * This property is expected to be of use only internal to the reducer;+ * external code should only needs {@link files} instead.+ */+ lastSyncedCollectionFiles: EnteFile[];+ /**+ * The items in the user's trash.+ *+ * The items are sorted in ascending order of their time to deletion. For+ * more details about the sorting order, see {@link sortTrashItems}.+ */+ trashItems: TrashItem[];+ /**+ * Latest snapshot of people related state, as reported by+ * {@link usePeopleStateSnapshot}.+ */+ peopleState: PeopleState | undefined;++ /*--< Derived state >--*/++ /**+ * The user's "collection files", with any unsynced modifications also+ * applied to them.+ *+ * "Collection files" means that there might be multiple entries for the+ * same file ID, one for each collection the file belongs to. For more+ * details, see [Note: Collection file].+ *+ * The list is sorted so that newer files are first.+ *+ * See {@link lastSyncedFiles} for the same list, but without unsynced+ * modifications.+ *+ * [Note: Unsynced modifications]+ *+ * Unsynced modifications are those whose effects have already been made on+ * remote (so thus they have been "saved", so to say), but we still haven't+ * yet refreshed our local state to incorporate them. The refresh will+ * happen on the next files pull, until then they remain as in-memory state+ * in the reducer.+ */+ collectionFiles: EnteFile[];+ /**+ * Collection IDs of hidden collections.+ */+ hiddenCollectionIDs: Set<number>;+ /**+ * Collection IDs of default hidden collections.+ *+ * The default hidden collection contains files that have been hidden+ * individually. Rarely, but it is a technical possibility, multiple clients+ * might create such "default" hidden collections. So this needs to be a set+ * of IDs, but usually will be only one. In either case, the client shows a+ * "merged" default hidden collection to the user.+ */+ defaultHiddenCollectionIDs: Set<number>;+ /**+ * File IDs of hidden files.+ *+ * [Note: Hidden files]+ *+ * Files can be individually hidden, or hidden by virtue of being placed in+ * a hidden album. However unlike archiving (See: [Note: Archived files]),+ * in the case of individually hiding a file, we do not set a file level+ * property but rather move it to the "default hidden collection".+ *+ * So effectively, files can be hidden only by virtue of being present in a+ * hidden collection.+ *+ * If a file is present in any hidden collection, then it is considered+ * hidden. Since this computation requires multiple steps, we precompute the+ * list of such files and keep it this set.+ */+ hiddenFileIDs: Set<number>;+ /**+ * Collection IDs of archived collections.+ */+ archivedCollectionIDs: Set<number>;+ /**+ * File IDs of the files that the user has archived.+ *+ * Includes the effects of {@link unsyncedVisibilityUpdates}.+ *+ * [Note: Archived files]+ *+ * Files can be individually archived (which is a file level property), or+ * archived by virtue of being placed in an archived album (which is a+ * collection file level property).+ *+ * Archived files are not supposed to be shown in the all section,+ * irrespective of which of those two way they obtain their archive status.+ *+ * In particular, a (collection) file can be both in an archived album and+ * an normal album, so just checking for membership in archived collections+ * is not enough to filter them out from all. Instead, we need to compile a+ * list of file IDs that have the archive status, and then filter the+ * collection files using this list.+ *+ * For fast filtering, this is a set instead of a list.+ */+ archivedFileIDs: Set<number>;+ /**+ * File IDs of all the files that the user has marked as a favorite.+ *+ * Includes the effects of {@link unsyncedFavoriteUpdates}.+ *+ * For fast lookup, this is a set instead of a list.+ */+ favoriteFileIDs: Set<number>;+ /**+ * A map from collection IDs to their user visible name.+ *+ * It will contain entries for all collections (both normal and hidden).+ */+ collectionNameByID: Map<number, string>;+ /**+ * A map from file IDs to the IDs of the normal (non-hidden) collections+ * that they're a part of.+ */+ fileNormalCollectionIDs: Map<number, number[]>;+ /**+ * A map from known Ente user IDs to their emails+ *+ * This will not have an entry for the user themselves.+ *+ * This is used to perform a fast lookup of the email of the Ente user that+ * shared a file or collection.+ */+ emailByUserID: Map<number, string>;+ /**+ * A list of emails that can be served as suggestions when the user is+ * trying to share a collection with another Ente user.+ *+ * These are derived from the emails of the Ente users with whom the user+ * has already shared collections, plus the emails of their family members.+ */+ shareSuggestionEmails: string[];++ /*--< Derived UI state >--*/++ /**+ * A map of normal (non-hidden) collections massaged into a form suitable+ * for being directly consumed by the UI, indexed by the collection IDs.+ */+ normalCollectionSummaries: Map<number, CollectionSummary>;+ /**+ * A variant of {@link normalCollectionSummaries}, but for hidden+ * collections.+ */+ hiddenCollectionSummaries: Map<number, CollectionSummary>;+ /**+ * The ID of the collection summary that should be shown when the user+ * navigates to the uncategorized section.+ *+ * This will be either the ID of the user's uncategorized collection, if one+ * has already been created, otherwise it will be the predefined+ * {@link PseudoCollectionID.uncategorizedPlaceholder}.+ *+ * See: [Note: Uncategorized placeholder]+ */+ uncategorizedCollectionSummaryID: number;++ /*--< In-flight updates >--*/++ /**+ * File IDs of the files that have been just been deleted by the user.+ *+ * The delete on remote for these has either completed, or is currently in+ * flight, but the local state has not yet been updated. We stash these+ * changes here temporarily so that the UI can reflect the changes until our+ * local state also gets synced in a bit.+ */+ tempDeletedFileIDs: Set<number>;+ /**+ * Variant of {@link tempDeletedFileIDs} for files that have just been+ * hidden.+ */+ tempHiddenFileIDs: Set<number>;+ /**+ * File (IDs) for which there is currently an in-flight favorite /+ * unfavorite operation.+ *+ * See also {@link unsyncedFavoriteUpdates}.+ */+ pendingFavoriteUpdates: Set<number>;+ /**+ * Updates to the favorite status of files (triggered by some interactive+ * user action) that have already been made to applied to remote, but whose+ * effects on remote have not yet been synced back to our local DB.+ *+ * Each entry from a file ID to its favorite status (`true` if it belongs to+ * the user's favorites, false otherwise) which should be used for that file+ * instead of what we get from our local DB.+ *+ * The next time a remote pull completes, we clear this map since thereafter+ * just deriving {@link favoriteFileIDs} from our local files would reflect+ * the correct state on remote too.+ */+ unsyncedFavoriteUpdates: Map<number, boolean>;+ /**+ * File (IDs) for which there is currently an in-flight archive / unarchive+ * operation.+ *+ * See also {@link unsyncedPrivateMagicMetadataUpdates}.+ */+ pendingVisibilityUpdates: Set<number>;+ /**+ * Updates to file magic metadata (triggered by some interactive user+ * action) that have already been made to applied to remote, but whose+ * effects on remote have not yet been synced back to our local DB.+ *+ * Each entry from a file ID to the magic metadata that should be used for+ * that file instead of what we get from our local DB.+ *+ * The next time a remote pull completes, we clear this map since thereafter+ * the synced files themselves will reflect the latest private magic+ * metadata.+ */+ unsyncedPrivateMagicMetadataUpdates: Map<+ number,+ MagicMetadata<FilePrivateMagicMetadataData>+ >;++ /*--< State that underlies transient UI state >--*/++ /**+ * The currently selected collection summary, if any.+ *+ * When present, this is used to derive the+ * {@link activeCollectionSummaryID} property of the {@link view}.+ *+ * UI code should use the {@link view}, this property is meant as the+ * underlying primitive state. In particular, this does not get reset when+ * we switch sections, which allows us to come back to the same active+ * collection (if possible) on switching back.+ */+ selectedCollectionSummaryID: number | undefined;+ /**+ * The currently selected person, if any.+ *+ * When present, it is used to derive the {@link activePerson} property of+ * the {@link view}.+ *+ * UI code should use the {@link view}, this property is meant as the+ * underlying primitive state. In particular, this does not get reset when+ * we switch sections, which allows us to come back to the same person (if+ * possible) on switching back.+ */+ selectedPersonID: string | undefined;+ /**+ * If present, this person is tacked on the the list of visible people+ * temporarily (until the user switches out from the people view).+ *+ * This is needed to retain a usually non-visible but temporarily selected+ * person in the people bar until the user switches to some other view.+ */+ extraVisiblePerson: Person | undefined;+ /**+ * The suggestion selected by the user from the search bar dropdown.+ *+ * This is used to compute the {@link searchResults}.+ */+ searchSuggestion: SearchSuggestion | undefined;+ /**+ * List of files that match the selected search option.+ *+ * This will be set only if we are showing search results.+ *+ * The search dropdown shows a list of options ("suggestions") that match+ * the user's search term. If the user selects from one of these options,+ * then we run a search to find all files that match that suggestion, and+ * set this value to the result.+ */+ searchResults: EnteFile[] | undefined;+ /**+ * `true` an external effect is currently (asynchronously) updating search+ * results.+ */+ isRecomputingSearchResults: boolean;+ /**+ * {@link SearchSuggestion}s that have been enqueued while we were+ * recomputing the current search results.+ *+ * We only need the last element of this array (if any), the rest are+ * discarded when we get around to processing these.+ */+ pendingSearchSuggestions: SearchSuggestion[];++ /*--< Transient UI state >--*/++ /**+ * The view, and the item within it, that the gallery is currently showing.+ *+ * This can be temporarily overridden when we display search results.+ */+ view: GalleryView | undefined;+ /**+ * `true` if we are in "search mode".+ *+ * We will always be in search mode if we are showing search results, but we+ * also may be in search mode earlier on smaller screens, where the search+ * input is only shown on entering search mode. See: [Note: "Search mode"].+ *+ * That is, {@link isInSearchMode} may be true even when+ * {@link searchResults} is undefined.+ *+ * We will be _showing_ search results if both {@link isInSearchMode} is+ * `true` and {@link searchResults} is defined.+ */+ isInSearchMode: boolean;+ /**+ * Sort order for search results.+ *+ * - `undefined`: No explicit sort selected, keep original order (preserves+ * CLIP relevance sorting for ML searches)+ * - `true`: Ascending order (oldest first)+ * - `false`: Descending order (newest first)+ */+ searchSortAsc: boolean | undefined;+ /**+ * The files to show, uniqued and sorted appropriately.+ */+ filteredFiles: EnteFile[];+}++export type GalleryAction =+ | {+ type: "mount";+ user: LocalUser;+ familyData: FamilyData | undefined;+ collections: Collection[];+ collectionFiles: EnteFile[];+ trashItems: TrashItem[];+ }+ | { type: "setUserDetails"; userDetails: UserDetails }+ | { type: "setCollections"; collections: Collection[] }+ | { type: "setCollectionFiles"; collectionFiles: EnteFile[] }+ | { type: "uploadFile"; file: EnteFile }+ | { type: "setTrashItems"; trashItems: TrashItem[] }+ | { type: "setPeopleState"; peopleState: PeopleState | undefined }+ | { type: "markTempDeleted"; files: EnteFile[] }+ | { type: "clearTempDeleted" }+ | { type: "markTempHidden"; files: EnteFile[] }+ | { type: "clearTempHidden" }+ | { type: "addPendingFavoriteUpdate"; fileID: number }+ | { type: "removePendingFavoriteUpdate"; fileID: number }+ | { type: "unsyncedFavoriteUpdate"; fileID: number; isFavorite: boolean }+ | { type: "addPendingVisibilityUpdate"; fileID: number }+ | { type: "removePendingVisibilityUpdate"; fileID: number }+ | {+ type: "unsyncedPrivateMagicMetadataUpdate";+ fileID: number;+ privateMagicMetadata: MagicMetadata<FilePrivateMagicMetadataData>;+ }+ | { type: "clearUnsyncedState" }+ | { type: "showAll" }+ | { type: "showHidden" }+ | { type: "showAlbums" }+ | { type: "showCollectionSummary"; collectionSummaryID: number | undefined }+ | { type: "showPeople" }+ | { type: "showPerson"; personID: string }+ | { type: "enterSearchMode"; searchSuggestion?: SearchSuggestion }+ | { type: "updatingSearchResults" }+ | { type: "setSearchResults"; searchResults: EnteFile[] }+ | { type: "exitSearch"; shouldExitSearchMode?: boolean }+ | { type: "setSearchSortOrder"; asc: boolean | undefined };++const initialGalleryState: GalleryState = {+ user: undefined,+ familyData: undefined,+ collections: [],+ lastSyncedCollectionFiles: [],+ trashItems: [],+ peopleState: undefined,+ collectionFiles: [],+ hiddenCollectionIDs: new Set(),+ defaultHiddenCollectionIDs: new Set(),+ hiddenFileIDs: new Set(),+ archivedCollectionIDs: new Set(),+ archivedFileIDs: new Set(),+ favoriteFileIDs: new Set(),+ collectionNameByID: new Map(),+ fileNormalCollectionIDs: new Map(),+ emailByUserID: new Map(),+ shareSuggestionEmails: [],+ normalCollectionSummaries: new Map(),+ hiddenCollectionSummaries: new Map(),+ uncategorizedCollectionSummaryID:+ PseudoCollectionID.uncategorizedPlaceholder,+ tempDeletedFileIDs: new Set(),+ tempHiddenFileIDs: new Set(),+ pendingFavoriteUpdates: new Set(),+ unsyncedFavoriteUpdates: new Map(),+ pendingVisibilityUpdates: new Set(),+ unsyncedPrivateMagicMetadataUpdates: new Map(),+ selectedCollectionSummaryID: undefined,+ selectedPersonID: undefined,+ extraVisiblePerson: undefined,+ searchSuggestion: undefined,+ searchResults: undefined,+ isRecomputingSearchResults: false,+ pendingSearchSuggestions: [],+ view: undefined,+ filteredFiles: [],+ isInSearchMode: false,+ searchSortAsc: undefined,+};++const galleryReducer: React.Reducer<GalleryState, GalleryAction> = (+ state,+ action,+) => {+ if (process.env.NEXT_PUBLIC_ENTE_TRACE) console.log("dispatch", action);+ switch (action.type) {+ case "mount": {+ const { user, familyData } = action;++ const lastSyncedCollectionFiles = sortFiles(action.collectionFiles);+ const trashItems = sortTrashItems(action.trashItems);++ // During mount there are no unsynced updates, and we can directly+ // use the provided files.+ const collectionFiles = lastSyncedCollectionFiles;++ const collections = action.collections;++ const {+ normalCollections,+ hiddenCollections,+ hiddenCollectionIDs,+ hiddenFileIDs,+ } = deriveHiddenInfo(collections, collectionFiles);++ const archivedCollectionIDs =+ deriveArchivedCollectionIDs(normalCollections);+ const archivedFileIDs = deriveArchivedFileIDs(+ archivedCollectionIDs,+ collectionFiles,+ );++ const normalCollectionSummaries = deriveNormalCollectionSummaries(+ normalCollections,+ action.user,+ trashItems,+ collectionFiles,+ hiddenFileIDs,+ archivedFileIDs,+ );++ const hiddenCollectionSummaries = deriveHiddenCollectionSummaries(+ hiddenCollections,+ action.user,+ collectionFiles,+ );++ const view = {+ type: "albums" as const,+ activeCollectionSummaryID: PseudoCollectionID.all,+ activeCollection: undefined,+ activeCollectionSummary: normalCollectionSummaries.get(+ PseudoCollectionID.all,+ )!,+ };++ return stateByUpdatingFilteredFiles({+ ...state,+ user,+ familyData,+ collections,+ lastSyncedCollectionFiles,+ trashItems,+ collectionFiles,+ hiddenCollectionIDs,+ defaultHiddenCollectionIDs:+ deriveDefaultHiddenCollectionIDs(hiddenCollections),+ hiddenFileIDs,+ archivedCollectionIDs,+ archivedFileIDs,+ favoriteFileIDs: deriveFavoriteFileIDs(+ action.user,+ collections,+ collectionFiles,+ state.unsyncedFavoriteUpdates,+ ),+ collectionNameByID: createCollectionNameByID(+ action.collections,+ ),+ fileNormalCollectionIDs: deriveFileNormalCollectionIDs(+ collectionFiles,+ hiddenCollectionIDs,+ ),+ emailByUserID: constructUserIDToEmailMap(user, collections),+ shareSuggestionEmails: createShareSuggestionEmails(+ user,+ familyData,+ collections,+ ),+ normalCollectionSummaries,+ hiddenCollectionSummaries,+ uncategorizedCollectionSummaryID:+ deriveUncategorizedCollectionSummaryID(normalCollections),+ view,+ });+ }++ case "setUserDetails": {+ // While user details have more state that can change, the only+ // changes that affect the reducer's state (so far) are if the+ // user's own email changes, or the list of their family members+ // changes.+ //+ // Both of these affect only the list of share suggestion emails.++ let user = state.user!;+ const { email, familyData } = action.userDetails;+ if (email != user.email) {+ user = { ...user, email };+ }++ return {+ ...state,+ user,+ familyData,+ shareSuggestionEmails: createShareSuggestionEmails(+ user,+ familyData,+ state.collections,+ ),+ };+ }++ case "setCollections": {+ const collections = action.collections;++ const {+ normalCollections,+ hiddenCollections,+ hiddenCollectionIDs,+ hiddenFileIDs,+ } = deriveHiddenInfo(collections, state.collectionFiles);++ const archivedCollectionIDs =+ deriveArchivedCollectionIDs(normalCollections);+ const archivedFileIDs = deriveArchivedFileIDs(+ archivedCollectionIDs,+ state.collectionFiles,+ );++ const normalCollectionSummaries = deriveNormalCollectionSummaries(+ normalCollections,+ state.user!,+ state.trashItems,+ state.collectionFiles,+ hiddenFileIDs,+ archivedFileIDs,+ );++ const hiddenCollectionSummaries = deriveHiddenCollectionSummaries(+ hiddenCollections,+ state.user!,+ state.collectionFiles,+ );++ // Revalidate the active view if needed.+ let view = state.view;+ let selectedCollectionSummaryID = state.selectedCollectionSummaryID;+ if (state.view?.type == "albums") {+ ({ view, selectedCollectionSummaryID } =+ deriveAlbumsViewAndSelectedID(+ collections,+ hiddenCollectionIDs,+ normalCollectionSummaries,+ selectedCollectionSummaryID,+ ));+ } else if (state.view?.type == "hidden-albums") {+ ({ view, selectedCollectionSummaryID } =+ deriveHiddenAlbumsViewAndSelectedID(+ collections,+ hiddenCollectionIDs,+ hiddenCollectionSummaries,+ selectedCollectionSummaryID,+ ));+ }++ return stateByUpdatingFilteredFiles({+ ...state,+ collections,+ hiddenCollectionIDs,+ defaultHiddenCollectionIDs:+ deriveDefaultHiddenCollectionIDs(hiddenCollections),+ hiddenFileIDs,+ archivedCollectionIDs,+ archivedFileIDs,+ favoriteFileIDs: deriveFavoriteFileIDs(+ state.user!,+ normalCollections,+ state.collectionFiles,+ state.unsyncedFavoriteUpdates,+ ),+ collectionNameByID: createCollectionNameByID(collections),+ fileNormalCollectionIDs: deriveFileNormalCollectionIDs(+ state.collectionFiles,+ hiddenCollectionIDs,+ ),+ emailByUserID: constructUserIDToEmailMap(+ state.user!,+ collections,+ ),+ shareSuggestionEmails: createShareSuggestionEmails(+ state.user!,+ state.familyData,+ collections,+ ),+ normalCollectionSummaries,+ hiddenCollectionSummaries,+ uncategorizedCollectionSummaryID:+ deriveUncategorizedCollectionSummaryID(normalCollections),+ selectedCollectionSummaryID,+ pendingSearchSuggestions:+ enqueuePendingSearchSuggestionsIfNeeded(+ state.searchSuggestion,+ state.pendingSearchSuggestions,+ state.isInSearchMode,+ ),+ view,+ });+ }++ case "setCollectionFiles": {+ const lastSyncedCollectionFiles = sortFiles(action.collectionFiles);+ const collectionFiles = lastSyncedCollectionFiles;++ return stateByUpdatingFilteredFiles({+ ...stateForUpdatedCollectionFiles(state, collectionFiles),+ lastSyncedCollectionFiles,+ unsyncedPrivateMagicMetadataUpdates: new Map(),+ });+ }++ case "uploadFile": {+ // TODO: Consider batching this instead of doing it per file+ // upload to speed up uploads. Perf test first though.++ const lastSyncedCollectionFiles = sortFiles([+ ...state.lastSyncedCollectionFiles,+ action.file,+ ]);+ const collectionFiles = deriveCollectionFiles(+ lastSyncedCollectionFiles,+ state.unsyncedPrivateMagicMetadataUpdates,+ );++ return stateByUpdatingFilteredFiles({+ ...stateForUpdatedCollectionFiles(state, collectionFiles),+ lastSyncedCollectionFiles,+ });+ }++ case "setTrashItems": {+ const trashItems = sortTrashItems(action.trashItems);++ return stateByUpdatingFilteredFiles({+ ...state,+ trashItems,+ normalCollectionSummaries: deriveNormalCollectionSummaries(+ state.collections.filter(+ (c) => !state.hiddenCollectionIDs.has(c.id),+ ),+ state.user!,+ trashItems,+ state.collectionFiles,+ state.hiddenFileIDs,+ state.archivedFileIDs,+ ),+ });+ }++ case "setPeopleState": {+ const peopleState = action.peopleState;++ if (state.view?.type != "people") return { ...state, peopleState };++ const { view, extraVisiblePerson } = derivePeopleView(+ peopleState,+ state.tempDeletedFileIDs,+ state.tempHiddenFileIDs,+ state.selectedPersonID,+ state.extraVisiblePerson,+ );+ return stateByUpdatingFilteredFiles({+ ...state,+ peopleState,+ selectedPersonID: view.activePerson?.id,+ extraVisiblePerson,+ view,+ });+ }++ case "markTempDeleted":+ return stateByUpdatingFilteredFiles({+ ...state,+ tempDeletedFileIDs: new Set(+ [...state.tempDeletedFileIDs].concat(+ action.files.map((f) => f.id),+ ),+ ),+ });++ case "clearTempDeleted":+ return stateByUpdatingFilteredFiles({+ ...state,+ tempDeletedFileIDs: new Set(),+ });++ case "markTempHidden":+ return stateByUpdatingFilteredFiles({+ ...state,+ tempHiddenFileIDs: new Set(+ [...state.tempHiddenFileIDs].concat(+ action.files.map((f) => f.id),+ ),+ ),+ });++ case "clearTempHidden":+ return stateByUpdatingFilteredFiles({+ ...state,+ tempHiddenFileIDs: new Set(),+ });++ case "addPendingFavoriteUpdate": {+ const pendingFavoriteUpdates = new Set(+ state.pendingFavoriteUpdates,+ );+ pendingFavoriteUpdates.add(action.fileID);+ return { ...state, pendingFavoriteUpdates };+ }++ case "removePendingFavoriteUpdate": {+ const pendingFavoriteUpdates = new Set(+ state.pendingFavoriteUpdates,+ );+ pendingFavoriteUpdates.delete(action.fileID);+ return { ...state, pendingFavoriteUpdates };+ }++ case "unsyncedFavoriteUpdate": {+ const unsyncedFavoriteUpdates = new Map(+ state.unsyncedFavoriteUpdates,+ );+ unsyncedFavoriteUpdates.set(action.fileID, action.isFavorite);++ // Skipping a call to stateByUpdatingFilteredFiles since it+ // currently doesn't depend on favorites.+ return {+ ...state,+ favoriteFileIDs: deriveFavoriteFileIDs(+ state.user!,+ state.collections,+ state.collectionFiles,+ unsyncedFavoriteUpdates,+ ),+ unsyncedFavoriteUpdates,+ };+ }++ case "addPendingVisibilityUpdate": {+ const pendingVisibilityUpdates = new Set(+ state.pendingVisibilityUpdates,+ );+ pendingVisibilityUpdates.add(action.fileID);+ // Not using stateByUpdatingFilteredFiles since it does not depend+ // on pendingVisibilityUpdates.+ return { ...state, pendingVisibilityUpdates };+ }++ case "removePendingVisibilityUpdate": {+ const pendingVisibilityUpdates = new Set(+ state.pendingVisibilityUpdates,+ );+ pendingVisibilityUpdates.delete(action.fileID);+ return { ...state, pendingVisibilityUpdates };+ }++ case "unsyncedPrivateMagicMetadataUpdate": {+ const unsyncedPrivateMagicMetadataUpdates = new Map(+ state.unsyncedPrivateMagicMetadataUpdates,+ );+ unsyncedPrivateMagicMetadataUpdates.set(+ action.fileID,+ action.privateMagicMetadata,+ );++ const collectionFiles = deriveCollectionFiles(+ state.lastSyncedCollectionFiles,+ unsyncedPrivateMagicMetadataUpdates,+ );++ return stateByUpdatingFilteredFiles({+ ...stateForUpdatedCollectionFiles(state, collectionFiles),+ unsyncedPrivateMagicMetadataUpdates,+ });+ }++ case "clearUnsyncedState": {+ const unsyncedFavoriteUpdates: GalleryState["unsyncedFavoriteUpdates"] =+ new Map();+ const favoriteFileIDs = deriveFavoriteFileIDs(+ state.user!,+ state.collections,+ state.collectionFiles,+ unsyncedFavoriteUpdates,+ );++ const collectionFiles = state.lastSyncedCollectionFiles;+ const unsyncedPrivateMagicMetadataUpdates: GalleryState["unsyncedPrivateMagicMetadataUpdates"] =+ new Map();++ return stateByUpdatingFilteredFiles({+ ...stateForUpdatedCollectionFiles(+ {+ ...state,+ favoriteFileIDs,+ tempDeletedFileIDs: new Set(),+ tempHiddenFileIDs: new Set(),+ pendingFavoriteUpdates: new Set(),+ pendingVisibilityUpdates: new Set(),+ unsyncedPrivateMagicMetadataUpdates,+ unsyncedFavoriteUpdates: new Map(),+ },+ collectionFiles,+ ),+ unsyncedPrivateMagicMetadataUpdates,+ });+ }++ case "showAll":+ return stateByUpdatingFilteredFiles({+ ...state,+ selectedCollectionSummaryID: undefined,+ extraVisiblePerson: undefined,+ searchSuggestion: undefined,+ searchResults: undefined,+ isRecomputingSearchResults: false,+ pendingSearchSuggestions: [],+ view: {+ type: "albums",+ activeCollectionSummaryID: PseudoCollectionID.all,+ activeCollection: undefined,+ activeCollectionSummary:+ state.normalCollectionSummaries.get(+ PseudoCollectionID.all,+ )!,+ },+ isInSearchMode: false,+ });++ case "showHidden":+ return stateByUpdatingFilteredFiles({+ ...state,+ selectedCollectionSummaryID: undefined,+ extraVisiblePerson: undefined,+ searchSuggestion: undefined,+ searchResults: undefined,+ isRecomputingSearchResults: false,+ pendingSearchSuggestions: [],+ view: {+ type: "hidden-albums",+ activeCollectionSummaryID: PseudoCollectionID.hiddenItems,+ activeCollection: undefined,+ activeCollectionSummary:+ state.hiddenCollectionSummaries.get(+ PseudoCollectionID.hiddenItems,+ )!,+ },+ isInSearchMode: false,+ });++ case "showAlbums": {+ const { view, selectedCollectionSummaryID } =+ deriveAlbumsViewAndSelectedID(+ state.collections,+ state.hiddenCollectionIDs,+ state.normalCollectionSummaries,+ state.selectedCollectionSummaryID,+ );++ return stateByUpdatingFilteredFiles({+ ...state,+ selectedCollectionSummaryID,+ extraVisiblePerson: undefined,+ searchSuggestion: undefined,+ searchResults: undefined,+ isRecomputingSearchResults: false,+ pendingSearchSuggestions: [],+ view,+ isInSearchMode: false,+ });+ }++ case "showCollectionSummary": {+ const selectedCollectionSummaryID = action.collectionSummaryID;+ const activeCollection = state.collections.find(+ ({ id }) => id == selectedCollectionSummaryID,+ );++ let view: GalleryState["view"];+ if (+ selectedCollectionSummaryID !== undefined &&+ state.hiddenCollectionSummaries.has(selectedCollectionSummaryID)+ ) {+ const activeCollectionSummaryID = selectedCollectionSummaryID;+ view = {+ type: "hidden-albums",+ activeCollectionSummaryID,+ activeCollection,+ activeCollectionSummary:+ state.hiddenCollectionSummaries.get(+ activeCollectionSummaryID,+ )!,+ };+ } else {+ const activeCollectionSummaryID =+ selectedCollectionSummaryID ?? PseudoCollectionID.all;+ view = {+ type: "albums",+ activeCollectionSummaryID,+ activeCollection,+ activeCollectionSummary:+ state.normalCollectionSummaries.get(+ activeCollectionSummaryID,+ )!,+ };+ }++ return stateByUpdatingFilteredFiles({+ ...state,+ selectedCollectionSummaryID,+ extraVisiblePerson: undefined,+ searchResults: undefined,+ searchSuggestion: undefined,+ isRecomputingSearchResults: false,+ pendingSearchSuggestions: [],+ view,+ isInSearchMode: false,+ });+ }++ case "showPeople": {+ const { view, extraVisiblePerson } = derivePeopleView(+ state.peopleState,+ state.tempDeletedFileIDs,+ state.tempHiddenFileIDs,+ state.selectedPersonID,+ state.extraVisiblePerson,+ );+ return stateByUpdatingFilteredFiles({+ ...state,+ selectedPersonID: view.activePerson?.id,+ extraVisiblePerson,+ searchResults: undefined,+ searchSuggestion: undefined,+ isRecomputingSearchResults: false,+ pendingSearchSuggestions: [],+ view,+ isInSearchMode: false,+ });+ }++ case "showPerson": {+ const { view, extraVisiblePerson } = derivePeopleView(+ state.peopleState,+ state.tempDeletedFileIDs,+ state.tempHiddenFileIDs,+ action.personID,+ state.extraVisiblePerson,+ );+ return stateByUpdatingFilteredFiles({+ ...state,+ selectedPersonID: view.activePerson?.id,+ extraVisiblePerson,+ searchResults: undefined,+ searchSuggestion: undefined,+ isRecomputingSearchResults: false,+ pendingSearchSuggestions: [],+ view,+ isInSearchMode: false,+ });+ }++ case "enterSearchMode": {+ const pendingSearchSuggestions = action.searchSuggestion+ ? [...state.pendingSearchSuggestions, action.searchSuggestion]+ : state.pendingSearchSuggestions;++ return stateByUpdatingFilteredFiles({+ ...state,+ isInSearchMode: true,+ searchSuggestion: action.searchSuggestion,+ pendingSearchSuggestions,+ });+ }++ case "updatingSearchResults":+ return stateByUpdatingFilteredFiles({+ ...state,+ isRecomputingSearchResults: true,+ pendingSearchSuggestions: [],+ });++ case "setSearchResults":+ // Discard stale updates+ if (!state.isRecomputingSearchResults) return state;++ return stateByUpdatingFilteredFiles({+ ...state,+ searchResults: action.searchResults,+ isRecomputingSearchResults: false,+ });++ case "exitSearch": {+ // Only exit search mode if explicitly requested (defaults to true for backward compatibility)+ const shouldExitSearchMode = action.shouldExitSearchMode ?? true;+ return stateByUpdatingFilteredFiles({+ ...state,+ searchResults: undefined,+ searchSuggestion: undefined,+ isRecomputingSearchResults: false,+ pendingSearchSuggestions: [],+ isInSearchMode: shouldExitSearchMode+ ? false+ : state.isInSearchMode,+ });+ }++ case "setSearchSortOrder":+ return stateByUpdatingFilteredFiles({+ ...state,+ searchSortAsc: action.asc,+ });+ }+};++export const useGalleryReducer = () =>+ useReducer(galleryReducer, initialGalleryState);++/**+ * Compute the effective files that we should use by overlaying the files we+ * read from disk by any temporary unsynced updates.+ */+const deriveCollectionFiles = (+ lastSyncedCollectionFiles: GalleryState["lastSyncedCollectionFiles"],+ unsyncedPrivateMagicMetadataUpdates: GalleryState["unsyncedPrivateMagicMetadataUpdates"],+) => {+ // Happy fastpath.+ if (unsyncedPrivateMagicMetadataUpdates.size == 0)+ return lastSyncedCollectionFiles;++ // We have one or more unsynced private magic metadata updates that should+ // be applied to all the collection files with the matching file ID.+ return lastSyncedCollectionFiles.map((file) => {+ const privateMagicMetadata = unsyncedPrivateMagicMetadataUpdates.get(+ file.id,+ );+ if (!privateMagicMetadata) return file;++ return { ...file, magicMetadata: privateMagicMetadata };+ });+};++/**+ * Compute various bits of the state associated with hidden items from their+ * dependencies.+ */+const deriveHiddenInfo = (+ collections: GalleryState["collections"],+ collectionFiles: GalleryState["collectionFiles"],+) => {+ const [hiddenCollections, normalCollections] = splitByPredicate(+ collections,+ isHiddenCollection,+ );+ const hiddenCollectionIDs = new Set(hiddenCollections.map((c) => c.id));+ return {+ normalCollections,+ hiddenCollections,+ hiddenCollectionIDs,+ hiddenFileIDs: deriveHiddenFileIDs(+ collectionFiles,+ hiddenCollectionIDs,+ ),+ };+};++/**+ * Compute the list of hidden file IDs from their dependencies.+ */+const deriveHiddenFileIDs = (+ collectionFiles: GalleryState["collectionFiles"],+ hiddenCollectionIDs: GalleryState["hiddenCollectionIDs"],+) =>+ new Set(+ collectionFiles+ .filter((f) => hiddenCollectionIDs.has(f.collectionID))+ .map((f) => f.id),+ );++/**+ * Compute the default hidden collection IDs from their dependencies.+ */+const deriveDefaultHiddenCollectionIDs = (hiddenCollections: Collection[]) =>+ findDefaultHiddenCollectionIDs(hiddenCollections);++/**+ * Compute archived collection IDs from their dependencies.+ */+const deriveArchivedCollectionIDs = (collections: Collection[]) =>+ new Set<number>(+ collections+ .filter(isArchivedCollection)+ .map((collection) => collection.id),+ );++/**+ * Compute archived file IDs from their dependencies.+ */+const deriveArchivedFileIDs = (+ archivedCollectionIDs: GalleryState["archivedCollectionIDs"],+ collectionFiles: GalleryState["collectionFiles"],+) =>+ new Set(+ collectionFiles+ .filter(+ (file) =>+ isArchivedFile(file) ||+ archivedCollectionIDs.has(file.collectionID),+ )+ .map((f) => f.id),+ );++/**+ * Compute favorite file IDs from their dependencies.+ */+const deriveFavoriteFileIDs = (+ user: LocalUser,+ collections: GalleryState["collections"],+ collectionFiles: GalleryState["collectionFiles"],+ unsyncedFavoriteUpdates: GalleryState["unsyncedFavoriteUpdates"],+) => {+ let favoriteFileIDs = new Set<number>();+ for (const collection of collections) {+ // See: [Note: User and shared favorites]+ if (collection.type == "favorites" && collection.owner.id == user.id) {+ favoriteFileIDs = new Set(+ collectionFiles+ .filter((file) => file.collectionID == collection.id)+ .map((file) => file.id),+ );+ break;+ }+ }+ for (const [fileID, isFavorite] of unsyncedFavoriteUpdates.entries()) {+ if (isFavorite) favoriteFileIDs.add(fileID);+ else favoriteFileIDs.delete(fileID);+ }+ return favoriteFileIDs;+};++/**+ * Compute file to (non-hidden) collection mapping from its dependencies.+ */+const deriveFileNormalCollectionIDs = (+ collectionFiles: GalleryState["collectionFiles"],+ hiddenCollectionIDs: GalleryState["hiddenCollectionIDs"],+) =>+ createFileCollectionIDs(+ collectionFiles.filter((f) => !hiddenCollectionIDs.has(f.collectionID)),+ );++/**+ * Construct a map from file IDs to the list of collections (IDs) to which the+ * file belongs.+ */+const createFileCollectionIDs = (files: EnteFile[]) =>+ files.reduce((result, file) => {+ const id = file.id;+ let fs = result.get(id);+ if (!fs) result.set(id, (fs = []));+ fs.push(file.collectionID);+ return result;+ }, new Map<number, number[]>());++/**+ * Compute normal (non-hidden) collection summaries from their dependencies.+ */+const deriveNormalCollectionSummaries = (+ normalCollections: Collection[],+ user: LocalUser,+ trashItems: GalleryState["trashItems"],+ collectionFiles: GalleryState["collectionFiles"],+ hiddenFileIDs: GalleryState["hiddenFileIDs"],+ archivedFileIDs: GalleryState["archivedFileIDs"],+) => {+ const normalCollectionSummaries = createCollectionSummaries(+ user,+ normalCollections,+ collectionFiles,+ );++ const uncategorizedCollection = normalCollections.find(+ ({ type }) => type == "uncategorized",+ );+ if (!uncategorizedCollection) {+ const id = PseudoCollectionID.uncategorizedPlaceholder;+ normalCollectionSummaries.set(id, {+ ...pseudoCollectionOptionsForFiles([]),+ id,+ type: "uncategorized",+ attributes: new Set([+ "uncategorized",+ "system",+ "hideFromCollectionBar",+ ]),+ name: t("section_uncategorized"),+ sortPriority: CollectionSummarySortPriority.system,+ });+ }++ const allSectionFiles = uniqueFilesByID(+ collectionFiles.filter(+ (f) => !hiddenFileIDs.has(f.id) && !archivedFileIDs.has(f.id),+ ),+ );++ const archiveItemsFiles = uniqueFilesByID(+ collectionFiles.filter(+ (f) => !hiddenFileIDs.has(f.id) && isArchivedFile(f),+ ),+ );++ normalCollectionSummaries.set(PseudoCollectionID.all, {+ ...pseudoCollectionOptionsForFiles(allSectionFiles),+ id: PseudoCollectionID.all,+ type: "all",+ attributes: new Set(["all", "system"]),+ name: t("section_all"),+ sortPriority: CollectionSummarySortPriority.system,+ });++ normalCollectionSummaries.set(PseudoCollectionID.trash, {+ ...pseudoCollectionOptionsForLatestFileAndCount(+ trashItems[0]?.file,+ trashItems.length,+ ),+ id: PseudoCollectionID.trash,+ name: t("section_trash"),+ type: "trash",+ attributes: new Set(["trash", "system", "hideFromCollectionBar"]),+ coverFile: undefined,+ sortPriority: CollectionSummarySortPriority.other,+ });++ normalCollectionSummaries.set(PseudoCollectionID.archiveItems, {+ ...pseudoCollectionOptionsForFiles(archiveItemsFiles),+ id: PseudoCollectionID.archiveItems,+ name: t("section_archive"),+ type: "archiveItems",+ attributes: new Set([+ "archiveItems",+ "system",+ "hideFromCollectionBar",+ ]),+ coverFile: undefined,+ sortPriority: CollectionSummarySortPriority.other,+ });++ return normalCollectionSummaries;+};++const pseudoCollectionOptionsForFiles = (files: EnteFile[]) =>+ pseudoCollectionOptionsForLatestFileAndCount(files[0], files.length);++const pseudoCollectionOptionsForLatestFileAndCount = (+ file: EnteFile | undefined,+ fileCount: number,+) => ({+ coverFile: file,+ latestFile: file,+ fileCount,+ updationTime: file?.updationTime,+});++/**+ * Compute hidden collection summaries from their dependencies.+ */+const deriveHiddenCollectionSummaries = (+ hiddenCollections: Collection[],+ user: LocalUser,+ collectionFiles: GalleryState["collectionFiles"],+) => {+ const hiddenCollectionSummaries = createCollectionSummaries(+ user,+ hiddenCollections,+ collectionFiles,+ );++ const dhcIDs = findDefaultHiddenCollectionIDs(hiddenCollections);+ const defaultHiddenFiles = uniqueFilesByID(+ collectionFiles.filter((file) => dhcIDs.has(file.collectionID)),+ );+ hiddenCollectionSummaries.set(PseudoCollectionID.hiddenItems, {+ ...pseudoCollectionOptionsForFiles(defaultHiddenFiles),+ id: PseudoCollectionID.hiddenItems,+ name: t("hidden_items"),+ type: "hiddenItems",+ attributes: new Set(["hiddenItems", "system"]),+ sortPriority: CollectionSummarySortPriority.system,+ });++ return hiddenCollectionSummaries;+};++/**+ * Return the ID of the collection summary that should be shown when the user+ * navigates to the uncategorized section.+ */+const deriveUncategorizedCollectionSummaryID = (+ normalCollections: Collection[],+) =>+ normalCollections.find(({ type }) => type == "uncategorized")?.id ??+ PseudoCollectionID.uncategorizedPlaceholder;++const createCollectionSummaries = (+ user: LocalUser,+ collections: Collection[],+ collectionFiles: EnteFile[],+) => {+ const collectionSummaries = new Map<number, CollectionSummary>();++ const filesByCollection = groupFilesByCollectionID(collectionFiles);+ const coverFiles = findCoverFiles(collections, filesByCollection);++ for (const collection of collections) {+ const collectionType = includes(collectionTypes, collection.type)+ ? collection.type+ : "album";++ const attributes = new Set<CollectionSummaryAttribute>();++ let type: CollectionSummaryType;+ let name = collection.name;+ let sortPriority: CollectionSummarySortPriority =+ CollectionSummarySortPriority.other;++ if (collection.owner.id != user.id) {+ // This case needs to be the first; the rest assume that they're+ // dealing with collections owned by the user.+ type = "sharedIncoming";+ attributes.add("shared");+ attributes.add("sharedIncoming");+ const userRole = collection.sharees.find(+ (s) => s.id == user.id,+ )?.role;+ attributes.add(+ userRole == "ADMIN"+ ? "sharedIncomingAdmin"+ : userRole == "COLLABORATOR"+ ? "sharedIncomingCollaborator"+ : "sharedIncomingViewer",+ );+ } else if (collectionType == "uncategorized") {+ type = "uncategorized";+ name = t("section_uncategorized");+ attributes.add("system");+ attributes.add("hideFromCollectionBar");+ sortPriority = CollectionSummarySortPriority.system;+ } else if (collectionType == "favorites") {+ // [Note: User and shared favorites]+ //+ // "favorites" can be both the user's own favorites, or favorites of+ // other users shared with them. However, all of the latter will get+ // typed as "sharedIncoming" in the first case above.+ //+ // So if we get here and the collection summary has type+ // "favorites", it is guaranteed to be the user's own favorites. We+ // mark these with the type "userFavorites", which gives it special+ // treatment like custom icon etc.+ //+ // However, notice that the type of the _collection_ itself is not+ // changed, so whenever we're checking the type of the collection+ // (not of the collection summary) and we specifically want to+ // target the user's own favorites, we also need to check the+ // collection owner's ID is the same as the logged in user's ID.+ //+ // This case needs to be above the other cases since the primary+ // classification of this collection summary is that it is the+ // user's "favorites", everything else is secondary and can be part+ // of the `attributes` computed below.+ type = "userFavorites";+ name = t("favorites");+ sortPriority = CollectionSummarySortPriority.favorites;+ } else if (isDefaultHiddenCollection(collection)) {+ type = "defaultHidden";+ attributes.add("system");+ attributes.add("hideFromCollectionBar");+ } else {+ type = collectionType;+ }++ attributes.add(type);+ attributes.add(collectionType);++ if (collection.owner.id == user.id && collection.sharees.length) {+ attributes.add("shared");+ attributes.add("sharedOutgoing");+ }+ if (collection.publicURLs.length && !collection.sharees.length) {+ attributes.add("shared");+ attributes.add("sharedOnlyViaLink");+ }+ if (isArchivedCollection(collection)) {+ attributes.add("archived");+ }+ if (collection.magicMetadata?.data.order == CollectionOrder.pinned) {+ attributes.add("pinned");+ sortPriority = CollectionSummarySortPriority.pinned;+ }+ // Check for sharee pinned (for incoming shared collections)+ if (+ type == "sharedIncoming" &&+ collection.sharedMagicMetadata?.data.order == CollectionOrder.pinned+ ) {+ attributes.add("shareePinned");+ sortPriority = CollectionSummarySortPriority.pinned;+ }++ if (type == "sharedIncoming" && collectionType == "favorites") {+ // See: [Note: User and shared favorites] above.+ //+ // Use the first letter of the email of the user who shared this+ // particular favorite as a prefix to disambiguate this collection+ // from the user's own favorites.+ // TODO: Use the person name when avail+ const initial = collection.owner.email?.at(0)?.toUpperCase();+ if (initial) {+ name = t("person_favorites", { name: initial });+ } else {+ name = t("shared_favorites");+ }+ }++ const collectionFiles = filesByCollection.get(collection.id);++ // Hide empty favorites from collection bar+ if (type == "userFavorites" && !collectionFiles?.length) {+ attributes.add("hideFromCollectionBar");+ }++ collectionSummaries.set(collection.id, {+ id: collection.id,+ type,+ attributes,+ name,+ latestFile: collectionFiles?.[0],+ coverFile: coverFiles.get(collection.id),+ fileCount: collectionFiles?.length ?? 0,+ updationTime: collection.updationTime,+ sortPriority,+ });+ }++ return collectionSummaries;+};++const findCoverFiles = (+ collections: Collection[],+ filesByCollection: Map<number, EnteFile[]>,+): Map<number, EnteFile> => {+ const coverFiles = new Map<number, EnteFile>();+ for (const collection of collections) {+ const collectionFiles = filesByCollection.get(collection.id);+ if (!collectionFiles || collectionFiles.length == 0) continue;++ let coverFile: EnteFile | undefined;++ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition+ const coverID = collection.pubMagicMetadata?.data?.coverID;+ if (typeof coverID == "number" && coverID > 0) {+ coverFile = collectionFiles.find(({ id }) => id === coverID);+ }++ if (!coverFile) {+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition+ if (collection.pubMagicMetadata?.data?.asc) {+ coverFile = collectionFiles[collectionFiles.length - 1];+ } else {+ coverFile = collectionFiles[0];+ }+ }++ if (coverFile) {+ coverFiles.set(collection.id, coverFile);+ }+ }+ return coverFiles;+};++/**+ * Compute the {@link GalleryView} from its dependencies when we are switching+ * to (or back to) the "albums" view, or the underlying collections might've+ * changed.+ */+const deriveAlbumsViewAndSelectedID = (+ collections: GalleryState["collections"],+ hiddenCollectionIDs: GalleryState["hiddenCollectionIDs"],+ collectionSummaries: GalleryState["normalCollectionSummaries"],+ selectedCollectionSummaryID: GalleryState["selectedCollectionSummaryID"],+) => {+ // Make sure that the last selected ID is still valid by searching for it.+ const selectedCollectionSummary = selectedCollectionSummaryID+ ? collectionSummaries.get(selectedCollectionSummaryID)+ : undefined;++ const activeCollectionSummaryID =+ selectedCollectionSummary?.id ?? PseudoCollectionID.all;+ const activeCollectionSummary = collectionSummaries.get(+ activeCollectionSummaryID,+ )!;+ const activeCollection =+ selectedCollectionSummary &&+ !hiddenCollectionIDs.has(activeCollectionSummaryID)+ ? collections.find(({ id }) => id == activeCollectionSummaryID)+ : undefined;+ return {+ selectedCollectionSummaryID: activeCollectionSummaryID,+ view: {+ type: "albums" as const,+ activeCollectionSummaryID,+ activeCollection,+ activeCollectionSummary,+ },+ };+};++/**+ * Sibling of {@link deriveAlbumsViewAndSelectedID} for when we're in the hidden+ * albums section.+ */+const deriveHiddenAlbumsViewAndSelectedID = (+ collections: GalleryState["collections"],+ hiddenCollectionIDs: GalleryState["hiddenCollectionIDs"],+ hiddenCollectionSummaries: GalleryState["hiddenCollectionSummaries"],+ selectedCollectionSummaryID: GalleryState["selectedCollectionSummaryID"],+) => {+ // Make sure that the last selected ID is still valid by searching for it.+ const selectedCollectionSummary = selectedCollectionSummaryID+ ? hiddenCollectionSummaries.get(selectedCollectionSummaryID)+ : undefined;++ const activeCollectionSummaryID =+ selectedCollectionSummary?.id ?? PseudoCollectionID.hiddenItems;+ const activeCollectionSummary = hiddenCollectionSummaries.get(+ activeCollectionSummaryID,+ )!;+ const activeCollection =+ selectedCollectionSummary &&+ hiddenCollectionIDs.has(activeCollectionSummaryID)+ ? collections.find(({ id }) => id == activeCollectionSummaryID)+ : undefined;+ return {+ selectedCollectionSummaryID: activeCollectionSummaryID,+ view: {+ type: "hidden-albums" as const,+ activeCollectionSummaryID,+ activeCollection,+ activeCollectionSummary,+ },+ };+};++/**+ * Compute the {@link GalleryView} from its dependencies when we are switching+ * to (or back to) the "people" view.+ */+const derivePeopleView = (+ peopleState: GalleryState["peopleState"],+ tempDeletedFileIDs: GalleryState["tempDeletedFileIDs"],+ tempHiddenFileIDs: GalleryState["tempHiddenFileIDs"],+ selectedPersonID: GalleryState["selectedPersonID"],+ extraVisiblePerson: GalleryState["extraVisiblePerson"],+): {+ view: Extract<GalleryView, { type: "people" }>;+ extraVisiblePerson: GalleryState["extraVisiblePerson"];+} => {+ let people = peopleState?.people ?? [];+ let visiblePeople = peopleState?.visiblePeople ?? [];+ if (tempDeletedFileIDs.size + tempHiddenFileIDs.size > 0) {+ // Prune the in-memory temp updates from the actual state to+ // obtain the UI state. Kept inside an preflight check to so+ // that the common path remains fast.+ const filterTemp = (ps: Person[]) =>+ ps+ .map((p) => ({+ ...p,+ fileIDs: p.fileIDs.filter(+ (id) =>+ !tempDeletedFileIDs.has(id) &&+ !tempHiddenFileIDs.has(id),+ ),+ }))+ .filter((p) => p.fileIDs.length > 0);+ people = filterTemp(people);+ visiblePeople = filterTemp(visiblePeople);+ }++ // We might have an extraVisiblePerson that is now part of the visible ones+ // when the user un-ignores a person. If that's the case (which we can+ // detect by its absence from the list of underlying people, since its ID+ // would've changed), clear it out, otherwise we'll end up with two entries.+ if (extraVisiblePerson) {+ if (!people.find((p) => p.id == extraVisiblePerson?.id))+ extraVisiblePerson = undefined;+ }++ const findByIDIn = (ps: Person[]) =>+ ps.find((p) => p.id == selectedPersonID);+ let activePerson = findByIDIn(visiblePeople);+ if (!activePerson) {+ // This might be one of the normally hidden small clusters.+ activePerson = findByIDIn(people);+ if (activePerson) {+ // Temporarily add this person's entry to the list of people+ // surfaced in the people view.+ extraVisiblePerson = activePerson;+ } else {+ // We don't have an "All" pseudo-album in people view, so default to+ // the first person in the list (if any).+ activePerson = visiblePeople[0];+ }+ }++ const view = {+ type: "people" as const,+ visiblePeople: extraVisiblePerson+ ? visiblePeople.concat([extraVisiblePerson])+ : visiblePeople,+ activePerson,+ };++ return { view, extraVisiblePerson };+};++/**+ * Return a new state from the given {@link state} by recomputing all properties+ * that depend on collection files, using the provided {@link collectionFiles}.+ *+ * Usually, we update state by manually dependency tracking on a fine grained+ * basis, but it results in a duplicate code when the files themselves change,+ * since they effect many things.+ *+ * So this is a convenience function for updating everything that needs to+ * change when the collections files themselves change.+ */+const stateForUpdatedCollectionFiles = (+ state: GalleryState,+ collectionFiles: GalleryState["collectionFiles"],+): GalleryState => {+ const hiddenFileIDs = deriveHiddenFileIDs(+ collectionFiles,+ state.hiddenCollectionIDs,+ );+ return {+ ...state,+ collectionFiles,+ hiddenFileIDs,+ archivedFileIDs: deriveArchivedFileIDs(+ state.archivedCollectionIDs,+ collectionFiles,+ ),+ favoriteFileIDs: deriveFavoriteFileIDs(+ state.user!,+ state.collections,+ collectionFiles,+ state.unsyncedFavoriteUpdates,+ ),+ fileNormalCollectionIDs: deriveFileNormalCollectionIDs(+ collectionFiles,+ state.hiddenCollectionIDs,+ ),+ normalCollectionSummaries: deriveNormalCollectionSummaries(+ state.collections.filter(+ (c) => !state.hiddenCollectionIDs.has(c.id),+ ),+ state.user!,+ state.trashItems,+ collectionFiles,+ hiddenFileIDs,+ state.archivedFileIDs,+ ),+ hiddenCollectionSummaries: deriveHiddenCollectionSummaries(+ state.collections.filter((c) =>+ state.hiddenCollectionIDs.has(c.id),+ ),+ state.user!,+ collectionFiles,+ ),+ pendingSearchSuggestions: enqueuePendingSearchSuggestionsIfNeeded(+ state.searchSuggestion,+ state.pendingSearchSuggestions,+ state.isInSearchMode,+ ),+ };+};++/**+ * Return a new state by recomputing the {@link filteredFiles} property+ * depending on which view we are showing+ *+ * Usually, we update state by manually dependency tracking on a fine grained+ * basis, but it is cumbersome (and mistake prone) to do that for the list of+ * filtered files which depend on a many things.+ *+ * So this is a convenience function for recomputing filtered files whenever any+ * bit of the underlying state that could affect the list of files changes.+ */+const stateByUpdatingFilteredFiles = (state: GalleryState) => {+ if (state.isInSearchMode) {+ const searchFiles = state.searchResults ?? state.filteredFiles;+ // Only apply time-based sorting if user explicitly selected a sort order.+ // When undefined, keep original order (preserves CLIP relevance sorting).+ const filteredFiles =+ state.searchSortAsc !== undefined+ ? sortFiles([...searchFiles], state.searchSortAsc)+ : searchFiles;+ return { ...state, filteredFiles };+ } else if (+ state.view?.type == "albums" ||+ state.view?.type == "hidden-albums"+ ) {+ const filteredFiles = deriveAlbumsOrHiddenAlbumsFilteredFiles(+ state.trashItems,+ state.collectionFiles,+ state.defaultHiddenCollectionIDs,+ state.hiddenFileIDs,+ state.archivedCollectionIDs,+ state.archivedFileIDs,+ state.tempDeletedFileIDs,+ state.tempHiddenFileIDs,+ state.view,+ );+ return { ...state, filteredFiles };+ } else if (state.view?.type == "people") {+ const filteredFiles = derivePeopleFilteredFiles(+ state.collectionFiles,+ state.hiddenFileIDs,+ state.view,+ );+ return { ...state, filteredFiles };+ } else {+ return state;+ }+};++/**+ * Compute the sorted list of files to show when we're in the "albums" or+ * "hidden-albums" view and the dependencies change.+ */+const deriveAlbumsOrHiddenAlbumsFilteredFiles = (+ trashItems: GalleryState["trashItems"],+ collectionFiles: GalleryState["collectionFiles"],+ defaultHiddenCollectionIDs: GalleryState["defaultHiddenCollectionIDs"],+ hiddenFileIDs: GalleryState["hiddenFileIDs"],+ archivedCollectionIDs: GalleryState["archivedCollectionIDs"],+ archivedFileIDs: GalleryState["archivedFileIDs"],+ tempDeletedFileIDs: GalleryState["tempDeletedFileIDs"],+ tempHiddenFileIDs: GalleryState["tempHiddenFileIDs"],+ view: Extract<GalleryView, { type: "albums" | "hidden-albums" }>,+) => {+ const activeCollectionSummaryID = view.activeCollectionSummaryID;++ // Trash is dealt with separately.+ //+ // [Note: Files in trash pseudo collection have deleteBy]+ //+ // When showing the trash pseudo collection, each file in the files array is+ // in fact an instance of `EnteTrashFile` - it has an additional (and+ // optional) `deleteBy` property. The types don't reflect this.++ if (activeCollectionSummaryID == PseudoCollectionID.trash) {+ return uniqueFilesByID([+ ...trashItems.map(({ file, deleteBy }) => ({ ...file, deleteBy })),+ ...collectionFiles.filter((file) =>+ tempDeletedFileIDs.has(file.id),+ ),+ ]);+ }++ const filteredFiles = collectionFiles.filter((file) => {+ if (tempDeletedFileIDs.has(file.id)) return false;++ // "Hidden items" shows all individually hidden files.+ if (+ activeCollectionSummaryID == PseudoCollectionID.hiddenItems &&+ defaultHiddenCollectionIDs.has(file.collectionID)+ ) {+ return true;+ }++ // Archived files can only be seen in the archive items, or in their+ // respective collection. Hidden files should be excluded in from+ // archive items (but not from their album).+ //+ // Note that a file may both be archived, AND be part of an archived+ // collection. Such files should be shown in both the archive section+ // and in their respective collection. Thus this (archived file) case+ // needs to be before the following (archived collection) case.+ if (isArchivedFile(file)) {+ return (+ (activeCollectionSummaryID == PseudoCollectionID.archiveItems &&+ !hiddenFileIDs.has(file.id) &&+ !tempHiddenFileIDs.has(file.id)) ||+ activeCollectionSummaryID == file.collectionID+ );+ }++ // Files in archived collections can only be seen in their respective+ // collection.+ if (archivedCollectionIDs.has(file.collectionID)) {+ return activeCollectionSummaryID === file.collectionID;+ }++ if (activeCollectionSummaryID === PseudoCollectionID.all) {+ // Hidden files should not be shown in "All".+ if (hiddenFileIDs.has(file.id)) return false;+ if (tempHiddenFileIDs.has(file.id)) return false;++ // Archived files (whether individually archived, or part of some+ // archived album) should not be shown in "All".+ if (archivedFileIDs.has(file.id)) {+ return false;+ }++ // Show all remaining (non-hidden, non-archived) files in "All".+ return true;+ }++ // Show files that belong to the active collection.+ return activeCollectionSummaryID == file.collectionID;+ });++ return sortAndUniqueFilteredFiles(filteredFiles, view.activeCollection);+};++/**+ * Prepare the list of files for being shown in the gallery.+ *+ * This functions uniques the given collection files so that there is only one+ * entry per file ID. Then it sorts them if the active collection prefers them+ * to be sorted oldest first (by default, lists of collection files are sorted+ * newest first, and we assume that {@link files} are already sorted that way).+ */+const sortAndUniqueFilteredFiles = (+ files: EnteFile[],+ activeCollection: Collection | undefined,+) => {+ const uniqueFiles = uniqueFilesByID(files);+ const sortAsc = activeCollection?.pubMagicMetadata?.data.asc ?? false;+ return sortAsc ? sortFiles(uniqueFiles, true) : uniqueFiles;+};++/**+ * Compute the sorted list of files to show when we're in the "people" view and+ * the dependencies change.+ */+const derivePeopleFilteredFiles = (+ collectionFiles: GalleryState["collectionFiles"],+ hiddenFileIDs: GalleryState["hiddenFileIDs"],+ view: Extract<GalleryView, { type: "people" }>,+) => {+ const pfSet = new Set(view.activePerson?.fileIDs ?? []);+ return uniqueFilesByID(+ collectionFiles.filter((f) => {+ if (!pfSet.has(f.id)) return false;+ if (hiddenFileIDs.has(f.id)) return false;+ return true;+ }),+ );+};++/**+ * Trigger a recomputation of search results if needed.+ *+ * This convenience helper is used on updates to some state (collections, files)+ * that is used to derive the base set of files on which the search are+ * performed. It re-enqueues the current search suggestion as pending, which'll+ * trigger a recomputation of the state's {@link searchResults}.+ */+const enqueuePendingSearchSuggestionsIfNeeded = (+ searchSuggestion: GalleryState["searchSuggestion"],+ pendingSearchSuggestions: GalleryState["pendingSearchSuggestions"],+ isInSearchMode: GalleryState["isInSearchMode"],+) =>+ searchSuggestion && isInSearchMode+ ? [...pendingSearchSuggestions, searchSuggestion]+ : pendingSearchSuggestions;++/**+ * Create a map from the user IDs to their emails, with entries for all Ente+ * users who have shared a collection with the user.+ */+const constructUserIDToEmailMap = (+ user: LocalUser,+ collections: GalleryState["collections"],+): Map<number, string> => {+ const userIDToEmail = new Map<number, string>();+ for (const { owner, sharees } of collections) {+ if (user.id != owner.id && owner.email) {+ userIDToEmail.set(owner.id, owner.email);+ }+ for (const sharee of sharees) {+ if (sharee.id != user.id && sharee.email) {+ userIDToEmail.set(sharee.id, sharee.email);+ }+ }+ }+ return userIDToEmail;+};++/**+ * Create a list of emails that are shown as suggestions to the user when they+ * are trying to share albums with specific users.+ */+const createShareSuggestionEmails = (+ user: LocalUser,+ familyData: FamilyData | undefined,+ collections: Collection[],+): string[] => [+ ...new Set(+ collections+ .map(({ owner, sharees }) =>+ owner.email && owner.id != user.id+ ? [owner.email]+ : sharees.map(({ email }) => email),+ )+ .flat()+ .filter((e) => e !== undefined)+ .concat((familyData?.members ?? []).map((member) => member.email))+ .filter((email) => email != user.email),+ ),+];diff --git a/web/apps/albums/vendor/ente-new/photos/components/icons/StarIcon.tsx b/web/apps/albums/vendor/ente-new/photos/components/icons/StarIcon.tsxnew file mode 100644index 0000000000..920405c01e--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/icons/StarIcon.tsx@@ -0,0 +1,31 @@+import SvgIcon, { type SvgIconProps } from "@mui/material/SvgIcon";+import React from "react";++/**+ * Custom star icon (filled).+ *+ * This is the app's custom star shape used for favorites.+ */+export const StarIcon: React.FC<SvgIconProps> = (props) => (+ <SvgIcon {...props} viewBox="0 0 21 20">+ <path d="M8.69381 1.56975C9.38617 0.609562 10.7995 0.609562 11.4919 1.56975L13.7114 4.64784C13.9253 4.9445 14.2255 5.16569 14.5699 5.28031L18.1427 6.46961C19.2572 6.84061 19.6939 8.20365 19.0073 9.16808L16.8062 12.2597C16.5941 12.5577 16.4794 12.9156 16.4783 13.2831L16.4669 17.0962C16.4634 18.2857 15.32 19.1281 14.2033 18.764L10.6234 17.5966C10.2784 17.4841 9.90729 17.4841 9.56228 17.5966L5.98245 18.764C4.86575 19.1281 3.72231 18.2857 3.71876 17.0962L3.70737 13.2831C3.70628 12.9156 3.5916 12.5577 3.37946 12.2597L1.17839 9.16808C0.491785 8.20365 0.928537 6.84061 2.04305 6.46961L5.61584 5.28031C5.96017 5.16569 6.26041 4.9445 6.47432 4.64784L8.69381 1.56975Z" />+ </SvgIcon>+);++/**+ * Custom star icon (outline).+ *+ * This is the app's custom star shape used for favorites (outline variant).+ */+export const StarBorderIcon: React.FC<SvgIconProps> = (props) => (+ <SvgIcon {...props} viewBox="0 0 21 20">+ <path+ d="M8.69381 1.56975C9.38617 0.609562 10.7995 0.609562 11.4919 1.56975L13.7114 4.64784C13.9253 4.9445 14.2255 5.16569 14.5699 5.28031L18.1427 6.46961C19.2572 6.84061 19.6939 8.20365 19.0073 9.16808L16.8062 12.2597C16.5941 12.5577 16.4794 12.9156 16.4783 13.2831L16.4669 17.0962C16.4634 18.2857 15.32 19.1281 14.2033 18.764L10.6234 17.5966C10.2784 17.4841 9.90729 17.4841 9.56228 17.5966L5.98245 18.764C4.86575 19.1281 3.72231 18.2857 3.71876 17.0962L3.70737 13.2831C3.70628 12.9156 3.5916 12.5577 3.37946 12.2597L1.17839 9.16808C0.491785 8.20365 0.928537 6.84061 2.04305 6.46961L5.61584 5.28031C5.96017 5.16569 6.26041 4.9445 6.47432 4.64784L8.69381 1.56975Z"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.7"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </SvgIcon>+);diff --git a/web/apps/albums/vendor/ente-new/photos/components/icons/StarOffIcon.tsx b/web/apps/albums/vendor/ente-new/photos/components/icons/StarOffIcon.tsxnew file mode 100644index 0000000000..16086e5cd1--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/icons/StarOffIcon.tsx@@ -0,0 +1,28 @@+import SvgIcon, { type SvgIconProps } from "@mui/material/SvgIcon";+import React from "react";++/**+ * Custom star-off icon (unfavorite).+ *+ * This is the app's custom star with a strike-through used to remove favorites.+ */+export const StarOffIcon: React.FC<SvgIconProps> = (props) => (+ <SvgIcon {...props} viewBox="0 0 21 20">+ <svg+ xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 24 24"+ width="24"+ height="24"+ color="#ffffff"+ fill="none"+ stroke="#ffffff"+ strokeWidth="1.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M18.5038 14.5L21.1477 11.8925C22.616 10.4206 22.1366 8.92853 20.099 8.58575L16.9128 8.05143C16.3734 7.9607 15.7342 7.48687 15.4945 6.99288L13.7366 3.44418C12.7877 1.51861 11.2296 1.51861 10.2707 3.44418L9.5 5" />+ <path d="M7.29561 7.99998C7.22668 8.02267 7.15848 8.04006 7.09201 8.05144L3.90008 8.58576C1.85885 8.92853 1.38856 10.4206 2.84945 11.8925L5.33095 14.3927C5.7512 14.8161 5.98134 15.6327 5.85126 16.2175L5.14083 19.3125C4.58049 21.7522 5.88128 22.7099 8.02257 21.4296L11.0144 19.6452C11.5647 19.3226 12.4553 19.3226 12.9956 19.6452L15.9874 21.4296C18.1387 22.7099 19.4295 21.7623 18.8691 19.3125L18.7974 19" />+ <path d="M2 2L22 22" />+ </svg>+ </SvgIcon>+);diff --git a/web/apps/albums/vendor/ente-new/photos/components/sidebar/MLSettings.tsx b/web/apps/albums/vendor/ente-new/photos/components/sidebar/MLSettings.tsxnew file mode 100644index 0000000000..4dd90d07cd--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/sidebar/MLSettings.tsx@@ -0,0 +1,319 @@+import {+ Box,+ Button,+ Checkbox,+ Divider,+ FormControlLabel,+ FormGroup,+ Link,+ Stack,+ Typography,+} from "@mui/material";+import { RowButtonGroup, RowSwitch } from "ente-base/components/RowButton";+import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import {+ TitledNestedSidebarDrawer,+ type NestedSidebarDrawerVisibilityProps,+} from "ente-base/components/mui/SidebarDrawer";+import { useBaseContext } from "ente-base/context";+import {+ disableML,+ enableML,+ type MLStatus,+} from "ente-new/photos/services/ml";+import { t } from "i18next";+import React, { useEffect, useState } from "react";+import { Trans } from "react-i18next";+import { openURL } from "../../utils/web";+import { useMLStatusSnapshot } from "../utils/use-snapshot";+import { useWrapAsyncOperation } from "../utils/use-wrap-async";++export const MLSettings: React.FC<NestedSidebarDrawerVisibilityProps> = ({+ open,+ onClose,+ onRootClose,+}) => {+ const mlStatus = useMLStatusSnapshot();+ const [openFaceConsent, setOpenFaceConsent] = useState(false);++ const handleRootClose = () => {+ onClose();+ onRootClose();+ };++ const handleEnableML = () => setOpenFaceConsent(true);++ const handleConsent = useWrapAsyncOperation(async () => {+ await enableML();+ // Close the FaceConsent drawer, come back to ourselves.+ setOpenFaceConsent(false);+ });++ const handleDisableML = useWrapAsyncOperation(disableML);++ let component: React.ReactNode;+ if (!mlStatus) {+ component = <Loading />;+ } else if (mlStatus.phase == "disabled") {+ component = <EnableML onEnable={handleEnableML} showMagicSearchHint />;+ } else {+ component = (+ <ManageML {...{ mlStatus }} onDisableML={handleDisableML} />+ );+ }++ return (+ <>+ <TitledNestedSidebarDrawer+ {...{ open, onClose }}+ onRootClose={handleRootClose}+ title={t("ml_search")}+ >+ {component}+ </TitledNestedSidebarDrawer>++ <FaceConsentDrawer+ open={openFaceConsent}+ onClose={() => setOpenFaceConsent(false)}+ onRootClose={handleRootClose}+ onConsent={handleConsent}+ />+ </>+ );+};++const Loading: React.FC = () => {+ return (+ <Box sx={{ textAlign: "center", pt: 4 }}>+ <ActivityIndicator />+ </Box>+ );+};++interface EnableMLProps {+ /** Called when the user enables ML. */+ onEnable: () => void;+ /**+ * If true, a footnote describing the magic search feature will be shown.+ */+ showMagicSearchHint?: boolean;+}++export const EnableML: React.FC<EnableMLProps> = ({+ onEnable,+ showMagicSearchHint,+}) => {+ const moreDetails = () =>+ openURL("https://ente.io/help/photos/features/machine-learning");++ return (+ <Stack sx={{ gap: "32px", py: "20px", px: 2 }}>+ <Typography sx={{ color: "text.muted" }}>+ {t("ml_search_description")}+ </Typography>+ <Stack sx={{ gap: "8px" }}>+ <Button fullWidth color="accent" onClick={onEnable}>+ {t("enable")}+ </Button>+ <Button fullWidth color="secondary" onClick={moreDetails}>+ {t("more_details")}+ </Button>+ </Stack>+ {showMagicSearchHint && (+ <Typography variant="small" sx={{ color: "text.faint" }}>+ {t("ml_search_footnote")}+ </Typography>+ )}+ </Stack>+ );+};++type FaceConsentDrawerProps = NestedSidebarDrawerVisibilityProps &+ Pick<FaceConsentProps, "onConsent">;++const FaceConsentDrawer: React.FC<FaceConsentDrawerProps> = ({+ open,+ onClose,+ onRootClose,+ onConsent,+}) => {+ const handleRootClose = () => {+ onClose();+ onRootClose();+ };++ return (+ <TitledNestedSidebarDrawer+ {...{ open, onClose }}+ onRootClose={handleRootClose}+ title={t("ml_consent_title")}+ >+ <FaceConsent onConsent={onConsent} onCancel={onClose} />+ </TitledNestedSidebarDrawer>+ );+};++interface FaceConsentProps {+ /** Called when the user provides their consent. */+ onConsent: () => void;+ /** Called when the user cancels out. */+ onCancel: () => void;+}++export const FaceConsent: React.FC<FaceConsentProps> = ({+ onConsent,+ onCancel,+}) => {+ const [acceptTerms, setAcceptTerms] = useState(false);++ useEffect(() => {+ setAcceptTerms(false);+ }, []);++ const privacyPolicyLink = (+ <Link+ target="_blank"+ href="https://ente.io/privacy#8-biometric-information-privacy-policy"+ underline="always"+ sx={{ color: "inherit", textDecorationColor: "inherit" }}+ />+ );++ return (+ <Stack sx={{ gap: "32px", py: "20px", px: "8px" }}>+ <Typography component="div" sx={{ color: "text.muted", px: "8px" }}>+ <Trans+ i18nKey={"ml_consent_description"}+ components={{ a: privacyPolicyLink }}+ />+ </Typography>+ <FormGroup sx={{ width: "100%" }}>+ <FormControlLabel+ sx={{ color: "text.muted", ml: 0, mt: 2 }}+ control={+ <Checkbox+ size="small"+ checked={acceptTerms}+ onChange={(e) => setAcceptTerms(e.target.checked)}+ />+ }+ label={t("ml_consent_confirmation")}+ />+ </FormGroup>+ <Stack sx={{ gap: "8px", px: "8px" }}>+ <FocusVisibleButton+ fullWidth+ color="accent"+ disabled={!acceptTerms}+ onClick={onConsent}+ >+ {t("ml_consent")}+ </FocusVisibleButton>+ <FocusVisibleButton+ fullWidth+ color="secondary"+ onClick={onCancel}+ >+ {t("cancel")}+ </FocusVisibleButton>+ </Stack>+ </Stack>+ );+};++interface ManageMLProps {+ /** The {@link MLStatus}; a non-disabled one. */+ mlStatus: Exclude<MLStatus, { phase: "disabled" }>;+ /** Called when the user wants to disable ML. */+ onDisableML: () => void;+}++const ManageML: React.FC<ManageMLProps> = ({ mlStatus, onDisableML }) => {+ const { showMiniDialog } = useBaseContext();++ const { phase, phaseFailed, nSyncedFiles, nTotalFiles } = mlStatus;++ let status: string;+ switch (phase) {+ case "scheduled":+ status = t("indexing_status_scheduled");+ break;+ case "fetching":+ status = t("indexing_status_fetching");+ break;+ case "indexing":+ status = t("indexing_status_running");+ break;+ case "clustering":+ status = t("people");+ break;+ default:+ status = phaseFailed ? t("error") : t("indexing_status_done");+ break;+ }++ // Show processed as percentages instead of potentially confusing counts.+ const processed = `${nTotalFiles ? Math.round((100 * nSyncedFiles) / nTotalFiles) : 100}%`;++ const confirmDisableML = () =>+ showMiniDialog({+ title: t("ml_search_disable"),+ message: t("ml_search_disable_confirm"),+ continue: {+ text: t("disable"),+ color: "critical",+ action: onDisableML,+ },+ });++ return (+ <Stack sx={{ px: "16px", py: "20px", gap: 4 }}>+ <Stack sx={{ gap: 3 }}>+ <RowButtonGroup>+ <RowSwitch+ label={t("enabled")}+ checked={true}+ onClick={confirmDisableML}+ />+ </RowButtonGroup>+ </Stack>++ <Stack>+ <Stack+ direction="row"+ sx={{+ gap: 2,+ px: 2,+ pt: 1,+ pb: 2,+ justifyContent: "space-between",+ }}+ >+ <Typography sx={{ color: "text.faint" }}>+ {t("indexing")}+ </Typography>+ <Typography>{status}</Typography>+ </Stack>+ <Divider sx={{ mx: 1.5 }} />+ <Stack+ direction="row"+ sx={{+ gap: 2,+ px: 2,+ pt: 2,+ pb: 1,+ justifyContent: "space-between",+ }}+ >+ <Typography sx={{ color: "text.faint" }}>+ {t("processed")}+ </Typography>+ <Typography sx={{ textAlign: "right" }}>+ {processed}+ </Typography>+ </Stack>+ </Stack>+ </Stack>+ );+};diff --git a/web/apps/albums/vendor/ente-new/photos/components/utils/download.tsx b/web/apps/albums/vendor/ente-new/photos/components/utils/download.tsxnew file mode 100644index 0000000000..6648273b81--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/utils/download.tsx@@ -0,0 +1,44 @@+import AutoAwesomeOutlinedIcon from "@mui/icons-material/AutoAwesomeOutlined";+import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";+import { ensureElectron } from "ente-base/electron";+import type { AppUpdate } from "ente-base/types/ipc";+import { openURL } from "ente-new/photos/utils/web";+import { t } from "i18next";++export const downloadAppDialogAttributes = (): MiniDialogAttributes => ({+ title: t("download_app"),+ message: t("download_app_message"),+ continue: { text: t("download"), action: downloadApp },+});++const downloadApp = () => openURL("https://ente.io/download/desktop");++export const updateReadyToInstallDialogAttributes = ({+ version,+}: AppUpdate): MiniDialogAttributes => ({+ title: t("update_available"),+ message: t("update_installable_message"),+ icon: <AutoAwesomeOutlinedIcon />,+ nonClosable: true,+ continue: {+ text: t("install_now"),+ action: () => ensureElectron().updateAndRestart(),+ },+ cancel: {+ text: t("install_on_next_launch"),+ action: () => ensureElectron().updateOnNextRestart(version),+ },+});++export const updateAvailableForDownloadDialogAttributes = ({+ version,+}: AppUpdate): MiniDialogAttributes => ({+ title: t("update_available"),+ message: t("update_available_message"),+ icon: <AutoAwesomeOutlinedIcon />,+ continue: { text: t("download_and_install"), action: downloadApp },+ cancel: {+ text: t("ignore_this_version"),+ action: () => ensureElectron().skipAppUpdate(version),+ },+});diff --git a/web/apps/albums/vendor/ente-new/photos/components/utils/thumbnail-grid-layout.ts b/web/apps/albums/vendor/ente-new/photos/components/utils/thumbnail-grid-layout.tsnew file mode 100644index 0000000000..5ab7f7935e--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/utils/thumbnail-grid-layout.ts@@ -0,0 +1,90 @@+export const thumbnailGap = 4;+export const thumbnailMaxHeight = 180;+export const thumbnailMaxWidth = 180;+export const thumbnailLayoutMinColumns = 4;++export interface ThumbnailGridLayoutParams {+ /**+ * The overall width available to us.+ *+ * This is the height that is the input to the computation, stashed here so+ * that other parts of the code downstream can also get at it if needed.+ */+ containerWidth: number;+ /**+ * `true` if the container width is classified as a smaller screen for the+ * purpose of the thumbnail grid, and some dimensions are reduced to account+ * for the lesser space available to us.+ */+ isSmallerLayout: boolean;+ /**+ * The inline padding (px) of the thumbnail grid.+ */+ paddingInline: number;+ /**+ * The number of columns in the thumbnail grid.+ */+ columns: number;+ /**+ * The width (px) of each item.+ */+ itemWidth: number;+ /**+ * The height (px) of each item.+ */+ itemHeight: number;+ /**+ * The gap (px) between each grid item.+ */+ gap: number;+}++/**+ * Determine the layout parameters for a grid of thumbnails that would best fit+ * the given width under various constraints.+ *+ * @param containerWidth The width available to the container. In our case,+ * since the thumbnail grids span the entire available width, this is the width+ * of the page itself.+ */+export const computeThumbnailGridLayoutParams = (+ containerWidth: number,+): ThumbnailGridLayoutParams => {+ const isSmallerLayout = !(+ containerWidth >+ thumbnailLayoutMinColumns * thumbnailMaxWidth+ );+ const paddingInline = getGapFromScreenEdge(containerWidth);+ const fittableColumns = getFractionFittableColumns(containerWidth);++ let columns = Math.floor(fittableColumns);+ if (columns < thumbnailLayoutMinColumns) {+ columns = thumbnailLayoutMinColumns;+ }++ const shrinkRatio = getShrinkRatio(containerWidth, columns);+ const itemHeight = thumbnailMaxHeight * shrinkRatio;+ const itemWidth = thumbnailMaxWidth * shrinkRatio;+ const gap = thumbnailGap;++ return {+ containerWidth,+ isSmallerLayout,+ paddingInline,+ columns,+ itemWidth,+ itemHeight,+ gap,+ };+};++const getFractionFittableColumns = (width: number): number =>+ (width - 2 * getGapFromScreenEdge(width) + thumbnailGap) /+ (thumbnailMaxWidth + thumbnailGap);++const getGapFromScreenEdge = (width: number) =>+ width > thumbnailLayoutMinColumns * thumbnailMaxWidth ? 24 : 4;++const getShrinkRatio = (width: number, columns: number) =>+ (width - 2 * getGapFromScreenEdge(width) - (columns - 1) * thumbnailGap) /+ (columns * thumbnailMaxWidth);diff --git a/web/apps/albums/vendor/ente-new/photos/components/utils/use-loading-bar.ts b/web/apps/albums/vendor/ente-new/photos/components/utils/use-loading-bar.tsnew file mode 100644index 0000000000..c5c7152fed--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/utils/use-loading-bar.ts@@ -0,0 +1,26 @@+import { useCallback, useRef } from "react";+import { type LoadingBarRef } from "react-top-loading-bar";++/**+ * A convenience hook for returning stable functions tied to a+ * {@link LoadingBar} ref.+ *+ * The {@link LoadingBar} component comes from the "react-top-loading-bar"+ * library. To control it, we keep a ref. We want to allow components in our+ * React tree to be able to also control the loading bar, but instead of+ * exposing the ref directly, we export wrapper functions to start and stop the+ * loading bar. This hook returns these functions (and the ref).+ */+export const useLoadingBar = () => {+ const loadingBarRef = useRef<LoadingBarRef | null>(null);++ const showLoadingBar = useCallback(() => {+ loadingBarRef.current?.continuousStart();+ }, []);++ const hideLoadingBar = useCallback(() => {+ loadingBarRef.current?.complete();+ }, []);++ return { loadingBarRef, showLoadingBar, hideLoadingBar };+};diff --git a/web/apps/albums/vendor/ente-new/photos/components/utils/use-snapshot.ts b/web/apps/albums/vendor/ente-new/photos/components/utils/use-snapshot.tsnew file mode 100644index 0000000000..0b76c01b3a--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/utils/use-snapshot.ts@@ -0,0 +1,62 @@+import {+ hlsGenerationStatusSnapshot,+ hlsGenerationStatusSubscribe,+} from "ente-gallery/services/video";+import { useSyncExternalStore } from "react";+import { appLockSnapshot, appLockSubscribe } from "../../services/app-lock";+import {+ mlStatusSnapshot,+ mlStatusSubscribe,+ peopleStateSnapshot,+ peopleStateSubscribe,+} from "../../services/ml";+import { settingsSnapshot, settingsSubscribe } from "../../services/settings";+import {+ userDetailsSnapshot,+ userDetailsSubscribe,+} from "../../services/user-details";++/**+ * A convenience hook that returns {@link appLockSnapshot}, and also subscribes+ * to updates.+ */+export const useAppLockSnapshot = () =>+ useSyncExternalStore(appLockSubscribe, appLockSnapshot, appLockSnapshot);++/**+ * A convenience hook that returns {@link settingsSnapshot}, and also+ * subscribes to updates.+ */+export const useSettingsSnapshot = () =>+ useSyncExternalStore(settingsSubscribe, settingsSnapshot);++/**+ * A convenience hook that returns {@link userDetailsSnapshot}, and also+ * subscribes to updates.+ */+export const useUserDetailsSnapshot = () =>+ useSyncExternalStore(userDetailsSubscribe, userDetailsSnapshot);++/**+ * A convenience hook that returns {@link mlStatusSnapshot}, and also subscribes+ * to updates.+ */+export const useMLStatusSnapshot = () =>+ useSyncExternalStore(mlStatusSubscribe, mlStatusSnapshot);++/**+ * A convenience hook that returns {@link peopleStateSnapshot}, and also+ * subscribes to updates.+ */+export const usePeopleStateSnapshot = () =>+ useSyncExternalStore(peopleStateSubscribe, peopleStateSnapshot);++/**+ * A convenience hook that returns {@link hlsGenerationStatusSnapshot}, and also+ * subscribes to updates.+ */+export const useHLSGenerationStatusSnapshot = () =>+ useSyncExternalStore(+ hlsGenerationStatusSubscribe,+ hlsGenerationStatusSnapshot,+ );diff --git a/web/apps/albums/vendor/ente-new/photos/components/utils/use-wrap-async.ts b/web/apps/albums/vendor/ente-new/photos/components/utils/use-wrap-async.tsnew file mode 100644index 0000000000..ebae892663--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/components/utils/use-wrap-async.ts@@ -0,0 +1,38 @@+import { useBaseContext } from "ente-base/context";+import { useCallback } from "react";+import { usePhotosAppContext } from "../../types/context";++/**+ * Wrap a function returning a promise in a loading bar and error handler.+ *+ * This function wraps asynchronous operations (e.g. API calls) in an global+ * activity indicator and error handler. The global activity indicator and error+ * alert triggering mechanism is obtained from the app context.+ *+ * Specifically, this function takes an async function. It starts the global+ * activity indicator (using {@link showLoadingBar}), performs the operation,+ * and stops the activity indicator on completion (using+ * {@link hideLoadingBar}).+ *+ * If the operation throws, it shows a generic error (using+ * {@link onGenericError}).+ */+export const useWrapAsyncOperation = <T extends unknown[]>(+ f: (...args: T) => Promise<void>,+) => {+ const { onGenericError } = useBaseContext();+ const { showLoadingBar, hideLoadingBar } = usePhotosAppContext();+ return useCallback(+ async (...args: T) => {+ showLoadingBar();+ try {+ await f(...args);+ } catch (e) {+ onGenericError(e);+ } finally {+ hideLoadingBar();+ }+ },+ [f, showLoadingBar, hideLoadingBar, onGenericError],+ );+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/app-lock.ts b/web/apps/albums/vendor/ente-new/photos/services/app-lock.tsnew file mode 100644index 0000000000..35cbceadc8--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/app-lock.ts@@ -0,0 +1,1088 @@+/**+ * @file Service for the app lock feature.+ *+ * App lock is a purely client-side feature that prevents unauthorized access to+ * the app after it has been authenticated. It supports PIN, password, and+ * local native device lock (macOS Touch ID), and uses Argon2id for passphrase+ * hashing.+ *+ * See: [Note: Snapshots and useSyncExternalStore].+ */++import { deriveInteractiveKey, deriveKey } from "ente-base/crypto";+import {+ clearMainWindowBlurSuppression,+ shouldSuppressMainWindowBlur,+ suppressMainWindowBlurForTrustedPrompt,+} from "ente-base/electron";+import { getKVN, getKVS, removeKV, setKV } from "ente-base/kv";+import log from "ente-base/log";+import { haveMasterKeyInSession } from "ente-base/session";+import type {+ NativeDeviceLockCapability,+ NativeDeviceLockUnavailableReason,+ PersistedAppLockConfig,+} from "ente-base/types/ipc";++/**+ * In-memory state for the app lock feature.+ *+ * Desktop config is persisted only in Electron safe storage, while passphrase+ * and brute-force state live in IndexedDB via KV DB.+ */+export interface AppLockState {+ /** Whether app lock is supported in the current desktop environment. */+ supported: boolean;+ /** Whether app lock is enabled. */+ enabled: boolean;+ /** Active lock type. */+ lockType: "pin" | "password" | "device" | "none";+ /** Why the lock screen is currently shown. */+ lockScreenMode: "lock" | "reauthenticate";+ /** Whether the app is currently locked. */+ isLocked: boolean;+ /** Consecutive failed attempts in current lockout cycle. */+ invalidAttemptCount: number;+ /** Epoch ms when cooldown expires (0 = no cooldown). */+ cooldownExpiresAt: number;+ /** Auto-lock delay in milliseconds. */+ autoLockTimeMs: number;+}++const createDefaultState = (): AppLockState => ({+ supported: false,+ enabled: false,+ lockType: "none",+ lockScreenMode: "lock",+ isLocked: false,+ invalidAttemptCount: 0,+ cooldownExpiresAt: 0,+ autoLockTimeMs: 0,+});++/**+ * Internal in-memory state shared by the functions in this module.+ *+ * This entire object will be reset on logout.+ */+class AppLockModuleState {+ constructor() {+ this.snapshot = createDefaultState();+ }++ /**+ * Subscriptions to {@link AppLockState} updates attached using+ * {@link appLockSubscribe}.+ */+ listeners: (() => void)[] = [];++ /**+ * Snapshot of the {@link AppLockState} returned by+ * {@link appLockSnapshot}.+ */+ snapshot: AppLockState;+}++/** State shared by the functions in this module. */+let _state: AppLockModuleState | undefined;+let _bruteForceStateHydration = Promise.resolve();+let _bruteForceStateHydrationGeneration = 0;+let _wasReauthenticationCancelled = false;++const appLockState = () => {+ _state ??= new AppLockModuleState();+ return _state;+};++/**+ * Subscribe to updates to {@link AppLockState}.+ *+ * The callback is invoked whenever {@link setSnapshot} updates+ * {@link _state.snapshot}. Returns an unsubscribe function that removes the+ * callback from the listener list.+ *+ * See: [Note: Snapshots and useSyncExternalStore].+ */+export const appLockSubscribe = (onChange: () => void): (() => void) => {+ const state = appLockState();+ state.listeners.push(onChange);+ return () => {+ state.listeners = state.listeners.filter((l) => l != onChange);+ };+};++/**+ * Return the last known, cached {@link AppLockState}.+ *+ * See also {@link appLockSubscribe}.+ */+export const appLockSnapshot = () => appLockState().snapshot;++/**+ * Update the internal app lock state snapshot and notify all subscribers.+ *+ * This is the single source of truth for state updates. All modifications to+ * _state.snapshot must go through this function to ensure subscribers are+ * properly notified of changes.+ *+ * See: [Note: Snapshots and useSyncExternalStore].+ */+const setSnapshot = (snapshot: AppLockState) => {+ const state = appLockState();+ state.snapshot = snapshot;+ state.listeners.forEach((l) => {+ l();+ });+};++const ssKeySuppressNextSessionRefreshLock =+ "appLock.suppressNextSessionRefreshLock";++// -- KV DB keys (IndexedDB, async) --++const kvKeyHash = "appLock.hash";+const kvKeySalt = "appLock.salt";+const kvKeyOpsLimit = "appLock.opsLimit";+const kvKeyMemLimit = "appLock.memLimit";+const kvKeyInvalidAttempts = "appLock.invalidAttempts";+const kvKeyCooldownExpiresAt = "appLock.cooldownExpiresAt";++// -- Device lock constants --++const deviceLockEnablePromptReason = "enable device lock";+const deviceLockUnlockPromptReason = "unlock";+const maxInvalidUnlockAttempts = 10;+const cooldownStartsAtAttempt = 5;+const cooldownBaseSeconds = 30;+const unlockAttemptLockName = "ente-app-lock-unlock-attempt";+const trustedPromptAutoLockSuppressionMs = 5 * 1e3;++/**+ * Temporarily suppress auto-lock on blur for trusted app-initiated prompts.+ *+ * This is used for native device authentication prompts that can transiently+ * blur the app window even though the user hasn't backgrounded the app.+ */+export const suppressAutoLockOnBlurForTrustedPrompt = () => {+ suppressMainWindowBlurForTrustedPrompt(trustedPromptAutoLockSuppressionMs);+};++/**+ * Return true if blur-triggered auto-lock should currently be suppressed.+ */+export const shouldSuppressAutoLockOnBlur = () =>+ shouldSuppressMainWindowBlur();++/**+ * Clear any pending blur auto-lock suppression.+ */+export const clearAutoLockBlurSuppression = () => {+ clearMainWindowBlurSuppression();+};++/**+ * Suppress one app-lock refresh cycle after a trusted app-initiated reload.+ */+export const suppressAppLockRefreshFromSessionForTrustedReload = () => {+ try {+ if (!appLockSnapshot().enabled) return;+ sessionStorage.setItem(ssKeySuppressNextSessionRefreshLock, "true");+ } catch {+ // Ignore storage write errors; fallback to regular app-lock behavior.+ }+};++const consumeAppLockRefreshSuppressionFromSession = () => {+ try {+ if (+ sessionStorage.getItem(ssKeySuppressNextSessionRefreshLock) !==+ "true"+ ) {+ return false;+ }++ sessionStorage.removeItem(ssKeySuppressNextSessionRefreshLock);+ return true;+ } catch {+ // Ignore storage read errors; fallback to regular app-lock behavior.+ return false;+ }+};++export type DeviceLockMode = "native";++export type DeviceLockFailureReason = "native-prompt-failed" | "unknown";++const logDeviceLockEvent = (+ phase: "setup" | "unlock",+ status: "not-supported" | "failed",+ reason: NativeDeviceLockUnavailableReason | DeviceLockFailureReason,+ error?: unknown,+) => {+ const message =+ status === "not-supported"+ ? `Device lock ${phase} is not supported`+ : `Device lock ${phase} failed`;++ if (typeof error != "undefined") {+ log.warn(message, { reason, error });+ return;+ }++ log.warn(message, { reason });+};++/**+ * Return the cooldown duration for a failed-attempt count.+ *+ * This policy is shared by lockout enforcement and cooldown UI (used by the+ * app lock screen to render countdown progress).+ */+export const appLockCooldownDurationMs = (attemptCount: number): number => {+ if (attemptCount < cooldownStartsAtAttempt) return 0;+ return (+ Math.pow(2, attemptCount - cooldownStartsAtAttempt) *+ cooldownBaseSeconds *+ 1000+ );+};++const setBruteForceSnapshot = (+ invalidAttemptCount: number,+ cooldownExpiresAt: number,+) => {+ const snapshot = appLockState().snapshot;+ if (+ snapshot.invalidAttemptCount !== invalidAttemptCount ||+ snapshot.cooldownExpiresAt !== cooldownExpiresAt+ ) {+ setSnapshot({ ...snapshot, invalidAttemptCount, cooldownExpiresAt });+ }+};++const readBruteForceStateFromKV = async () => {+ const [invalidAttempts, cooldownExpiry] = await Promise.all([+ getKVN(kvKeyInvalidAttempts),+ getKVN(kvKeyCooldownExpiresAt),+ ]);++ return {+ invalidAttemptCount: clampNonNegativeInt(Number(invalidAttempts ?? 0)),+ cooldownExpiresAt: clampNonNegativeInt(Number(cooldownExpiry ?? 0)),+ };+};++/**+ *+ * @param value the autoLockTimeMS+ * @returns clampedNonNegativeFinite integer value+ *+ * So this function is bascially a normalization function, to update the+ * value of the autoLockTimeMs in case it becomes any non-negative/non-finite+ * number like -4 or NaN in-case of some corruption or unexpected case.+ */+const clampNonNegativeInt = (value: number) =>+ Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;++const defaultPersistedAppLockConfig = (): PersistedAppLockConfig => ({+ enabled: false,+ lockType: "none",+ autoLockTimeMs: 0,+});++/**+ * Validates and retrieves the Electron app lock API from the global scope.+ *+ * Checks if the Electron API is available and has all required app lock+ * related functions before returning it. This ensures safe access to+ * Electron's secure storage capabilities for app lock configuration.+ *+ * @returns {Object | undefined} The Electron API object with app lock methods+ * if all required functions are available,+ * otherwise undefined.+ */+const appLockElectron = () => {+ const electron = globalThis.electron;+ if (+ !electron ||+ typeof electron.isSafeStorageAvailable != "function" ||+ typeof electron.appLockConfigFromSafeStorage != "function" ||+ typeof electron.saveAppLockConfigInSafeStorage != "function" ||+ typeof electron.clearAppLockConfigFromSafeStorage != "function"+ ) {+ return undefined;+ }++ return electron;+};++const isAppLockSupported = async () => {+ const electron = appLockElectron();+ if (!electron) return false;++ try {+ return await electron.isSafeStorageAvailable();+ } catch (e) {+ log.warn("Failed to query safe storage support for app lock", e);+ return false;+ }+};++const readPersistedAppLockConfig =+ async (): Promise<PersistedAppLockConfig> => {+ const electron = appLockElectron();+ if (!electron) {+ throw new Error("App lock is not supported");+ }++ const persistedConfig = await electron.appLockConfigFromSafeStorage();+ if (!persistedConfig) {+ return defaultPersistedAppLockConfig();+ }++ return {+ enabled: persistedConfig.enabled,+ lockType: persistedConfig.lockType,+ autoLockTimeMs: clampNonNegativeInt(persistedConfig.autoLockTimeMs),+ };+ };++const savePersistedAppLockConfig = async (config: PersistedAppLockConfig) => {+ const electron = appLockElectron();+ if (!electron || !(await isAppLockSupported())) {+ throw new Error("App lock is not supported");+ }++ await electron.saveAppLockConfigInSafeStorage({+ enabled: config.enabled,+ lockType: config.lockType,+ autoLockTimeMs: clampNonNegativeInt(config.autoLockTimeMs),+ });+};++const clearPersistedAppLockConfig = async () => {+ const electron = appLockElectron();+ if (!electron) {+ throw new Error("App lock is not supported");+ }++ await electron.clearAppLockConfigFromSafeStorage();+};++/**+ * Update in-memory app-lock state from persisted config.+ *+ * Used during `initAppLock` (cold start) and+ * `refreshAppLockStateFromSession` (after session restore).+ */+const setSnapshotFromPersistedConfig = (+ config: PersistedAppLockConfig,+ isLocked: boolean,+ supported = true,+) => {+ const snapshot = appLockState().snapshot;+ setSnapshot({+ ...snapshot,+ supported,+ enabled: config.enabled,+ lockType: config.lockType,+ lockScreenMode: "lock",+ isLocked,+ autoLockTimeMs: config.autoLockTimeMs,+ });+ hydrateBruteForceStateIfNeeded();+};++let _localUnlockAttemptQueue = Promise.resolve();++/**+ * Serialize unlock attempts within the current tab.+ *+ * This fallback mutex is used when the Web Locks API is unavailable.+ */+const withLocalUnlockAttemptLock = async <T>(fn: () => Promise<T>) => {+ const previous = _localUnlockAttemptQueue;+ let releaseCurrent: (() => void) | undefined;++ _localUnlockAttemptQueue = new Promise<void>((resolve) => {+ releaseCurrent = resolve;+ });++ await previous;+ try {+ return await fn();+ } finally {+ releaseCurrent?.();+ }+};++/**+ * Serialize unlock attempts across tabs when possible.+ *+ * Uses the Web Locks API for cross-tab mutual exclusion, and falls back to+ * {@link withLocalUnlockAttemptLock} when unavailable.+ */+const withUnlockAttemptLock = async <T>(fn: () => Promise<T>) => {+ const locks =+ typeof navigator == "undefined"+ ? undefined+ : (navigator as Navigator & { locks?: LockManager }).locks;++ if (locks && typeof locks.request == "function") {+ const result: unknown = await locks.request(+ unlockAttemptLockName,+ { mode: "exclusive" },+ fn,+ );+ return result as T;+ }++ return withLocalUnlockAttemptLock(fn);+};++// -- Public API --++/**+ * Initialize app lock state from persistent storage on cold start.+ *+ * On desktop, this restores the config from Electron safe storage before+ * gating rendering, then locks pessimistically while session hydration is in+ * flight.+ *+ * After the initial snapshot, asynchronously restores the brute-force+ * attempt count and cooldown expiry from KV DB so that a page refresh cannot+ * bypass the cooldown.+ */+export const initAppLock = async () => {+ if (!(await isAppLockSupported())) {+ setSnapshot(createDefaultState());+ stopBruteForceStateHydration();+ return;+ }++ const config = await readPersistedAppLockConfig();+ const hasSession = haveMasterKeyInSession();++ // On desktop, lock pessimistically while safe-storage hydration is in flight.+ const isLocked = config.enabled && (hasSession || !!globalThis.electron);++ setSnapshotFromPersistedConfig(config, isLocked, true);+};++/**+ * Restore the brute-force attempt count and cooldown expiry from KV DB into+ * the in-memory snapshot.+ *+ * Called during {@link initAppLock} to ensure that cooldown timers persist+ * across page refreshes.+ */+const restoreBruteForceState = async (generation: number) => {+ try {+ const { invalidAttemptCount, cooldownExpiresAt } =+ await readBruteForceStateFromKV();++ if (generation !== _bruteForceStateHydrationGeneration) {+ return;+ }++ setBruteForceSnapshot(invalidAttemptCount, cooldownExpiresAt);+ } catch (e) {+ log.error("Failed to restore brute-force state from KV DB", e);+ }+};++const stopBruteForceStateHydration = () => {+ _bruteForceStateHydrationGeneration += 1;+ _bruteForceStateHydration = Promise.resolve();+};++const hydrateBruteForceStateIfNeeded = () => {+ const snapshot = appLockState().snapshot;+ const isPassphraseLock =+ snapshot.lockType === "pin" || snapshot.lockType === "password";+ if (!snapshot.isLocked || !isPassphraseLock) {+ stopBruteForceStateHydration();+ return;+ }++ const generation = ++_bruteForceStateHydrationGeneration;+ _bruteForceStateHydration = restoreBruteForceState(generation);+};++const ensureBruteForceStateHydrated = async () => {+ await _bruteForceStateHydration;+};++const unsupportedNativeDeviceLockCapability: NativeDeviceLockCapability = {+ available: false,+ provider: "none",+ reason: "unsupported-platform",+};++const nativeDeviceLockCapability =+ async (): Promise<NativeDeviceLockCapability> => {+ // Native device lock is available only in the desktop (Electron) app.+ // On web, we always treat it as unsupported.+ if (!globalThis.electron) return unsupportedNativeDeviceLockCapability;++ try {+ if (+ typeof globalThis.electron.getNativeDeviceLockCapability ==+ "function"+ ) {+ return await globalThis.electron.getNativeDeviceLockCapability();+ }++ return unsupportedNativeDeviceLockCapability;+ } catch (e) {+ log.warn("Failed to query native device lock support", e);+ return unsupportedNativeDeviceLockCapability;+ }+ };++type DeviceLockCapability =+ | { usable: true; mode: DeviceLockMode }+ | { usable: false; reason: NativeDeviceLockUnavailableReason };++const nativeCapabilityUnavailableReason = (+ capability: NativeDeviceLockCapability,+): NativeDeviceLockUnavailableReason => {+ switch (capability.reason) {+ case "touchid-not-enrolled":+ case "touchid-temporarily-unavailable":+ case "touchid-api-error":+ return capability.reason;+ default:+ return "unsupported-platform";+ }+};++const resolveDeviceLockCapability = async (): Promise<DeviceLockCapability> => {+ const nativeCapability = await nativeDeviceLockCapability();+ if (nativeCapability.available) return { usable: true, mode: "native" };++ const reason = nativeCapabilityUnavailableReason(nativeCapability);+ if (reason === "touchid-temporarily-unavailable") {+ // Keep unlock/setup retryable on macOS even when capability checks are+ // briefly inconclusive.+ return { usable: true, mode: "native" };+ }++ return { usable: false, reason };+};++/**+ * Return true if the current environment should show "Device lock" in the+ * lock-type picker.+ *+ * We show it when native auth is currently available, or when the platform+ * supports it but setup/auth is temporarily unavailable (for example, Touch ID+ * not enrolled).+ */+export const shouldShowDeviceLockOption = async () => {+ if (!appLockSnapshot().supported) return false;++ const capability = await nativeDeviceLockCapability();+ if (capability.available) return true;++ return (+ nativeCapabilityUnavailableReason(capability) !== "unsupported-platform"+ );+};++const clearPassphraseMaterial = async () =>+ Promise.all([+ removeKV(kvKeyHash),+ removeKV(kvKeySalt),+ removeKV(kvKeyOpsLimit),+ removeKV(kvKeyMemLimit),+ ]);++/**+ * Reset brute-force protection state.+ *+ * Clears persisted invalid-attempt and cooldown values in KV and updates the+ * in-memory snapshot to zero.+ */+const resetBruteForceState = async () => {+ await Promise.all([+ setKV(kvKeyInvalidAttempts, 0),+ setKV(kvKeyCooldownExpiresAt, 0),+ ]);+ setBruteForceSnapshot(0, 0);+};++const unlockLocally = () => {+ const snapshot = appLockState().snapshot;+ const wasReauthentication = snapshot.lockScreenMode === "reauthenticate";+ setSnapshot({+ ...snapshot,+ lockScreenMode: "lock",+ isLocked: false,+ invalidAttemptCount: 0,+ cooldownExpiresAt: 0,+ });+ if (wasReauthentication) {+ _wasReauthenticationCancelled = false;+ }+ stopBruteForceStateHydration();+};++/**+ * Cancel an in-progress explicit reauthentication prompt.+ *+ * This only dismisses the reauthentication lock screen, allowing callers of+ * {@link reauthenticateWithAppLock} to fall back to alternate auth flows.+ */+export const cancelReauthentication = () => {+ const snapshot = appLockState().snapshot;+ if (!snapshot.isLocked || snapshot.lockScreenMode !== "reauthenticate") {+ return;+ }++ _wasReauthenticationCancelled = true;+ setSnapshot({ ...snapshot, lockScreenMode: "lock", isLocked: false });+ stopBruteForceStateHydration();+};++/**+ * Recompute and refresh whether the app should currently be locked based on+ * session availability.+ *+ * Call this after desktop safe-storage restore to prevent auto-login bypass.+ */+export const refreshAppLockStateFromSession = async () => {+ if (!(await isAppLockSupported())) {+ setSnapshot(createDefaultState());+ stopBruteForceStateHydration();+ return;+ }++ const config = await readPersistedAppLockConfig();+ const shouldSuppressLockForTrustedReload =+ consumeAppLockRefreshSuppressionFromSession();+ const isLocked =+ config.enabled &&+ haveMasterKeyInSession() &&+ !shouldSuppressLockForTrustedReload;+ setSnapshotFromPersistedConfig(config, isLocked, true);+};++/**+ * The result of a device lock setup attempt.+ *+ * - `success` - Device lock setup completed and app lock configured.+ * - `not-supported` - Platform authenticator is unavailable in this context.+ * - `failed` - Setup failed or was cancelled by the user.+ */+export type SetupDeviceLockResult =+ | { status: "success"; mode: DeviceLockMode }+ | { status: "not-supported"; reason: NativeDeviceLockUnavailableReason }+ | { status: "failed"; reason: DeviceLockFailureReason };++/**+ * Set up a PIN for app lock.+ *+ * Derives a key from the PIN using Argon2id with interactive limits, stores+ * the hash and derivation parameters in KV DB, and enables the lock.+ */+const setupPassphraseLock = async (+ lockType: Extract<AppLockState["lockType"], "pin" | "password">,+ input: string,+) => {+ if (!(await isAppLockSupported())) {+ throw new Error("App lock is not supported");+ }++ const derived = await deriveInteractiveKey(input);+ await Promise.all([+ setKV(kvKeyHash, derived.key),+ setKV(kvKeySalt, derived.salt),+ setKV(kvKeyOpsLimit, derived.opsLimit),+ setKV(kvKeyMemLimit, derived.memLimit),+ resetBruteForceState(),+ ]);++ const snapshot = appLockState().snapshot;+ await savePersistedAppLockConfig({+ enabled: true,+ lockType,+ autoLockTimeMs: snapshot.autoLockTimeMs,+ });+ setSnapshot({+ ...snapshot,+ enabled: true,+ lockType,+ invalidAttemptCount: 0,+ cooldownExpiresAt: 0,+ });+ stopBruteForceStateHydration();+};++export const setupPin = async (pin: string) => setupPassphraseLock("pin", pin);++/**+ * Set up a password for app lock.+ *+ * Same as {@link setupPin} but sets the lock type to "password".+ */+export const setupPassword = async (password: string) =>+ setupPassphraseLock("password", password);++/**+ * Set up native device lock authentication for app lock (macOS only).+ */+export const setupDeviceLock = async (): Promise<SetupDeviceLockResult> => {+ if (!(await isAppLockSupported())) {+ return { status: "failed", reason: "unknown" };+ }++ // Resolve whether native device lock is currently usable in this environment.+ // Flow: resolveDeviceLockCapability() -> nativeDeviceLockCapability() ->+ // globalThis.electron.getNativeDeviceLockCapability().+ const capability = await resolveDeviceLockCapability();++ // Surface unsupported reasons to callers/UI.+ if (!capability.usable) {+ logDeviceLockEvent("setup", "not-supported", capability.reason);+ return { status: "not-supported", reason: capability.reason };+ }++ try {+ // Ignore blur auto-lock caused by this trusted, app-initiated native+ // prompt.+ suppressAutoLockOnBlurForTrustedPrompt();++ // Trigger the OS-native authentication prompt (for example, Touch ID).+ const unlocked = await globalThis.electron?.promptDeviceLock(+ deviceLockEnablePromptReason,+ );+ if (!unlocked) {+ logDeviceLockEvent("setup", "failed", "native-prompt-failed");+ return { status: "failed", reason: "native-prompt-failed" };+ }++ // Reset brute-force lockout/cooldown state in KV and in memory.+ await resetBruteForceState();++ // Update the in-memory app-lock snapshot.+ const snapshot = appLockState().snapshot;+ await savePersistedAppLockConfig({+ enabled: true,+ lockType: "device",+ autoLockTimeMs: snapshot.autoLockTimeMs,+ });+ setSnapshot({+ ...snapshot,+ enabled: true,+ lockType: "device",+ invalidAttemptCount: 0,+ cooldownExpiresAt: 0,+ });++ // Stop ongoing brute-force hydration.+ stopBruteForceStateHydration();++ return { status: "success", mode: "native" };+ } catch (e) {+ log.error("Failed to set up device lock app lock", e);+ return { status: "failed", reason: "unknown" };+ }+};++/**+ * The result of an unlock attempt.+ *+ * - `"success"` - The input was correct; the app is now unlocked.+ * - `"failed"` - The input was incorrect.+ * - `"cooldown"` - Too many recent attempts; currently in cooldown.+ * - `"logout"` - Too many total attempts (>= 10); caller should force logout.+ */+export type UnlockResult = "success" | "failed" | "cooldown" | "logout";++/**+ * The result of a device lock unlock attempt.+ */+export type DeviceLockUnlockResult =+ | { status: "success"; mode: DeviceLockMode }+ | { status: "not-supported"; reason: NativeDeviceLockUnavailableReason }+ | { status: "failed"; reason: DeviceLockFailureReason };++/**+ * Attempt to unlock the app using native device lock (macOS only).+ */+export const attemptDeviceLockUnlock =+ async (): Promise<DeviceLockUnlockResult> => {+ const capability = await resolveDeviceLockCapability();+ if (!capability.usable) {+ logDeviceLockEvent("unlock", "not-supported", capability.reason);+ return { status: "not-supported", reason: capability.reason };+ }++ try {+ const unlocked = await globalThis.electron?.promptDeviceLock(+ deviceLockUnlockPromptReason,+ );+ if (!unlocked) {+ logDeviceLockEvent("unlock", "failed", "native-prompt-failed");+ return { status: "failed", reason: "native-prompt-failed" };+ }++ await resetBruteForceState();+ unlockLocally();+ return { status: "success", mode: "native" };+ } catch (e) {+ log.error("Failed device lock unlock attempt", e);+ return { status: "failed", reason: "unknown" };+ }+ };++/**+ * Attempt to unlock the app with the given PIN or password.+ *+ * Implements brute-force protection: after 5 failed attempts, a cooldown+ * period is enforced (exponential backoff starting at 30s). After 10 failed+ * attempts, signals that the caller should force-logout the user.+ */+export const attemptUnlock = async (input: string): Promise<UnlockResult> => {+ /**+ * This flow applies only to PIN and password locks.+ * Guard against being called for any other lock type.+ */+ const snapshot = appLockState().snapshot;+ const isPassphraseLock =+ snapshot.lockType === "pin" || snapshot.lockType === "password";+ if (!isPassphraseLock) {+ return "failed";+ }++ return withUnlockAttemptLock<UnlockResult>(async () => {+ // Ensure persisted lockout state has been rehydrated before enforcing.+ await ensureBruteForceStateHydrated();++ /**+ * Refresh lockout state from KV so stale tabs cannot reset counters.+ *+ * If multiple tabs attempt to unlock at the same time, sync from KV DB+ * before validation so all tabs use the latest attempt/cooldown state.+ */+ const persistedState = await readBruteForceStateFromKV();+ const latestSnapshot = appLockState().snapshot;+ const invalidAttemptCount = Math.max(+ latestSnapshot.invalidAttemptCount,+ persistedState.invalidAttemptCount,+ );+ const cooldownExpiresAt = Math.max(+ latestSnapshot.cooldownExpiresAt,+ persistedState.cooldownExpiresAt,+ );++ // Update the snapshot with the latest values.+ setBruteForceSnapshot(invalidAttemptCount, cooldownExpiresAt);++ if (invalidAttemptCount >= maxInvalidUnlockAttempts) {+ await setKV(kvKeyCooldownExpiresAt, 0);+ setBruteForceSnapshot(invalidAttemptCount, 0);+ return "logout";+ }++ // Check cooldown from in-memory state.+ const snapshotWithCooldown = appLockState().snapshot;+ if (+ snapshotWithCooldown.cooldownExpiresAt > 0 &&+ Date.now() < snapshotWithCooldown.cooldownExpiresAt+ ) {+ return "cooldown";+ }++ // Read stored derivation parameters and hash from KV DB.+ const salt = await getKVS(kvKeySalt);+ const storedHash = await getKVS(kvKeyHash);+ const opsLimit = await getKVN(kvKeyOpsLimit);+ const memLimit = await getKVN(kvKeyMemLimit);++ if (!salt || !storedHash || !opsLimit || !memLimit) {+ log.error("App lock credentials missing from KV DB");+ return "failed";+ }++ // Derive key from input using the stored parameters.+ const derivedKey = await deriveKey(input, salt, opsLimit, memLimit);++ if (derivedKey === storedHash) {+ // Correct input: reset attempts, unlock.+ await resetBruteForceState();+ unlockLocally();+ return "success";+ }++ // Incorrect input: increment attempts.+ const count = invalidAttemptCount + 1;+ await setKV(kvKeyInvalidAttempts, count);++ if (count >= maxInvalidUnlockAttempts) {+ // Too many attempts: signal logout.+ await setKV(kvKeyCooldownExpiresAt, 0);+ setBruteForceSnapshot(count, 0);+ return "logout";+ }++ if (count >= cooldownStartsAtAttempt) {+ // Enforce cooldown with exponential backoff.+ const expiresAt = Date.now() + appLockCooldownDurationMs(count);+ await setKV(kvKeyCooldownExpiresAt, expiresAt);+ setBruteForceSnapshot(count, expiresAt);++ // The current failed attempt has triggered cooldown, so surface the+ // cooldown state immediately to callers/UI.+ return "cooldown";+ } else {+ setBruteForceSnapshot(count, 0);+ }++ return "failed";+ });+};++/**+ * Perform an explicit reauthentication using app lock.+ *+ * - `"authenticated"` when app lock reauthentication succeeds.+ * - `"cancelled"` when the user dismisses the reauthentication prompt.+ * - `"fallback"` when app lock is unavailable or cannot be started, so callers+ * can use an alternate auth flow (for example, master password prompt).+ */+export type ReauthenticateWithAppLockResult =+ | "authenticated"+ | "cancelled"+ | "fallback";++export const reauthenticateWithAppLock =+ async (): Promise<ReauthenticateWithAppLockResult> => {+ try {+ _wasReauthenticationCancelled = false;+ const snapshot = appLockSnapshot();+ let canUseAppLock =+ snapshot.enabled && snapshot.lockType !== "none";+ if (canUseAppLock && snapshot.lockType === "device") {+ // For device lock, ensure native auth is actually usable right now.+ // If unavailable (e.g. Touch ID disabled), fall back to password flow.+ const capability = await resolveDeviceLockCapability();+ canUseAppLock = capability.usable;+ }+ if (!canUseAppLock) return "fallback";++ return await new Promise<ReauthenticateWithAppLockResult>(+ (resolve) => {+ const unsubscribe = appLockSubscribe(() => {+ if (!appLockSnapshot().isLocked) {+ unsubscribe();+ const wasAuthenticated =+ !_wasReauthenticationCancelled;+ _wasReauthenticationCancelled = false;+ resolve(+ wasAuthenticated+ ? "authenticated"+ : "cancelled",+ );+ }+ });++ lock("reauthenticate");+ if (!appLockSnapshot().isLocked) {+ unsubscribe();+ resolve("fallback");+ }+ },+ );+ } catch (e) {+ log.error("Failed to start app lock reauthentication", e);+ return "fallback";+ }+ };++/**+ * Lock the app.+ */+export const lock = (+ lockScreenMode: AppLockState["lockScreenMode"] = "lock",+) => {+ const snapshot = appLockState().snapshot;+ setSnapshot({ ...snapshot, lockScreenMode, isLocked: true });+ hydrateBruteForceStateIfNeeded();+};++/**+ * Clear all app lock data on logout.+ *+ * Removes all persisted config and KV DB keys, and resets in-memory state to+ * defaults.+ */+export const logoutAppLock = async () => {+ if (appLockElectron()) {+ await clearPersistedAppLockConfig();+ }++ await Promise.all([+ clearPassphraseMaterial(),+ removeKV(kvKeyInvalidAttempts),+ removeKV(kvKeyCooldownExpiresAt),+ ]);++ stopBruteForceStateHydration();+ _wasReauthenticationCancelled = false;+ _state = undefined;+};++/**+ * Update the auto-lock delay.+ */+export const setAutoLockTime = async (ms: number) => {+ if (!(await isAppLockSupported())) {+ throw new Error("App lock is not supported");+ }++ const autoLockTimeMs = clampNonNegativeInt(ms);+ const snapshot = appLockState().snapshot;+ await savePersistedAppLockConfig({+ enabled: snapshot.enabled,+ lockType: snapshot.lockType,+ autoLockTimeMs,+ });+ setSnapshot({ ...snapshot, autoLockTimeMs });+};++/**+ * Disable app lock entirely.+ *+ * Clears all stored credentials from KV DB, resets attempts and cooldown, and+ * updates persisted config and in-memory state.+ */+export const disableAppLock = async () => {+ if (!(await isAppLockSupported())) {+ throw new Error("App lock is not supported");+ }++ await Promise.all([+ clearPassphraseMaterial(),+ removeKV(kvKeyInvalidAttempts),+ removeKV(kvKeyCooldownExpiresAt),+ ]);++ const snapshot = appLockState().snapshot;+ await savePersistedAppLockConfig({+ enabled: false,+ lockType: "none",+ autoLockTimeMs: snapshot.autoLockTimeMs,+ });+ setSnapshot({+ ...snapshot,+ enabled: false,+ lockType: "none",+ lockScreenMode: "lock",+ isLocked: false,+ invalidAttemptCount: 0,+ cooldownExpiresAt: 0,+ });+ stopBruteForceStateHydration();+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/avatar.ts b/web/apps/albums/vendor/ente-new/photos/services/avatar.tsnew file mode 100644index 0000000000..6c5395302e--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/avatar.ts@@ -0,0 +1,66 @@+/**+ * The CSS color for the uploader indicator on a file that was uploaded to a+ * public "collect" link that the user has created.+ *+ * Such files belong to the user, even if they were uploaded by someone on their+ * behalf, and are thus marked differently (in this case, colorlessly) than+ * other shared files.+ *+ * This is a hex string, suitable for being used in CSS.+ */+export const avatarBackgroundColorPublicCollectedFile = "#000000";++/**+ * Foreground / text color for the avatars.+ *+ * All avatar background colors are chosen to work with this.+ */+export const avatarTextColor = "#fff";++/**+ * The ordered list of CSS colors for the owner indicator avatar background on+ * files that the user does not own in shared albums.+ *+ * Each entry is a hex string, suitable for being used in CSS.+ */+const avatarBackgroundColors = [+ "#76549A",+ "#DF7861",+ "#94B49F",+ "#87A2FB",+ "#C689C6",+ "#937DC2",+ "#325288",+ "#85B4E0",+ "#C1A3A3",+ "#E1A059",+ "#426165",+ "#6B77B2",+ "#957FEF",+ "#DD9DE2",+ "#82AB8B",+ "#9BBBE8",+ "#8FBEBE",+ "#8AC3A1",+ "#A8B0F2",+ "#B0C695",+ "#E99AAD",+ "#D18484",+ "#78B5A7",+];++/**+ * Return the CSS color to use as the background of the avatar indicating the+ * owner of a shared file.+ *+ * @param ownerID The user ID of the user who owns that file.+ *+ * Note that for the files in shared albums uploaded via collect links, while we+ * do show an avatar / uploader indicator, but these should use+ * {@link avatarBackgroundColorPublicCollectedFile}.+ *+ * @returns A a hex string, suitable for being used in CSS as the color of the+ * owner avatar indicator atop item thumbnails.+ */+export const avatarBackgroundColor = (ownerID: number) =>+ avatarBackgroundColors[ownerID % avatarBackgroundColors.length]!;diff --git a/web/apps/albums/vendor/ente-new/photos/services/collection-summary.ts b/web/apps/albums/vendor/ente-new/photos/services/collection-summary.tsnew file mode 100644index 0000000000..0ce77e61ca--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/collection-summary.ts@@ -0,0 +1,259 @@+import type { CollectionType } from "ente-media/collection";+import type { EnteFile } from "ente-media/file";++export type CollectionSummaryType =+ | CollectionType+ | "all"+ | "hiddenItems"+ | "defaultHidden"+ | "archiveItems"+ | "trash"+ | "userFavorites"+ | "sharedIncoming";++export type CollectionSummaryAttribute =+ | CollectionSummaryType+ | "shared"+ | "sharedOutgoing"+ | "sharedIncomingViewer"+ | "sharedIncomingCollaborator"+ | "sharedIncomingAdmin"+ | "sharedOnlyViaLink"+ | "system"+ | "archived"+ | "hideFromCollectionBar"+ | "pinned"+ | "shareePinned";++/**+ * ID of the special {@link CollectionSummary} instances that are not backed by+ * a real {@link Collection}.+ */+export const PseudoCollectionID = {+ /**+ * The "All" section.+ *+ * The "All" section is the default view when the user opens the gallery,+ * showing them all of their unique non-hidden and non-archived files.+ */+ all: 0,+ /**+ * A pseudo-collection containing the individually archived files.+ *+ * The archive items is a pseudo-collection consisting of all the files+ * which have been individually archived. It is what gets shown when the+ * user navigates to the "Archive" section.+ */+ archiveItems: -1,+ /**+ * Trash.+ *+ * This pseudo-collection contains items that are in the user's trash. Each+ * items corresponds to a file that has been deleted, but has not yet been+ * deleted permanently.+ *+ * As a special case, when the trash pseudo collection is being shown, then+ * the corresponding files array will have {@link EnteTrashFile} items+ * instead of normal {@link EnteFile} ones.+ */+ trash: -2,+ /**+ * A placeholder for the uncategorized collection until the real one comes+ * into existence.+ *+ * [Note: Uncategorized placeholder]+ *+ * The user's sole "uncategorized" collection is created on demand the first+ * time we need to move a file out of the last collection it belonged to+ * (yet retain the file).+ *+ * Until the real uncategorized collection comes into existence, we use this+ * dummy placeholder collection as the {@link CollectionSummary} that gets+ * shown if the user navigates to the "Uncategorized" section in the UI.+ */+ uncategorizedPlaceholder: -3,+ /**+ * A pseudo-collection containing the individually hidden files.+ *+ * The "Hidden items" is the default pseudo-collection shown in the "Hidden"+ * section. It consists of the files that the user has individually hidden.+ *+ * It is derived by merging all of the user's "default hidden" albums (See:+ * Note: Multiple "default" hidden collections]).+ *+ * In addition to this "Hidden items" pseudo-collection, the "Hidden"+ * section also shows other albums that were hidden.+ */+ hiddenItems: -4,+} as const;++/**+ * A massaged version of a collection or a pseudo-collection suitable for being+ * directly shown in the UI.+ *+ * From one perspective, this can be thought of as a+ * "CollectionOrPseudoCollection": a group of files listed together in the UI,+ * with the files coming from a real "collection" or some special "section".+ *+ * - In the first case, the underlying listing will be backed by a+ * {@link Collection},+ *+ * - In the second case the files and other attributes comprising the listing+ * will be determined by the special case-specific rules for that particular+ * pseudo-collection.+ *+ * However, even when this is backed by a corresponding "real"+ * {@link Collection}, it adds some extra attributes that make it easier and+ * more efficient for the UI elements to render this collection summary+ * directly. So from that perspective, this can be also be thought of as a+ * "UICollection".+ */+export interface CollectionSummary {+ /**+ * The ID of the underlying {@link Collection}, or one of the predefined+ * {@link PseudoCollectionID}s.+ */+ id: number;+ /**+ * The primary "UI" type for the collection or pseudo-collection.+ *+ * For newer code consider using {@link attributes} instead.+ */+ type: CollectionSummaryType;+ /**+ * Various UI related attributes of the collection or pseudo-collection.+ *+ * This is meant to replace {@link type} gradually. It defines various+ * ad-hoc "UI" attributes which make it easier and more efficient for the UI+ * elements to render the collection summary in the UI.+ */+ attributes: Set<CollectionSummaryAttribute>;+ /**+ * The name of the collection or pseudo-collection surfaced in the UI.+ */+ name: string;+ /**+ * The newest file in the collection or pseudo-collection (if any).+ */+ latestFile: EnteFile | undefined;+ /**+ * The file to show as the cover for the collection or pseudo-collection.+ *+ * This can be one of+ * - A file explicitly chosen by the user.+ * - The latest file.+ * - The oldest file (if the user has set a reverse sort on the collection).+ */+ coverFile: EnteFile | undefined;+ /**+ * The number of files in the underlying collection, or the number of files+ * computed to belong to the pseudo-collection.+ */+ fileCount: number;+ /**+ * The time (epoch microseconds) when the collection was last updated. For+ * pseudo-collections this will (usually) be the updation time of the latest+ * file that it contains.+ */+ updationTime: number | undefined;+ sortPriority: CollectionSummarySortPriority;+ order?: number;+}++/**+ * Collection summaries, indexed by their IDs.+ */+export type CollectionSummaries = Map<number, CollectionSummary>;++/**+ * The sort schemes that can be used when we're showing list of collections+ * (e.g. in the collection bar).+ *+ * This is the list of all possible values, see {@link CollectionsSortBy} for+ * the type.+ */+export const collectionsSortBy = [+ "name-asc",+ "name-desc",+ "creation-time-asc",+ "creation-time-desc",+ "updation-time-asc",+ "updation-time-desc",+] as const;++/**+ * Type of individual {@link collectionsSortBy} values.+ */+export type CollectionsSortBy = (typeof collectionsSortBy)[number];++/**+ * An orderable set collection "priorities".+ *+ * Collection summaries that need to appear prior to other collection summaries+ * get assigned a "priority", which is an otherwise arbitrary integer that only+ * serves as a sort priority (higher being prior).+ *+ * All collections in a higher category appear together, and before collections+ * in lower categories. Within each priority, the collections are sorted by the+ * applicable {@link CollectionsSortBy}.+ */+export const CollectionSummarySortPriority = {+ /**+ * Currently: "All", "Uncategorized", "Hidden items".+ */+ system: 9,+ favorites: 8,+ pinned: 7,+ other: 0,+} as const;++/**+ * The TypeScript type that restricts the possible values to be one from amongst+ * the {@link CollectionSummarySortCategory} constants.+ */+export type CollectionSummarySortPriority =+ (typeof CollectionSummarySortPriority)[keyof typeof CollectionSummarySortPriority];++export const haveOnlySystemCollections = (+ collectionSummaries: CollectionSummaries,+) =>+ [...collectionSummaries.values()].every((cs) =>+ cs.attributes.has("system"),+ );++export const canAddToCollection = ({ attributes }: CollectionSummary) =>+ !attributes.has("system") && !attributes.has("sharedIncomingViewer");++export const canMoveToCollection = ({ attributes }: CollectionSummary) =>+ !attributes.has("system") && !attributes.has("sharedIncoming");++/**+ * Sort an array of collection summaries by the specified sort order.+ *+ * @param collectionSummaries The array of collection summaries to sort+ * @param by The sort order to apply+ * @returns A new sorted array of collection summaries+ */+export const sortCollectionSummaries = (+ collectionSummaries: CollectionSummary[],+ by: CollectionsSortBy,+): CollectionSummary[] => {+ return [...collectionSummaries].sort((a, b) => {+ switch (by) {+ case "name-asc":+ return a.name.localeCompare(b.name);+ case "name-desc":+ return b.name.localeCompare(a.name);+ case "creation-time-asc":+ // Oldest first: lower ID = created earlier.+ return a.id - b.id;+ case "creation-time-desc":+ // Newest first: higher ID = created later.+ return b.id - a.id;+ case "updation-time-asc":+ return (a.updationTime ?? 0) - (b.updationTime ?? 0);+ case "updation-time-desc":+ return (b.updationTime ?? 0) - (a.updationTime ?? 0);+ }+ });+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/collection.ts b/web/apps/albums/vendor/ente-new/photos/services/collection.tsnew file mode 100644index 0000000000..69bf36ca54--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/collection.ts@@ -0,0 +1,1841 @@+import { ensureLocalUser } from "ente-accounts/services/user";+import { blobCache } from "ente-base/blob-cache";+import {+ boxSeal,+ boxSealOpen,+ decryptBox,+ encryptBox,+ generateKey,+} from "ente-base/crypto";+import { haveWindow } from "ente-base/env";+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { ensureMasterKeyFromSession } from "ente-base/session";+import { groupFilesByCollectionID } from "ente-gallery/utils/file";+import {+ CollectionSubType,+ decryptRemoteCollection,+ RemoteCollection,+ RemotePublicURL,+ type Collection,+ type CollectionNewParticipantRole,+ type CollectionOrder,+ type CollectionPrivateMagicMetadataData,+ type CollectionPublicMagicMetadataData,+ type CollectionShareeMagicMetadataData,+ type CollectionType,+ type PublicURL,+} from "ente-media/collection";+import {+ decryptRemoteFile,+ FileDiffResponse,+ type EnteFile,+} from "ente-media/file";+import { ItemVisibility, metadataHash } from "ente-media/file-metadata";+import {+ createMagicMetadata,+ encryptMagicMetadata,+} from "ente-media/magic-metadata";+import { splitByPredicate } from "ente-utils/array";+import { z } from "zod";+import { batched, type UpdateMagicMetadataRequest } from "./file";+import {+ removeCollectionIDLastSyncTime,+ saveCollectionFiles,+ saveCollectionLastSyncTime,+ saveCollections,+ saveCollectionsUpdationTime,+ savedCollectionFiles,+ savedCollectionLastSyncTime,+ savedCollections,+ savedCollectionsUpdationTime,+} from "./photos-fdb";+import { ensureUserKeyPair, getPublicKey } from "./user";++const uncategorizedCollectionName = "Uncategorized";+const defaultHiddenCollectionName = ".hidden";+export const defaultHiddenCollectionUserFacingName = "Hidden";+const favoritesCollectionName = "Favorites";++/**+ * Create a new album (a collection of type "album") on remote, and return its+ * local representation.+ *+ * Remote only, does not modify local state.+ *+ * @param albumName The name to use for the new album.+ */+export const createAlbum = (albumName: string) =>+ createCollection(albumName, "album");++/**+ * Create a new quick link collection on remote, and return its local+ * representation.+ *+ * Remote only, does not modify local state.+ *+ * @param name The name to use for the new quick link collection.+ */+export const createQuickLinkCollection = (name: string) =>+ createCollection(name, "album", {+ subType: CollectionSubType.quicklink,+ visibility: ItemVisibility.visible,+ });++/**+ * Create a new hidden album on remote, and return its local representation.+ *+ * Remote only, does not modify local state.+ *+ * @param albumName The name to use for the new hidden album.+ */+export const createHiddenAlbum = (albumName: string) =>+ createCollection(albumName, "album", { visibility: ItemVisibility.hidden });++/**+ * Create a new collection on remote, and return its local representation.+ *+ * Remote only, does not modify local state.+ *+ * @param name The name of the new collection.+ *+ * @param type The type of the new collection.+ *+ * @param magicMetadataData Optional metadata to use as the collection's private+ * mutable metadata when creating the new collection.+ */+const createCollection = async (+ name: string,+ type: CollectionType,+ magicMetadataData?: CollectionPrivateMagicMetadataData,+): Promise<Collection> => {+ const collectionKey = await generateKey();+ const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =+ await encryptBox(collectionKey, await ensureMasterKeyFromSession());+ const { encryptedData: encryptedName, nonce: nameDecryptionNonce } =+ await encryptBox(new TextEncoder().encode(name), collectionKey);+ const magicMetadata = magicMetadataData+ ? await encryptMagicMetadata(+ createMagicMetadata(magicMetadataData),+ collectionKey,+ )+ : undefined;++ const remoteCollection = await postCollections({+ encryptedKey,+ keyDecryptionNonce,+ encryptedName,+ nameDecryptionNonce,+ type,+ ...(magicMetadata && { magicMetadata }),+ });++ return decryptRemoteKeyAndCollection(remoteCollection);+};++/**+ * Given a {@link RemoteCollection}, first obtain its decryption key, and then+ * use that to decrypt and return the collection itself.+ */+const decryptRemoteKeyAndCollection = async (collection: RemoteCollection) =>+ decryptRemoteCollection(collection, await decryptCollectionKey(collection));++/**+ * Return the decrypted collection key (as a base64 string) for the given+ * {@link RemoteCollection}.+ */+export const decryptCollectionKey = async (+ collection: RemoteCollection,+): Promise<string> => {+ const { owner, encryptedKey, keyDecryptionNonce } = collection;+ if (owner.id == ensureLocalUser().id) {+ // The collection key of collections owned by the user is encrypted with+ // the user's master key. The nonce will be present in such cases.+ return decryptBox(+ { encryptedData: encryptedKey, nonce: keyDecryptionNonce! },+ await ensureMasterKeyFromSession(),+ );+ } else {+ // The collection key of collections shared with the user is encrypted+ // with the user's public key.+ return boxSealOpen(encryptedKey, await ensureUserKeyPair());+ }+};++/**+ * Zod schema for a remote response containing a single collection.+ */+const CollectionResponse = z.object({ collection: RemoteCollection });++/**+ * Create a collection on remote with the provided data, and return the new+ * remote collection object returned by remote on success.+ */+const postCollections = async (+ collectionData: Partial<RemoteCollection>,+): Promise<RemoteCollection> => {+ const res = await fetch(await apiURL("/collections"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(collectionData),+ });+ ensureOk(res);+ return CollectionResponse.parse(await res.json()).collection;+};++/**+ * Fetch a collection from remote by its ID.+ *+ * Remote only, does not use or modify local state.+ *+ * This is not expected to be needed in the normal flow of things, since we+ * fetch collections en masse, and efficiently, using the collection diff+ * requests.+ *+ * @param collectionID The ID of the collection to fetch.+ *+ * @returns The collection obtained from remote after decrypting its contents.+ */+export const getCollectionByID = async (+ collectionID: number,+): Promise<Collection> => {+ const res = await fetch(await apiURL(`/collections/${collectionID}`), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ const { collection } = CollectionResponse.parse(await res.json());+ return decryptRemoteKeyAndCollection(collection);+};++/**+ * Zod schema for a remote response containing a an array of collections.+ */+const CollectionsResponse = z.object({+ collections: z.array(RemoteCollection),+});++/**+ * An collection upsert or deletion obtained as a result of+ * {@link getCollections} invocation.+ *+ * Each change either contains the latest data associated with the collection+ * that has been created or updated, or has a flag set to indicate that the+ * corresponding collection has been deleted.+ */+export interface CollectionChange {+ /**+ * The ID of the collection.+ */+ id: number;+ /**+ * The added or updated collection, or `undefined` for deletions.+ *+ * - This will be set to the (decrypted) collection if it was added or+ * updated on remote.+ *+ * - This will not be set if the corresponding collection was deleted on+ * remote.+ */+ collection?: Collection;+ /**+ * Epoch microseconds denoting when this collection was last changed+ * (created or updated or deleted).+ */+ updationTime: number;+}++/**+ * Pull the latest collections from remote.+ *+ * This function uses a delta diff, pulling only changes since the timestamp+ * saved by the last pull.+ *+ * @returns the latest list of collections, reflecting both the state in our+ * local database and on remote.+ */+export const pullCollections = async (): Promise<Collection[]> => {+ const collections = await savedCollections();+ let sinceTime = (await savedCollectionsUpdationTime()) ?? 0;++ const changes = await getCollections(sinceTime);++ if (!changes.length) return collections;++ const collectionsByID = new Map(collections.map((c) => [c.id, c]));+ for (const { id, updationTime, collection } of changes) {+ sinceTime = Math.max(sinceTime, updationTime);+ if (collection) {+ collectionsByID.set(id, collection);+ } else {+ // Collection was deleted on remote.+ await removeCollectionIDLastSyncTime(id);+ collectionsByID.delete(id);+ }+ }++ const updatedCollections = [...collectionsByID.values()];++ await saveCollections(updatedCollections);+ await saveCollectionsUpdationTime(sinceTime);++ return updatedCollections;+};++/**+ * Fetch all collections that have been added or updated on remote since+ * {@link sinceTime}, with markers for those that have been deleted.+ *+ * @param sinceTime The {@link updationTime} of the latest collection that was+ * fetched in a previous set of changes. This allows us to resume fetching from+ * that point. Pass 0 to fetch from the beginning.+ *+ * @returns An array of {@link CollectionChange}s. It is guaranteed that there+ * will be at most one entry for a given collection in the result array. See:+ * [Note: Diff response will have at most one entry for an id]+ */+const getCollections = async (+ sinceTime: number,+): Promise<CollectionChange[]> => {+ const res = await fetch(await apiURL("/collections/v2", { sinceTime }), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ const { collections } = CollectionsResponse.parse(await res.json());+ return Promise.all(+ collections.map(async (c) => ({+ id: c.id,+ updationTime: c.updationTime,+ collection: c.isDeleted+ ? undefined+ : await decryptRemoteKeyAndCollection(c),+ })),+ );+};++/**+ * Fetch all files from remote and update our local database.+ *+ * Each time it updates the local database, the {@link onSetCollectionFiles}+ * callback is also invoked to give the caller a chance to bring its own+ * in-memory state up to speed.+ *+ * @param collections The user's collections. These are assumed to be the latest+ * collections on remote (that is, the pull for collections should happen prior+ * to calling this function).+ *+ * @param onSetCollectionFiles An optional callback invoked when the locally+ * saved collection files were replaced by the provided {@link collectionFiles}.+ *+ * The callback is optional because we might be called in a context where we+ * just want to update the local database, and there is no other in-memory state+ * we need to keep in sync.+ *+ * The callback can be invoked multiple times for each pull (once for each batch+ * of changes received, for each collection that was updated).+ *+ * @returns true if one or more files were updated locally, false otherwise.+ */+export const pullCollectionFiles = async (+ collections: Collection[],+ onSetCollectionFiles: ((files: EnteFile[]) => void) | undefined,+) => {+ let didUpdateFiles = false;++ const savedFiles = await savedCollectionFiles();++ // Prune collections files for which we no longer have a collection.+ const collectionIDs = new Set(collections.map((c) => c.id));+ let files = savedFiles.filter((f) => collectionIDs.has(f.collectionID));++ // Update both the saved and in-memory files to reflect the pruning.+ if (files.length != savedFiles.length) {+ await saveCollectionFiles(files);+ onSetCollectionFiles?.(files);+ didUpdateFiles = true;+ }++ for (const collection of collections) {+ let sinceTime = (await savedCollectionLastSyncTime(collection)) ?? 0;+ if (sinceTime == collection.updationTime) {+ // The updationTime of a collection is guaranteed to be >= the+ // updationTime of any file in the collection.+ continue;+ }++ const [thisCollectionFiles, otherFiles] = splitByPredicate(+ files,+ (f) => f.collectionID == collection.id,+ );++ const thisCollectionFilesByID = new Map(+ thisCollectionFiles.map((f) => [f.id, f]),+ );++ while (true) {+ const { diff, hasMore } = await getCollectionDiff(+ collection.id,+ sinceTime,+ );+ if (!diff.length) break;++ for (const change of diff) {+ sinceTime = Math.max(sinceTime, change.updationTime);+ if (change.isDeleted) {+ thisCollectionFilesByID.delete(change.id);+ } else {+ const file = await decryptRemoteFile(+ change,+ collection.key,+ );+ await clearCachedThumbnailIfContentChanged(+ thisCollectionFilesByID.get(change.id),+ file,+ );+ thisCollectionFilesByID.set(change.id, file);+ }+ }++ files = otherFiles.concat([...thisCollectionFilesByID.values()]);++ await saveCollectionFiles(files);+ await saveCollectionLastSyncTime(collection, sinceTime);+ onSetCollectionFiles?.(files);+ didUpdateFiles = true;++ if (!hasMore) break;+ }++ // There might be a difference between the latest updation time of a+ // file in the collection, and the latest time of the collection itself,+ // if something about the collection itself changed, not the files in it+ // (e.g. if the collection was renamed).+ //+ // In such cases, advance the sync time to match the collection's update+ // time so we don't do an unnecessary collection diff the next time.+ await saveCollectionLastSyncTime(collection, collection.updationTime);+ }++ return didUpdateFiles;+};++/**+ * Fetch all files in the given collection have been created or updated since+ * {@link sinceTime}.+ *+ * Remote only, does not modify local state.+ *+ * @param collection The ID of the collection whose updates we want to fetch.+ *+ * @param sinceTime The timestamp of most recently update for the collection+ * that we have already pulled. This serves both as a pagination mechanish, and+ * a way to fetch a delta diff the next time the client needs to pull changes+ * from remote.+ */+const getCollectionDiff = async (collectionID: number, sinceTime: number) => {+ const res = await fetch(+ await apiURL("/collections/v2/diff", { collectionID, sinceTime }),+ { headers: await authenticatedRequestHeaders() },+ );+ ensureOk(res);+ return FileDiffResponse.parse(await res.json());+};++/**+ * Clear cached thumbnail of an existing file if the thumbnail data has changed.+ *+ * This function in expected to be called when we are processing a collection+ * diff, updating our local state to reflect files that were updated on remote.+ * This is an opportune moment to invalidate any cached thumbnails for files+ * whose thumbnail content has changed.+ *+ * An example of when such invalidation is necessary:+ *+ * 1. Take a photo on mobile, and let it sync via the mobile app to us (web).+ * 2. Edit the photo outside of Ente (e.g. using Apple Photos).+ * 3. When the Ente mobile client next comes into foreground, it'll update the+ * remote thumbnail for the existing file to reflect the changes.+ *+ * @param existingFile The {@link EnteFile} we had in our local database before+ * processing the diff response. Pass `undefined` to indicate that there was no+ * existing file corresponding to {@link updatedFile}; in such a case this+ * function is a no-op.+ *+ * @param updatedFile The update {@link EntneFile} (with the same file ID as the+ * {@link existingFile}) which we got in the diff response.+ */+const clearCachedThumbnailIfContentChanged = async (+ existingFile: EnteFile | undefined,+ updatedFile: EnteFile,+) => {+ if (!existingFile) return;++ // The hashes of the files differ, which indicates that the change was in+ // the file's contents, not the metadata itself, and thus we should refresh+ // the thumbnail.+ if (+ metadataHash(existingFile.metadata) !=+ metadataHash(updatedFile.metadata)+ ) {+ // This is an infrequent occurrence, so we lazily get the cache.+ const thumbnailCache = await blobCache("thumbs");+ await thumbnailCache.delete(updatedFile.id.toString());+ }+};++/**+ * Return all collections (both normal and hidden) that are present in our+ * local database.+ */+export const savedAllCollections = (): Promise<Collection[]> =>+ savedCollections();++/**+ * Return all normal (non-hidden) collections that are present in our local+ * database.+ */+export const savedNormalCollections = (): Promise<Collection[]> =>+ savedCollections().then(+ (cs) => splitByPredicate(cs, isHiddenCollection)[1],+ );++/**+ * Return all hidden collections that are present in our local database.+ */+export const savedHiddenCollections = (+ currentUserID?: number,+): Promise<Collection[]> =>+ savedCollections().then(+ (cs) =>+ splitByPredicate(cs, (c) =>+ isHiddenCollection(c, currentUserID),+ )[0],+ );++/**+ * Return a map of the (user-facing) collection name, indexed by collection ID.+ */+export const createCollectionNameByID = (collections: Collection[]) =>+ new Map(collections.map((c) => [c.id, collectionUserFacingName(c)]));++/**+ * Return the "user facing" name of the given collection.+ *+ * Usually this is the same as the collection name, but it might be a different+ * string for special collections like default hidden collections.+ */+export const collectionUserFacingName = (collection: Collection) =>+ isDefaultHiddenCollection(collection)+ ? defaultHiddenCollectionUserFacingName+ : collection.name;++/**+ * A CollectionFileItem represents a file in a API request to add, move or+ * restore files to a particular collection.+ */+interface CollectionFileItem {+ /**+ * The file's ID.+ */+ id: number;+ /**+ * The file's key (as a base64 string), encrypted with the key of the+ * collection to which it is being added or moved.+ */+ encryptedKey: string;+ /**+ * The nonce (as a base64 string) that was used during the encryption of+ * {@link encryptedKey}.+ */+ keyDecryptionNonce: string;+}++/**+ * Make a remote request to add the given {@link files} to the given+ * {@link collection}.+ *+ * Remote only, does not modify local state.+ */+export const addToCollection = async (+ collection: Collection,+ files: EnteFile[],+) =>+ batched(files, async (batchFiles) => {+ const encryptedFileKeys = await encryptWithCollectionKey(+ collection,+ batchFiles,+ );+ ensureOk(+ await fetch(await apiURL("/collections/add-files"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({+ collectionID: collection.id,+ files: encryptedFileKeys,+ }),+ }),+ );+ });++/**+ * Make a remote request to restore the given {@link files} to the given+ * {@link collection}.+ *+ * Remote only, does not modify local state.+ */+export const restoreToCollection = async (+ collection: Collection,+ files: EnteFile[],+) =>+ batched(files, async (batchFiles) => {+ const encryptedFileKeys = await encryptWithCollectionKey(+ collection,+ batchFiles,+ );+ ensureOk(+ await fetch(await apiURL("/collections/restore-files"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({+ collectionID: collection.id,+ files: encryptedFileKeys,+ }),+ }),+ );+ });++/**+ * Make a remote request to move the given {@link files} (which may be in+ * different collections) to the given {@link collection}.+ *+ * This is a higher level primitive than {@link moveFromCollection} that first+ * segregates the files into per-collection sets, and then performs+ * {@link moveFromCollection} for each such set.+ *+ * Remote only, does not modify local state.+ */+export const moveToCollection = async (+ collection: Collection,+ files: EnteFile[],+) =>+ Promise.all(+ groupFilesByCollectionID(files)+ .entries()+ .filter(([cid]) => cid != collection.id)+ .map(([cid, cf]) => moveFromCollection(cid, collection, cf)),+ );++/**+ * Make a remote request to move the given {@link files} from a collection (as+ * identified by its {@link fromCollectionID}) to the given+ * {@link toCollection}.+ *+ * Remote only, does not modify local state.+ */+export const moveFromCollection = async (+ fromCollectionID: number,+ toCollection: Collection,+ files: EnteFile[],+) =>+ batched(files, async (batchFiles) => {+ const encryptedFileKeys = await encryptWithCollectionKey(+ toCollection,+ batchFiles,+ );+ ensureOk(+ await fetch(await apiURL("/collections/move-files"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({+ fromCollectionID: fromCollectionID,+ toCollectionID: toCollection.id,+ files: encryptedFileKeys,+ }),+ }),+ );+ });++/**+ * Return an array of {@link CollectionFileItem}s, one for each file in+ * {@link files}, containing the corresponding file' ID and keys, but this time+ * encrypted using the key of the given {@link collection}.+ */+const encryptWithCollectionKey = async (+ collection: Collection,+ files: EnteFile[],+): Promise<CollectionFileItem[]> =>+ Promise.all(+ files.map(async (file) => {+ const box = await encryptBox(file.key, collection.key);+ return {+ id: file.id,+ encryptedKey: box.encryptedData,+ keyDecryptionNonce: box.nonce,+ };+ }),+ );++/**+ * Make a remote request to move the given {@link files} to trash.+ *+ * @param files The {@link EnteFile}s to move to trash. The API request needs+ * both a file ID and a collection ID, but there should be at most one entry for+ * a particular fileID in this array.+ *+ * Remote only, does not modify local state.+ */+export const moveToTrash = async (files: EnteFile[]) =>+ batched(files, async (batchFiles) =>+ ensureOk(+ await fetch(await apiURL("/files/trash"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({+ items: batchFiles.map((file) => ({+ fileID: file.id,+ collectionID: file.collectionID,+ })),+ }),+ }),+ ),+ );++/**+ * Make a remote request to delete the given {@link fileIDs} from trash.+ *+ * Remote only, does not modify local state.+ */+export const deleteFromTrash = async (fileIDs: number[]) =>+ batched(fileIDs, async (batchIDs) =>+ ensureOk(+ await fetch(await apiURL("/trash/delete"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ fileIDs: batchIDs }),+ }),+ ),+ );++/**+ * Remove the given files from the specified collection owned by the user.+ *+ * Reads local state but does not modify it. The effects are on remote.+ *+ * @param collection A collection (either owned by the user, or shared with the+ * user).+ *+ * @param files The files to remove from the collection. The files owned by the+ * user will be removed. If the collection is not owned by the user, then any+ * files that are not owned by the user will not be processed (unless the user+ * is an admin of the collection). In such cases, this function will return a+ * count less than the count of the provided files (after having removed what+ * can be removed).+ *+ * @returns The count of files that were processed. This can be less than the+ * count of the provided {@link files} if some files were not processed because+ * because they belong to other users (and {@link collection} also does not+ * belong to the current user, and the user is not an admin).+ *+ * [Note: Removing files from a collection]+ *+ * There are four scenarios+ *+ * own file shared file+ * own collection M R+ * admin in collection R R+ * others collection R not supported+ *+ * M (move) when both collection and file belongs to user+ * R (remove) when only one of them belongs to the user, or user is admin+ *+ * The move operation is not supported across ownership boundaries. The remove+ * operation is only supported across ownership boundaries, but the user should+ * have ownership of either the file or collection (not both), or be an admin.+ *+ * In more detail, the above scenarios can be described this way.+ *+ * 1. Move: If the user owns both the collection and the file they're trying to+ * remove from the collection, then instead of a remove the client needs to+ * move it to a different user owned collection in which it already exists+ * (such a move acts as a remove). If it doesn't exist in any other user+ * owned collection, then move it to the user's "Uncategorized" collection.+ * The intent is that a "remove from collection" should not remove the last+ * copy of a file (thus deleting it).+ *+ * 2. Remove: If the user does not own the file being removed, or owns the file+ * being removed but does not own the collection from which it is being+ * removed, they can remove it from the collection using the POST+ * "/collections/v3/remove-files".+ *+ * 3. Admin remove: If the user is an admin of a collection they don't own, they+ * can remove any file from the collection (including files they don't own).+ *+ * 4. Not supported: Removing a file the user does not own from a collection+ * that the user does not own and is not an admin of.+ *+ * The "remove from collection" primitive is provided to the user both as a UI+ * action (on selecting files in a collection), and as an implicit action if the+ * user chooses the option to "keep files" when deleting a collection.+ *+ * This entire shebang is implemented by the following set of functions:+ *+ * 1. [Public] {@link removeFromCollection} - Handles both own and others+ * collections by delegating to the one of the following functions.+ *+ * 2. [Public] {@link removeFromOwnCollection} - Handles both cases for own+ * collections by delegating to either "Move" or "Remove"+ *+ * 3. [Private] {@link removeFromOthersCollection} - Handles cases for other's+ * collections. If the user is an admin, they can remove all files. Otherwise+ * only the user's own files can be removed.+ *+ * 4. [Private] {@link removeOwnFilesFromOwnCollection} implements the "Move".+ *+ * 5. [Private] {@link removeNonCollectionOwnerFiles} implements the "Remove".+ */+export const removeFromCollection = async (+ collection: Collection,+ files: EnteFile[],+): Promise<number> =>+ collection.owner.id == ensureLocalUser().id+ ? removeFromOwnCollection(collection.id, files)+ : removeFromOthersCollection(collection, files);++export const removeFromOwnCollection = async (+ collectionID: number,+ files: EnteFile[],+) => {+ const userID = ensureLocalUser().id;+ const [userFiles, nonUserFiles] = splitByPredicate(+ files,+ (f) => f.ownerID == userID,+ );+ if (userFiles.length) {+ await removeOwnFilesFromOwnCollection(collectionID, userFiles);+ }+ if (nonUserFiles.length) {+ await removeNonCollectionOwnerFiles(collectionID, nonUserFiles);+ }+ return files.length;+};++const removeFromOthersCollection = async (+ collection: Collection,+ files: EnteFile[],+) => {+ const userID = ensureLocalUser().id;+ // Check if user is an admin of this collection+ const isAdmin =+ collection.sharees.find((s) => s.id == userID)?.role == "ADMIN";++ if (isAdmin) {+ // Admins can remove all files from the collection+ if (files.length) {+ await removeNonCollectionOwnerFiles(collection.id, files);+ }+ return files.length;+ }++ // Non-admins can only remove their own files+ const [userFiles] = splitByPredicate(files, (f) => f.ownerID == userID);+ if (userFiles.length) {+ await removeNonCollectionOwnerFiles(collection.id, userFiles);+ }+ return userFiles.length;+};++/**+ * Remove the given user owned files from the given collection also owned by the+ * user, ensuring that at least one user owned instance is retained for them+ * (either in a different user owned collection in which they already existed,+ * or in the user's "Uncategorized" collection as a fallback).+ *+ * Reads local state but does not modify it. The effects are on remote.+ *+ * This is used as a subroutine of [Note: Removing files from a collection].+ */+const removeOwnFilesFromOwnCollection = async (+ collectionID: number,+ filesToRemove: EnteFile[],+) => {+ const userID = ensureLocalUser().id;+ const collections = await savedCollections();+ const collectionFiles = await savedCollectionFiles();++ const collectionsByID = new Map(collections.map((c) => [c.id, c]));++ // This set keeps a running track of file IDs that still need to be removed.+ // It is seeded with the original set of files we were asked to remove.+ const filesToRemoveIDs = new Set(filesToRemove.map((f) => f.id));+ // A predicate that checks if the given file is still pending removal.+ const pendingRemove = (f: EnteFile) => filesToRemoveIDs.has(f.id);++ const collectionFilesToRemove = collectionFiles.filter(pendingRemove);+ const groups = groupFilesByCollectionID(collectionFilesToRemove);+ for (const [targetCollectionID, filesInCollection] of groups.entries()) {+ // Ignore the source collection itself.+ if (targetCollectionID == collectionID) continue;++ const targetCollection = collectionsByID.get(targetCollectionID)!;+ // We want a copy to exist in at least one other user owned collection.+ if (targetCollection.owner.id != userID) continue;+ // We'll move to uncategorized after the loop (if they still remain).+ if (targetCollection.type == "uncategorized") continue;++ const filesInCollectionToRemove =+ filesInCollection.filter(pendingRemove);+ if (!filesInCollectionToRemove.length) continue;++ // The file already exists in the target collection, but this acts as+ // "remove" from the source.+ await moveFromCollection(+ collectionID,+ targetCollection,+ filesInCollectionToRemove,+ );++ // Mark the files we just moved as been taken care of.+ filesInCollectionToRemove.forEach((f) => filesToRemoveIDs.delete(f.id));+ }++ // Any files that were not moved so far, move them to uncategorized,+ // creating uncategorized if needed.+ const remainingFiles = filesToRemove.filter(pendingRemove);+ if (remainingFiles.length) {+ const uncategorizedCollection =+ collections.find((c) => c.type == "uncategorized") ??+ (await createUncategorizedCollection());++ await moveFromCollection(+ collectionID,+ uncategorizedCollection,+ remainingFiles,+ );+ }+};++/**+ * Remove the provided files from the provided collection on remote.+ *+ * Only files which do not belong to the collection owner can be removed from+ * the collection using this endpoint. That is,+ *+ * - Either the user owns the collection and the all files being removed are+ * owned by somebody else, or+ *+ * - The user owns all the files being removed, but the collection belongs to+ * somebody else.+ *+ * If the collection owner wants to remove files owned by them, then their+ * client should first move those files first to other collections owned by the+ * collection owner.+ *+ * Remote only, does not modify local state.+ *+ * See also: [Note: Removing files from a collection].+ *+ * @param collectionID The ID of collection from which to remove the files.+ *+ * @param files A list of files which do not belong to the user, and which we+ * the user wants to remove from the given collection.+ */+const removeNonCollectionOwnerFiles = async (+ collectionID: number,+ files: EnteFile[],+) =>+ batched(files, async (batchFiles) =>+ ensureOk(+ await fetch(await apiURL("/collections/v3/remove-files"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({+ collectionID,+ fileIDs: batchFiles.map((f) => f.id),+ }),+ }),+ ),+ );++/**+ * Delete a collection on remote.+ *+ * Reads local state but does not modify it. The effects are on remote.+ *+ * @param collectionID The ID of the collection to delete.+ *+ * @param opts Deletion options. In particular, if {@link keepFiles} is true,+ * then the any of the user's files that only exist in this collection are+ * first moved to another one of the user's collection (or Uncategorized if no+ * such collection exists) before deleting the collection.+ *+ * See: [Note: Removing files from a collection]+ */+export const deleteCollection = async (+ collectionID: number,+ opts?: { keepFiles?: boolean },+) => {+ const keepFiles = opts?.keepFiles ?? false;++ if (keepFiles) {+ const collectionFiles = await savedCollectionFiles();+ await removeFromOwnCollection(+ collectionID,+ collectionFiles.filter((f) => f.collectionID == collectionID),+ );+ }++ ensureOk(+ await fetch(+ await apiURL(`/collections/v3/${collectionID}`, {+ collectionID,+ keepFiles,+ }),+ { method: "DELETE", headers: await authenticatedRequestHeaders() },+ ),+ );+};++/**+ * Rename a collection on remote.+ *+ * Remote only, does not modify local state.+ *+ * @param collection The collection to rename.+ *+ * @param newName The new name of the collection+ */+export const renameCollection = async (+ collection: Collection,+ newName: string,+) => {+ if (collection.magicMetadata?.data.subType == CollectionSubType.quicklink) {+ // Convert quicklinks to a regular collection before giving them a name.+ await updateCollectionPrivateMagicMetadata(collection, {+ subType: CollectionSubType.default,+ });+ }+ const { encryptedData: encryptedName, nonce: nameDecryptionNonce } =+ await encryptBox(new TextEncoder().encode(newName), collection.key);+ await postCollectionsRename({+ collectionID: collection.id,+ encryptedName,+ nameDecryptionNonce,+ });+};++interface RenameRequest {+ collectionID: number;+ encryptedName: string;+ nameDecryptionNonce: string;+}++const postCollectionsRename = async (renameRequest: RenameRequest) =>+ ensureOk(+ await fetch(await apiURL("/collections/rename"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(renameRequest),+ }),+ );++/**+ * Change the visibility (normal, archived, hidden) of a collection on remote.+ *+ * Remote only, does not modify local state.+ *+ * This function works with both collections owned by the user, and collections+ * shared with the user.+ *+ * @param collection The collection whose visibility we want to change.+ *+ * @param visibility The new visibility (normal, archived, hidden).+ */+export const updateCollectionVisibility = async (+ collection: Collection,+ visibility: ItemVisibility,+) =>+ collection.owner.id == ensureLocalUser().id+ ? updateCollectionPrivateMagicMetadata(collection, { visibility })+ : updateCollectionShareeMagicMetadata(collection, { visibility });++/**+ * Change the pinned state of a collection on remote.+ *+ * Remote only, does not modify local state.+ *+ * This function works only for collections owned by the user.+ *+ * @param collection The collection whose order we want to change.+ *+ * @param order Whether on not the collection is pinned.+ */+export const updateCollectionOrder = async (+ collection: Collection,+ order: CollectionOrder,+) => updateCollectionPrivateMagicMetadata(collection, { order });++/**+ * Change the order (pin/unpin) of a shared collection on remote for the sharee.+ *+ * Remote only, does not modify local state.+ *+ * This function works only for collections shared with the user (not owned).+ *+ * @param collection The shared collection whose order we want to change.+ *+ * @param order Whether on not the collection is pinned by the sharee.+ */+export const updateShareeCollectionOrder = async (+ collection: Collection,+ order: CollectionOrder,+) => updateCollectionShareeMagicMetadata(collection, { order });++/**+ * Change the sort order of the files with a collection on remote.+ *+ * Remote only, does not modify local state.+ *+ * This function works only for collections owned by the user.+ *+ * @param collection The collection whose file sort order we want to change.+ *+ * @param asc If true, then the files are sorted ascending (oldest first).+ * Otherwise they are sorted descending (newest first).+ */+export const updateCollectionSortOrder = async (+ collection: Collection,+ asc: boolean,+) => updateCollectionPublicMagicMetadata(collection, { asc });++/**+ * Change the cover photo of a collection on remote.+ *+ * Remote only, does not modify local state.+ *+ * This function works only for collections owned by the user.+ *+ * @param collection The collection whose cover we want to change.+ *+ * @param coverID The file ID to set as the cover.+ *+ * Pass `0` to reset to the default cover.+ */+export const updateCollectionCover = async (+ collection: Collection,+ coverID: number,+) => updateCollectionPublicMagicMetadata(collection, { coverID });++/**+ * Change the layout type of a collection on remote.+ *+ * Remote only, does not modify local state.+ *+ * This function works only for collections owned by the user.+ *+ * @param collection The collection whose layout we want to change.+ *+ * @param layout The layout type ("masonry", "grouped", "continuous", "trip").+ */+export const updateCollectionLayout = async (+ collection: Collection,+ layout: string,+) => updateCollectionPublicMagicMetadata(collection, { layout });++/**+ * Update the private magic metadata of a collection on remote.+ *+ * Remote only, does not modify local state.+ *+ * @param collection The collection whose magic metadata we want to update.+ *+ * The existing magic metadata of this collection is used both to obtain the+ * current magic metadata version, and the existing contents on top of which the+ * updates are applied, so it is imperative that both these values are up to+ * sync with remote otherwise the update will fail.+ *+ * @param updates A non-empty subset of+ * {@link CollectionPrivateMagicMetadataData} entries.+ *+ * See: [Note: Magic metadata data cannot have nullish values]+ */+const updateCollectionPrivateMagicMetadata = async (+ { id, key, magicMetadata }: Collection,+ updates: CollectionPrivateMagicMetadataData,+) =>+ putCollectionsMagicMetadata({+ id,+ magicMetadata: await encryptMagicMetadata(+ createMagicMetadata(+ { ...magicMetadata?.data, ...updates },+ magicMetadata?.version,+ ),+ key,+ ),+ });++/**+ * Update the private magic metadata of a single collection on remote.+ */+const putCollectionsMagicMetadata = async (+ updateRequest: UpdateMagicMetadataRequest,+) =>+ ensureOk(+ await fetch(await apiURL("/collections/magic-metadata"), {+ method: "PUT",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(updateRequest),+ }),+ );++/**+ * Update the public magic metadata of a collection on remote.+ *+ * Remote only, does not modify local state.+ *+ * This is a variant of {@link updateCollectionPrivateMagicMetadata} that works+ * with the {@link pubMagicMetadata} of a collection.+ */+const updateCollectionPublicMagicMetadata = async (+ { id, key, pubMagicMetadata }: Collection,+ updates: CollectionPublicMagicMetadataData,+) =>+ putCollectionsPublicMagicMetadata({+ id,+ magicMetadata: await encryptMagicMetadata(+ createMagicMetadata(+ { ...pubMagicMetadata?.data, ...updates },+ pubMagicMetadata?.version,+ ),+ key,+ ),+ });++/**+ * Update the public magic metadata of a single collection on remote.+ */+const putCollectionsPublicMagicMetadata = async (+ updateRequest: UpdateMagicMetadataRequest,+) =>+ ensureOk(+ await fetch(await apiURL("/collections/public-magic-metadata"), {+ method: "PUT",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(updateRequest),+ }),+ );++/**+ * Update the per-sharee magic metadata of a collection on remote.+ *+ * Remote only, does not modify local state.+ *+ * This is a variant of {@link updateCollectionPrivateMagicMetadata} that works+ * with the {@link sharedMagicMetadata} of a collection.+ */+const updateCollectionShareeMagicMetadata = async (+ { id, key, sharedMagicMetadata }: Collection,+ updates: CollectionShareeMagicMetadataData,+) =>+ putCollectionsShareeMagicMetadata({+ id,+ magicMetadata: await encryptMagicMetadata(+ createMagicMetadata(+ { ...sharedMagicMetadata?.data, ...updates },+ sharedMagicMetadata?.version,+ ),+ key,+ ),+ });++/**+ * Update the sharee magic metadata of a single shared collection on remote.+ */+const putCollectionsShareeMagicMetadata = async (+ updateRequest: UpdateMagicMetadataRequest,+) =>+ ensureOk(+ await fetch(await apiURL("/collections/sharee-magic-metadata"), {+ method: "PUT",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(updateRequest),+ }),+ );++/**+ * Create a new collection of type "favorites" for the user on remote, and+ * return its local representation.+ *+ * Remote only, does not modify local state.+ *+ * Each user can have at most one collection of type "favorites" owned by them.+ * While this function does not enforce the constraint locally, it will fail+ * because remote will enforce the constraint and fail the request when we+ * attempt to create a second collection of type "favorites".+ */+const createFavoritesCollection = () =>+ createCollection(favoritesCollectionName, "favorites");++/**+ * Create a new collection of type "uncategorized" for the user on remote, and+ * return its local representation.+ *+ * Remote only, does not modify local state.+ *+ * Each user can have at most one collection of type "uncategorized" owned by+ * them. While this function does not enforce the constraint locally, it will+ * fail because remote will enforce the constraint and fail the request when we+ * attempt to create a second collection of type "uncategorized".+ */+export const createUncategorizedCollection = () =>+ createCollection(uncategorizedCollectionName, "uncategorized");++/**+ * Return the user's own favorites collection if one is found in the local+ * database. Otherwise create a new one and return that.+ *+ * Reads local state but does not modify it. The effects are on remote.+ */+const savedOrCreateUserFavoritesCollection = async () =>+ (await savedUserFavoritesCollection()) ?? createFavoritesCollection();++/**+ * Return the user's own favorites collection, if any, present in the local+ * database.+ */+export const savedUserFavoritesCollection = async () => {+ const userID = ensureLocalUser().id;+ const collections = await savedCollections();+ return collections.find(+ (collection) =>+ // See: [Note: User and shared favorites]+ collection.type == "favorites" && collection.owner.id == userID,+ );+};++/**+ * Mark the provided {@link files} as the user's favorites by adding them to the+ * user's favorites collection.+ *+ * If the user doesn't yet have a favorites collection, it is created.+ *+ * Reads local state but does not modify it. The effects are on remote.+ */+export const addToFavoritesCollection = async (files: EnteFile[]) =>+ addToCollection(await savedOrCreateUserFavoritesCollection(), files);++export const removeFromFavoritesCollection = async (files: EnteFile[]) =>+ // Non-null assertion because if we get here and a favorites collection does+ // not already exist, then something is wrong.+ removeFromOwnCollection((await savedUserFavoritesCollection())!.id, files);++/**+ * Return the default hidden collection for the user if one is found in the+ * local database. Otherwise create a new one and return that.+ *+ * Reads local state but does not modify it. The effects are on remote.+ */+const savedOrCreateDefaultHiddenCollection = async () =>+ (await savedDefaultHiddenCollection()) ?? createDefaultHiddenCollection();++/**+ * Return the user's default hidden collection, if any, present in the+ * local database.+ */+const savedDefaultHiddenCollection = async () =>+ (await savedCollections()).find((collection) =>+ isDefaultHiddenCollection(collection),+ );++/**+ * Create a new collection with hidden visibility on remote, marking it as the+ * default hidden collection, and return its local representation.+ *+ * Remote only, does not modify local state.+ *+ * See also: [Note: Multiple "default" hidden collections].+ */+const createDefaultHiddenCollection = () =>+ createCollection(defaultHiddenCollectionName, "album", {+ subType: CollectionSubType.defaultHidden,+ visibility: ItemVisibility.hidden,+ });++/**+ * Return true if the provided collection is the default hidden collection.+ *+ * See also: [Note: Multiple "default" hidden collections].+ */+export const isDefaultHiddenCollection = (collection: Collection) =>+ collection.magicMetadata?.data.subType == CollectionSubType.defaultHidden;++/**+ * Extract the IDs of all the "default" hidden collections.+ *+ * [Note: Multiple "default" hidden collections].+ *+ * Normally, there is only expected to be one such collection. But to provide+ * clients laxity in synchronization, we don't enforce this and instead allow+ * for multiple such default hidden collections to exist.+ */+export const findDefaultHiddenCollectionIDs = (collections: Collection[]) =>+ new Set<number>(+ collections+ .filter(isDefaultHiddenCollection)+ .map((collection) => collection.id),+ );++/**+ * Return `true` if the given collection is hidden.+ *+ * Hidden collections are those that have their visibility set to hidden for+ * the current user (owner or sharee).+ *+ * In one instance, the isHiddenCollection function is called outside of a window, like+ * for the people tab's review suggestions, this function was trigged from a worker.+ * In that case, since the worker has no access to the localStorage, we need to pass the currentUserID+ * explicitly.+ */+export const isHiddenCollection = (+ collection: Collection,+ currentUserID?: number,+) => {+ const userID =+ currentUserID ?? (haveWindow() ? ensureLocalUser().id : undefined);++ if (userID === undefined) {+ throw new Error(+ "isHiddenCollection: currentUserID is required outside window context",+ );+ }+ if (collection.owner.id == userID) {+ return (+ collection.magicMetadata?.data.visibility == ItemVisibility.hidden+ );+ }+ return (+ collection.sharedMagicMetadata?.data.visibility == ItemVisibility.hidden+ );+};++/**+ * Return `true` if the given collection is archived.+ *+ * Archived collections are those that have their visibility set to hidden in the+ * collection's private magic metadata or per-sharee private metadata.+ */+export const isArchivedCollection = (collection: Collection) =>+ collection.magicMetadata?.data.visibility == ItemVisibility.archived ||+ collection.sharedMagicMetadata?.data.visibility == ItemVisibility.archived;++/**+ * Return `true` if the current user can remove files from all participants in+ * the given collection.+ *+ * This is true if the user is either:+ * - The owner of the collection, or+ * - An admin of the collection+ *+ * This is used to determine if the user can remove files added by other users+ * from a shared collection.+ */+export const canRemoveFilesFromAllParticipants = (collection: Collection) => {+ const userID = ensureLocalUser().id;+ if (collection.owner.id == userID) return true;+ // Check if the user is an admin of this collection+ const sharee = collection.sharees.find((s) => s.id == userID);+ return sharee?.role == "ADMIN";+};++/**+ * Hide the provided {@link files} by moving them to the default hidden+ * collection.+ *+ * If the default hidden collection does not already exist, it is created.+ *+ * Reads local state but does not modify it. The effects are on remote.+ */+export const hideFiles = async (files: EnteFile[]) =>+ moveToCollection(await savedOrCreateDefaultHiddenCollection(), files);++/**+ * Share the provided collection with another Ente user.+ *+ * Remote only, does not modify local state.+ *+ * @param collection The {@link Collection} to share.+ *+ * @param withUserEmail The email of the Ente user with whom to share it.+ *+ * @param role The desired role for the new participant.+ */+export const shareCollection = async (+ collection: Collection,+ withUserEmail: string,+ role: CollectionNewParticipantRole,+) => {+ const publicKey = await getPublicKey(withUserEmail);+ const encryptedKey = await boxSeal(collection.key, publicKey);++ ensureOk(+ await fetch(await apiURL("/collections/share"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({+ collectionID: collection.id,+ email: withUserEmail,+ role,+ encryptedKey,+ }),+ }),+ );+};++/**+ * Stop sharing a collection on remote with the given user.+ *+ * Remote only, does not modify local state.+ *+ * @param collectionID The ID of the collection to stop sharing with the user+ * having the given {@link email}.+ *+ * @param email The email of the Ente user with whom to stop sharing.+ */+export const unshareCollection = async (collectionID: number, email: string) =>+ ensureOk(+ await fetch(await apiURL("/collections/unshare"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ collectionID, email }),+ }),+ );++/**+ * The subset of public URL attributes that can be customized by the user when+ * creating a link.+ */+export type CreatePublicURLAttributes = Pick<+ Partial<PublicURL>,+ | "enableCollect"+ | "enableJoin"+ | "enableComment"+ | "validTill"+ | "deviceLimit"+>;++/**+ * Create a new public link for the given collection.+ *+ * Remote only, does not modify local state.+ *+ * @param collectionID The ID of the collection for which the public link should+ * be created.+ *+ * @param attributes Optional attributes to set when creating the public link.+ */+export const createPublicURL = async (+ collectionID: number,+ attributes?: CreatePublicURLAttributes,+): Promise<PublicURL> => {+ const enableComment = true;+ const res = await fetch(await apiURL("/collections/share-url"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ collectionID, enableComment, ...attributes }),+ });+ ensureOk(res);+ return z.object({ result: RemotePublicURL }).parse(await res.json()).result;+};++/**+ * The subset of public URL attributes that can be updated by the user after the+ * link has already been created.+ */+export type UpdatePublicURLAttributes = Omit<+ Partial<PublicURL>,+ "url" | "enablePassword"+> & { disablePassword?: boolean; passHash?: string };++/**+ * Update the attributes of an existing public link for a shared collection.+ *+ * Remote only, does not modify local state.+ *+ * @param collectionID The ID of the collection whose public link to update.+ *+ * @param updates The public link attributes to modify. Only attributes+ * corresponding to entries with non nullish values will be updated, all the+ * other existing attributes will remain unmodified.+ *+ * @returns the updated public URL.+ */+export const updatePublicURL = async (+ collectionID: number,+ updates: UpdatePublicURLAttributes,+): Promise<PublicURL> => {+ const res = await fetch(await apiURL("/collections/share-url"), {+ method: "PUT",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ collectionID, ...updates }),+ });+ ensureOk(res);+ return z.object({ result: RemotePublicURL }).parse(await res.json()).result;+};++/**+ * Delete the public link for the collection with given {@link collectionID}.+ *+ * Remote only, does not modify local state.+ */+export const deleteShareURL = async (collectionID: number) =>+ ensureOk(+ await fetch(await apiURL(`/collections/share-url/${collectionID}`), {+ method: "DELETE",+ headers: await authenticatedRequestHeaders(),+ }),+ );++/**+ * Leave a collection which had previously been shared with the user.+ *+ * Remote only, does not modify local state.+ *+ * @param collectionID The ID of the shared collection to leave.+ */+export const leaveSharedCollection = async (collectionID: number) =>+ ensureOk(+ await fetch(await apiURL(`/collections/leave/${collectionID}`), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ }),+ );++/**+ * Zod schema for a collection action (used for pending removal actions).+ */+const CollectionAction = z.object({+ collectionID: z.number(),+ fileID: z.number().nullish(),+});++type CollectionAction = z.infer<typeof CollectionAction>;++/**+ * Zod schema for the pending removal actions response.+ */+const PendingRemovalActionsResponse = z.object({+ actions: z.array(CollectionAction).nullish(),+});++/**+ * Fetch pending removal actions from remote.+ *+ * Remote only, does not modify local state.+ *+ * Pending removal actions indicate files that have been removed from a+ * collection by the owner or an admin, and should be moved to the user's+ * uncategorized collection if they exist locally.+ *+ * @returns A list of {@link CollectionAction} objects representing files that+ * should be moved to uncategorized.+ */+export const fetchPendingRemovalActions = async (): Promise<+ CollectionAction[]+> => {+ const res = await fetch(+ await apiURL("/collection-actions/pending-remove"),+ { headers: await authenticatedRequestHeaders() },+ );+ ensureOk(res);+ const { actions } = PendingRemovalActionsResponse.parse(await res.json());+ return actions ?? [];+};++/**+ * Process pending removal actions by moving affected files to the user's+ * uncategorized collection.+ *+ * This function fetches pending removal actions from remote, identifies which+ * files are affected, and moves them to the uncategorized collection. This+ * ensures that files removed from shared collections by owners/admins are not+ * lost but instead moved to a safe location.+ *+ * @param collections The current list of collections (used to find affected+ * files).+ *+ * Reads local state but does not modify it. The effects are on remote.+ */+export const movePendingRemovalActionsToUncategorized = async (+ collections: Collection[],+) => {+ const pendingActions = await fetchPendingRemovalActions();+ if (!pendingActions.length) return;++ // Group file IDs by collection ID+ const collectionToFileIDs = new Map<number, Set<number>>();+ for (const action of pendingActions) {+ if (action.fileID == null) continue;+ const fileIDs = collectionToFileIDs.get(action.collectionID);+ if (fileIDs) {+ fileIDs.add(action.fileID);+ } else {+ collectionToFileIDs.set(+ action.collectionID,+ new Set([action.fileID]),+ );+ }+ }++ if (!collectionToFileIDs.size) return;++ // Get all files from local storage+ const collectionFiles = await savedCollectionFiles();++ // Group files by collection ID for efficient lookup+ const filesByCollectionID = groupFilesByCollectionID(collectionFiles);++ // Create a map of collection ID to collection for quick lookup+ const collectionByID = new Map(collections.map((c) => [c.id, c]));++ // Lazily initialized target collections (only created if needed)+ let uncategorizedCollection: Collection | undefined;+ let defaultHiddenCollection: Collection | undefined;++ // Process each collection with pending removal actions+ for (const [+ collectionID,+ pendingFileIDs,+ ] of collectionToFileIDs.entries()) {+ const sourceCollection = collectionByID.get(collectionID);+ const filesInCollection = filesByCollectionID.get(collectionID) ?? [];+ const filesToMove = filesInCollection.filter((file) =>+ pendingFileIDs.has(file.id),+ );++ if (!filesToMove.length) continue;++ // Determine target collection based on whether source is hidden+ const isSourceHidden =+ sourceCollection && isHiddenCollection(sourceCollection);++ let targetCollection: Collection;+ if (isSourceHidden) {+ // Move files from hidden collections to default hidden collection+ if (!defaultHiddenCollection) {+ defaultHiddenCollection =+ collections.find(isDefaultHiddenCollection) ??+ (await createDefaultHiddenCollection());+ }+ targetCollection = defaultHiddenCollection;+ } else {+ // Move files from normal collections to uncategorized+ if (!uncategorizedCollection) {+ uncategorizedCollection =+ collections.find((c) => c.type == "uncategorized") ??+ (await createUncategorizedCollection());+ }+ targetCollection = uncategorizedCollection;+ }++ // Move files to target collection (this also removes them from the+ // source collection, which is the primary goal here)+ await moveFromCollection(collectionID, targetCollection, filesToMove);+ }+};++/**+ * Remove files from the uncategorized collection if they exist in other+ * user-owned albums.+ *+ * This is a cleanup operation that helps users remove duplicates from their+ * uncategorized collection. Files that exist both in uncategorized and in+ * other albums are moved out of uncategorized to one of those albums.+ *+ * Reads local state but does not modify it. The effects are on remote.+ *+ * @param uncategorizedCollection The user's uncategorized collection.+ */+export const cleanUncategorized = async (+ uncategorizedCollection: Collection,+): Promise<number> => {+ const userID = ensureLocalUser().id;+ const collections = await savedCollections();+ const collectionFiles = await savedCollectionFiles();++ // Get files in the uncategorized collection+ const uncategorizedFiles = collectionFiles.filter(+ (f) => f.collectionID == uncategorizedCollection.id,+ );++ if (!uncategorizedFiles.length) return 0;++ // Build a map from file ID to the collections it belongs to (excluding+ // uncategorized itself)+ const fileIDToCollectionIDs = new Map<number, number[]>();+ for (const file of collectionFiles) {+ if (file.collectionID == uncategorizedCollection.id) continue;+ const existing = fileIDToCollectionIDs.get(file.id);+ if (existing) {+ existing.push(file.collectionID);+ } else {+ fileIDToCollectionIDs.set(file.id, [file.collectionID]);+ }+ }++ // Filter to only user-owned normal collections (not hidden, not shared)+ const userOwnedCollectionIDs = new Set(+ collections+ .filter(+ (c) =>+ c.owner.id == userID &&+ c.type != "uncategorized" &&+ !isHiddenCollection(c),+ )+ .map((c) => c.id),+ );++ const collectionsByID = new Map(collections.map((c) => [c.id, c]));++ // Find files that exist in other user-owned collections+ const filesToClean = uncategorizedFiles.filter((file) => {+ const otherCollectionIDs = fileIDToCollectionIDs.get(file.id);+ if (!otherCollectionIDs) return false;+ // Check if any of these collections are user-owned normal collections+ return otherCollectionIDs.some((cid) =>+ userOwnedCollectionIDs.has(cid),+ );+ });++ if (!filesToClean.length) return 0;++ // Group files by their target collection for efficient batching+ const filesByTargetCollection = new Map<number, EnteFile[]>();+ for (const file of filesToClean) {+ const otherCollectionIDs = fileIDToCollectionIDs.get(file.id)!;+ const targetCollectionID = otherCollectionIDs.find((cid) =>+ userOwnedCollectionIDs.has(cid),+ );+ if (!targetCollectionID) continue;++ const existing = filesByTargetCollection.get(targetCollectionID) ?? [];+ existing.push(file);+ filesByTargetCollection.set(targetCollectionID, existing);+ }++ // Move files in batches per target collection+ let cleanedCount = 0;+ for (const [targetCollectionID, files] of filesByTargetCollection) {+ const targetCollection = collectionsByID.get(targetCollectionID);+ if (!targetCollection) continue;++ // Move files from uncategorized to the target collection.+ // This effectively removes them from uncategorized since they already+ // exist in the target.+ await moveFromCollection(+ uncategorizedCollection.id,+ targetCollection,+ files,+ );+ cleanedCount += files.length;+ }++ return cleanedCount;+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/comment.ts b/web/apps/albums/vendor/ente-new/photos/services/comment.tsnew file mode 100644index 0000000000..e6a182acb2--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/comment.ts@@ -0,0 +1,79 @@+import { encryptBox } from "ente-base/crypto";+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { z } from "zod";++/**+ * A decrypted comment.+ */+export interface Comment {+ id: string;+ collectionID: number;+ fileID?: number;+ parentCommentID?: string;+ /** User ID of the parent comment's author (only in feed responses). */+ parentCommentUserID?: number;+ userID: number;+ anonUserID?: string;+ /** The decrypted comment text. */+ text: string;+ isDeleted: boolean;+ createdAt: number;+ updatedAt: number;+}++/**+ * Add a comment to a file in a collection.+ *+ * @param collectionID The ID of the collection containing the file.+ * @param fileID The ID of the file to comment on.+ * @param text The comment text to encrypt.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @param parentCommentID Optional parent comment ID for replies.+ * @returns The ID of the created comment.+ */+export const addComment = async (+ collectionID: number,+ fileID: number,+ text: string,+ collectionKey: string,+ parentCommentID?: string,+): Promise<string> => {+ const { encryptedData: cipher, nonce } = await encryptBox(+ new TextEncoder().encode(text),+ collectionKey,+ );++ const res = await fetch(await apiURL("/comments"), {+ method: "POST",+ headers: {+ ...(await authenticatedRequestHeaders()),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ collectionID,+ fileID,+ cipher,+ nonce,+ parentCommentID,+ }),+ });+ ensureOk(res);+ const { id } = CreateCommentResponse.parse(await res.json());+ return id;+};++/**+ * Delete a comment by its ID.+ *+ * @param commentID The ID of the comment to delete.+ */+export const deleteComment = async (commentID: string): Promise<void> => {+ const res = await fetch(await apiURL(`/comments/${commentID}`), {+ method: "DELETE",+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+};++const CreateCommentResponse = z.object({ id: z.string() });diff --git a/web/apps/albums/vendor/ente-new/photos/services/file.ts b/web/apps/albums/vendor/ente-new/photos/services/file.tsnew file mode 100644index 0000000000..ac82b9eea3--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/file.ts@@ -0,0 +1,302 @@+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";+import { apiURL } from "ente-base/origins";+import type { EnteFile } from "ente-media/file";+import type {+ FilePrivateMagicMetadataData,+ FilePublicMagicMetadataData,+ ItemVisibility,+} from "ente-media/file-metadata";+import {+ createMagicMetadata,+ encryptMagicMetadata,+ type RemoteMagicMetadata,+} from "ente-media/magic-metadata";+import { batch } from "ente-utils/array";+import { savedHiddenCollections } from "./collection";+import { savedCollectionFiles } from "./photos-fdb";++/**+ * An reasonable but otherwise arbitrary number of items (e.g. files) to include+ * in a single API request.+ *+ * Remote will reject too big payloads, and requests which affect multiple items+ * (e.g. files when moving files to a collection, changing the visibility of+ * selected files) are expected to be batched to keep each request of a+ * reasonable size. By default, we break the request into batches of 1000.+ */+const requestBatchSize = 1000;++/**+ * Perform an operation on batches, serially.+ *+ * The given {@link items} are split into batches, each of+ * {@link requestBatchSize}. The provided operation is called on all these+ * batches, one after the other. When all the operations are complete, the+ * function returns with an array of results (one from each batch promise+ * resolution).+ *+ * @param items The arbitrary items to break into {@link requestBatchSize}+ * batches.+ *+ * @param op The operation to perform on each batch.+ *+ * @returns A promise for an array of results, one from each batch operation. If+ * any operations fails, then the promise rejects with its failure reason.+ */+export const batched = async <T, U>(+ items: T[],+ op: (batchItems: T[]) => Promise<U>,+): Promise<U[]> => {+ const result: U[] = [];+ for (const b of batch(items, requestBatchSize)) result.push(await op(b));+ return result;+};++/**+ * Return all files (from both normal and hidden collections) present in our+ * local database.+ */+export const computeAllCollectionFilesFromSaved = async () =>+ savedCollectionFiles();++/**+ * Return all normal (non-hidden) files present in our local database.+ *+ * The long name and the "compute" in it is to signal that this is not just a DB+ * read, and that it also does some potentially non-trivial computation.+ */+export const computeNormalCollectionFilesFromSaved = async (+ currentUserID?: number,+) => {+ const hiddenCollections = await savedHiddenCollections(currentUserID);+ const hiddenCollectionIDs = new Set(hiddenCollections.map((c) => c.id));++ const collectionFiles = await savedCollectionFiles();+ const hiddenFileIDs = new Set(+ collectionFiles+ .filter((f) => hiddenCollectionIDs.has(f.collectionID))+ .map((f) => f.id),+ );++ return collectionFiles.filter((f) => !hiddenFileIDs.has(f.id));+};++/**+ * Change the visibility (normal, archived, hidden) of a list of files on+ * remote.+ *+ * Remote only, does not modify local state.+ *+ * The visibility of an {@link EnteFile} is stored in its private magic+ * metadata, so this function in effect updates the private magic metadata of+ * the given files on remote.+ *+ * @param files The list of files whose visibility we want to change. All the+ * files will get their visibility updated to the new, provided, value.+ *+ * @param visibility The new visibility (normal, archived, hidden).+ */+export const updateFilesVisibility = async (+ files: EnteFile[],+ visibility: ItemVisibility,+) => batched(files, (b) => updateFilesPrivateMagicMetadata(b, { visibility }));++/**+ * Update the private magic metadata of a list of files on remote.+ *+ * Remote only, does not modify local state.+ *+ * @param file The list of files whose magic metadata we want to update. The+ * same updates will be applied to the magic metadata of all the files.+ *+ * The existing magic metadata of the provided files is used both to obtain the+ * current magic metadata version, and the existing contents on top of which the+ * updates are applied, so it is imperative that both these values are up to+ * sync with remote otherwise the update will fail.+ *+ * @param updates A non-empty subset of {@link FilePrivateMagicMetadataData}+ * entries.+ *+ * See: [Note: Magic metadata data cannot have nullish values]+ */+const updateFilesPrivateMagicMetadata = async (+ files: EnteFile[],+ updates: FilePrivateMagicMetadataData,+) =>+ putFilesMagicMetadata({+ metadataList: await Promise.all(+ files.map(async ({ id, key, magicMetadata }) => ({+ id,+ magicMetadata: await encryptMagicMetadata(+ createMagicMetadata(+ { ...magicMetadata?.data, ...updates },+ magicMetadata?.version,+ ),+ key,+ ),+ })),+ ),+ });++/**+ * The payload of the remote requests for updating the magic metadata of a+ * single item (file or collection).+ */+export interface UpdateMagicMetadataRequest {+ /**+ * File or collection ID+ */+ id: number;+ /**+ * The updated magic metadata.+ *+ * Remote usually enforces the following constraints when we're trying to+ * update already existing data.+ *+ * - The version should be same as the existing version.+ * - The count should be greater than or equal to the existing count.+ */+ magicMetadata: RemoteMagicMetadata;+}++/**+ * The payload of the remote requests for updating the magic metadata of a+ * multiple items.+ *+ * Currently this is only used by endpoints that update magic metadata for a+ * list of files.+ */+export interface UpdateMultipleMagicMetadataRequest {+ metadataList: UpdateMagicMetadataRequest[];+}++/**+ * Update the private magic metadata of a list of files on remote.+ */+const putFilesMagicMetadata = async (+ updateRequest: UpdateMultipleMagicMetadataRequest,+) =>+ ensureOk(+ await fetch(await apiURL("/files/magic-metadata"), {+ method: "PUT",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(updateRequest),+ }),+ );++/**+ * Update the file name of the provided file on remote.+ *+ * Remote only, does not modify local state.+ *+ * The file name of an {@link EnteFile} is stored in its public magic metadata,+ * so this function in effect updates the public magic metadata of the given+ * file on remote.+ *+ * @param file The file whose file name we want to change.+ *+ * @param newFileName The new file name of the file.+ */+export const updateFileFileName = (file: EnteFile, newFileName: string) =>+ updateFilePublicMagicMetadata(file, { editedName: newFileName });++/**+ * Update the caption associated with the provided file on remote.+ *+ * Remote only, does not modify local state.+ *+ * The caption of an {@link EnteFile} is stored in its public magic metadata, so+ * this function in effect updates the public magic metadata of the given file+ * on remote.+ *+ * @param file The file whose file name we want to change.+ *+ * @param caption The caption associated with the file.+ *+ * Fields in magic metadata cannot be removed after being added, so to reset the+ * caption to the default (no value) state pass a blank string.+ */+export const updateFileCaption = (file: EnteFile, caption: string) =>+ updateFilePublicMagicMetadata(file, { caption });++/**+ * Update the public magic metadata of a file on remote.+ *+ * Remote only, does not modify local state.+ *+ * @param file The list of files whose magic metadata we want to update.+ *+ * @param updates A non-empty but otherwise arbitrary subset of+ * {@link FilePrivateMagicMetadataData} entries.+ *+ * See: [Note: Magic metadata data cannot have nullish values]+ */+export const updateFilePublicMagicMetadata = async (+ file: EnteFile,+ updates: FilePublicMagicMetadataData,+) => updateFilesPublicMagicMetadata([file], updates);++/**+ * Update the public magic metadata of a list of files on remote.+ *+ * Remote only, does not modify local state.+ *+ * This is a variant of {@link updateFilePrivateMagicMetadata} that works with+ * the {@link pubMagicMetadata} of the given files.+ */+const updateFilesPublicMagicMetadata = async (+ files: EnteFile[],+ updates: FilePublicMagicMetadataData,+) =>+ putFilesPublicMagicMetadata({+ metadataList: await Promise.all(+ files.map(async ({ id, key, pubMagicMetadata }) => ({+ id,+ magicMetadata: await encryptMagicMetadata(+ createMagicMetadata(+ { ...pubMagicMetadata?.data, ...updates },+ pubMagicMetadata?.version,+ ),+ key,+ ),+ })),+ ),+ });++/**+ * Update the public magic metadata of a list of files on remote.+ */+const putFilesPublicMagicMetadata = async (+ updateRequest: UpdateMultipleMagicMetadataRequest,+) =>+ ensureOk(+ await fetch(await apiURL("/files/public-magic-metadata"), {+ method: "PUT",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(updateRequest),+ }),+ );++/**+ * Update the location (latitude and longitude) for a list of files on remote.+ *+ * Remote only, does not modify local state.+ *+ * The location of an {@link EnteFile} is stored in its public magic metadata+ * as the `lat` and `long` fields.+ *+ * @param files The list of files whose location we want to update.+ *+ * @param lat The new latitude.+ *+ * @param long The new longitude.+ */+export const updateFilesLocation = async (+ files: EnteFile[],+ lat: number,+ long: number,+): Promise<void> => {+ await batched(files, (b) =>+ updateFilesPublicMagicMetadata(b, { lat, long }),+ );+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/blob.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/blob.tsnew file mode 100644index 0000000000..01d884b472--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/blob.ts@@ -0,0 +1,143 @@+import { basename } from "ente-base/file-name";+import type { ElectronMLWorker } from "ente-base/types/ipc";+import { renderableImageBlob } from "ente-gallery/services/convert";+import { downloadManager } from "ente-gallery/services/download";+import {+ fileSystemUploadItemIfUnchanged,+ type ProcessableUploadItem,+ type UploadItem,+} from "ente-gallery/services/upload";+import { readStream } from "ente-gallery/utils/native-stream";+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";+export { createImageBitmapAndData } from "./decode";+export type { ImageBitmapAndData } from "./decode";++/**+ * Return a renderable blob (converting to JPEG if needed) for the given data.+ *+ * The blob from the relevant image component is either constructed using the+ * given {@link uploadItem} if present, otherwise it is downloaded from remote.+ *+ * - For images it is constructed from the image.+ * - For videos it is constructed from the thumbnail.+ * - For live photos it is constructed from the image component of the live+ * photo.+ *+ * Then, if the image blob we have seems to be something that the browser cannot+ * handle, we convert it into a JPEG blob so that it can subsequently be used to+ * create an {@link ImageBitmap}.+ *+ * @param file The {@link EnteFile} to index.+ *+ * @param uploadItem If we're called during the upload process, then this will+ * be set to the {@link FilesystemUploadItem} that was uploaded so that we can+ * directly use the on-disk file instead of needing to download the original.+ *+ * @param electron The {@link ElectronMLWorker} instance that we can use to IPC+ * with the Node.js layer.+ */+export const fetchRenderableBlob = async (+ file: EnteFile,+ puItem: ProcessableUploadItem | undefined,+ electron: ElectronMLWorker,+): Promise<Blob> =>+ (puItem+ ? await fetchRenderableUploadItemBlob(file, puItem, electron)+ : undefined) ?? (await fetchRenderableEnteFileBlob(file));++const fetchRenderableUploadItemBlob = async (+ file: EnteFile,+ puItem: ProcessableUploadItem,+ electron: ElectronMLWorker,+) => {+ if (file.metadata.fileType == FileType.video) {+ const thumbnailData = await downloadManager.thumbnailData(file);+ return new Blob([thumbnailData!]);+ } else {+ const uploadItem =+ puItem instanceof File+ ? puItem+ : await fileSystemUploadItemIfUnchanged(+ puItem,+ electron.fsStatMtime,+ );+ if (!uploadItem) {+ // The file on disk has changed. Fetch it from remote.+ return undefined;+ }+ const blob = await readNonVideoUploadItem(uploadItem, electron);+ return renderableImageBlob(blob, fileFileName(file));+ }+};++/**+ * Read the given {@link uploadItem} into an in-memory representation.+ *+ * See: [Note: Reading a UploadItem]+ *+ * @param uploadItem An {@link UploadItem} which we are trying to index. The+ * code calling us guarantees that this function will not be called for videos.+ *+ * @returns a web {@link File} that can be used to access the upload item's+ * contents.+ */+const readNonVideoUploadItem = async (+ uploadItem: UploadItem,+ electron: ElectronMLWorker,+): Promise<File> => {+ if (typeof uploadItem == "string" || Array.isArray(uploadItem)) {+ const { response, lastModifiedMs } = await readStream(+ electron,+ uploadItem,+ );+ const path = typeof uploadItem == "string" ? uploadItem : uploadItem[1];+ // This function will not be called for videos, and for images+ // it is reasonable to read the entire stream into memory here.+ return new File([await response.arrayBuffer()], basename(path), {+ lastModified: lastModifiedMs,+ });+ } else {+ if (uploadItem instanceof File) {+ return uploadItem;+ } else {+ return uploadItem.file;+ }+ }+};++/**+ * Return a renderable one (possibly involving a JPEG conversion) blob for the+ * given {@link EnteFile}.+ *+ * - The original will be downloaded if needed.+ * - The original will be converted to JPEG if needed.+ */+export const fetchRenderableEnteFileBlob = async (+ file: EnteFile,+): Promise<Blob> => {+ const fileType = file.metadata.fileType;+ if (fileType == FileType.video) {+ const thumbnailData = await downloadManager.thumbnailData(file);+ return new Blob([thumbnailData!]);+ }++ const originalFileBlob = await downloadManager.fileBlob(file, {+ background: true,+ });++ if (fileType == FileType.livePhoto) {+ const { imageFileName, imageData } = await decodeLivePhoto(+ fileFileName(file),+ originalFileBlob,+ );+ return renderableImageBlob(new Blob([imageData]), imageFileName);+ } else if (fileType == FileType.image) {+ return await renderableImageBlob(originalFileBlob, fileFileName(file));+ } else {+ // A layer above us should've already filtered these out.+ throw new Error(`Cannot index unsupported file type ${fileType}`);+ }+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/clip.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/clip.tsnew file mode 100644index 0000000000..7736c34134--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/clip.ts@@ -0,0 +1,179 @@+import type { ElectronMLWorker } from "ente-base/types/ipc";+import type { ImageBitmapAndData } from "./blob";+import { savedCLIPIndexes } from "./db";+import { dotProduct, norm } from "./math";+import type { CLIPMatches } from "./worker-types";++/**+ * The version of the CLIP indexing pipeline implemented by the current client.+ */+export const clipIndexingVersion = 1;++/**+ * The CLIP embedding for a file (and some metadata).+ *+ * See {@link FaceIndex} for a similar structure with more comprehensive+ * documentation.+ *+ * ---+ *+ * [Note: Natural language search using CLIP]+ *+ * CLIP (Contrastive Language-Image Pretraining) is a neural network trained on+ * (image, text) pairs. It can be thought of as two separate (but jointly+ * trained) encoders - one for images, and one for text - that both map to the+ * same embedding space.+ *+ * We use this for natural language search (aka "magic search") within the app:+ *+ * 1. Pre-compute an embedding for each image.+ *+ * 2. When the user searches, compute an embedding for the search term.+ *+ * 3. Use cosine similarity to find the find the image (embedding) closest to+ * the text (embedding).+ *+ * More details are in our [blog+ * post](https://ente.io/blog/image-search-with-clip-ggml/) that describes the+ * initial launch of this feature using the GGML runtime.+ *+ * Since the initial launch, we've switched over to another runtime,+ * [ONNX](https://onnxruntime.ai), started using Apple's+ * [MobileCLIP](https://github.com/apple/ml-mobileclip/) as the model and have+ * made other implementation changes, but the overall gist remains the same.+ *+ * Note that we don't train the neural network - we only use one of the publicly+ * available pre-trained neural networks for inference. These neural networks+ * are wholly defined by their connectivity and weights. ONNX, our ML runtimes,+ * loads these weights and instantiates a running network that we can use to+ * compute the embeddings.+ *+ * Theoretically, the same CLIP model can be loaded by different frameworks /+ * runtimes, but in practice each runtime has its own preferred format, and+ * there are also quantization tradeoffs. So there is a specific model (a binary+ * encoding of weights) tied to our current runtime that we use.+ *+ * To ensure that the embeddings, for the most part, can be shared, whenever+ * possible we try to ensure that all the preprocessing steps, and the model+ * itself, is the same across clients - web and mobile.+ */+export interface CLIPIndex {+ /**+ * The CLIP embedding.+ *+ * This is an array of 512 floating point values that represent the+ * embedding of the image in the same space where we'll embed the text so+ * that both of them can be compared using a cosine distance.+ */+ embedding: number[];+}++export type RemoteCLIPIndex = CLIPIndex & {+ /** An integral version number of the indexing algorithm / pipeline. */+ version: number;+ /** The UA for the client which generated this embedding. */+ client: string;+};++export type LocalCLIPIndex = CLIPIndex & {+ /** The ID of the {@link EnteFile} whose index this is. */+ fileID: number;+};++/**+ * Compute the CLIP embedding of a given {@link image}.+ *+ * This function is the third and fourth stage of the CLIP indexing pipeline.+ * The file goes through various stages:+ *+ * 1. Download the original (if needed).+ * 2. Convert (if needed) to obtain an image bitmap.+ * 3. Preprocess the image bitmap.+ * 4. Compute embeddings of this preprocessed image using ONNX/CLIP.+ *+ * Once all of it is done, it CLIP embedding (wrapped as a {@link CLIPIndex} so+ * that it can be saved locally and also uploaded to the user's remote storage+ * for use on their other devices).+ *+ * @param image The image bitmap (and its associated data) of the image file+ * whose CLIP embedding we're computing.+ *+ * @param electron The {@link ElectronMLWorker} instance that allows us to call+ * our Node.js layer to run the ONNX inference.+ */+export const indexCLIP = async (+ image: ImageBitmapAndData,+ electron: ElectronMLWorker,+): Promise<CLIPIndex> => ({+ embedding: Array.from(await computeEmbedding(image.data, electron)),+});++const computeEmbedding = async (+ imageData: ImageData,+ electron: ElectronMLWorker,+): Promise<Float32Array> => {+ // The image pre-preprocessing happens within the model itself, using ONNX+ // primitives. This is more performant and also saves us from having to+ // reinvent (say) the antialiasing wheels.+ const { height, width, data: pixelData } = imageData;+ const inputShape = [height, width, 4]; // [H, W, C]+ return normalized(+ await electron.computeCLIPImageEmbedding(pixelData, inputShape),+ );+};++const normalized = (embedding: Float32Array) => {+ const n = norm(embedding);+ return embedding.map((v) => v / n);+};++/**+ * Find the files whose CLIP embedding "matches" the given {@link searchPhrase}.+ *+ * The result can also be `undefined`, which indicates that the download for the+ * ML model is still in progress (trying again later should succeed).+ */+export const _clipMatches = async (+ searchPhrase: string,+ electron: ElectronMLWorker,+): Promise<CLIPMatches | undefined> => {+ const t = await electron.computeCLIPTextEmbeddingIfAvailable(searchPhrase);+ if (!t) return undefined;++ const textEmbedding = normalized(t);+ const items = (await cachedOrReadCLIPIndexes()).map(+ ({ fileID, embedding }) =>+ // The dot product gives us cosine similarity here since both the+ // vectors are already normalized.+ [fileID, dotProduct(embedding, textEmbedding)] as const,+ );+ // This score threshold was obtain heuristically. 0.2 generally gives solid+ // results, and around 0.15 we start getting many false positives (all this+ // is query dependent too).+ return new Map(items.filter(([, score]) => score >= 0.175));+};++let _cachedCLIPIndexes:+ | { fileID: number; embedding: Float32Array }[]+ | undefined;++/**+ * Cache the CLIP indexes when possible to avoid converting them from number[]+ * to Float32Array during the match for-loop itself.+ *+ * Converting them to Float32Array gives a big performance boost (See: [Note:+ * Dot product performance]). But doing that each time loses out on the+ * amortized benefit, so this temporary cache is as attempt to alleviate that.+ *+ * Use {@link clearCachedCLIPIndexes} to clear the cache (e.g. after indexing+ * produces potentially new CLIP indexes).+ */+const cachedOrReadCLIPIndexes = async () =>+ (_cachedCLIPIndexes ??= (await savedCLIPIndexes()).map(+ ({ fileID, embedding }) => ({+ fileID,+ embedding: new Float32Array(embedding),+ }),+ ));++export const clearCachedCLIPIndexes = () => (_cachedCLIPIndexes = undefined);diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/cluster.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/cluster.tsnew file mode 100644index 0000000000..d4e34378dc--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/cluster.ts@@ -0,0 +1,426 @@+import { assertionFailed } from "ente-base/assert";+import { newNonSecureID } from "ente-base/id-worker";+import log from "ente-base/log";+import type { EnteFile } from "ente-media/file";+import { fileCreationTime } from "ente-media/file-metadata";+import { wait } from "ente-utils/promise";+import {+ pullUserEntities,+ savedCGroups,+ updateOrCreateUserEntities,+} from "../user-entity";+import { savedFaceClusters, saveFaceClusters } from "./db";+import {+ faceDirection,+ fileIDFromFaceID,+ type Face,+ type FaceIndex,+} from "./face";+import { dotProduct } from "./math";++/**+ * A face cluster is an set of faces, and a nanoid to uniquely identify it.+ *+ * These are local only clusters. The clusters that are synced with remote are+ * part of "cgroup" user entities.+ */+export interface FaceCluster {+ /**+ * A nanoid for this cluster.+ */+ id: string;+ /**+ * An unordered set of ids of the faces that belong to this cluster.+ *+ * For ease of transportation and persistence this is an array, but it+ * should conceptually be thought of as a set.+ */+ faces: string[];+}++export interface ClusteringProgress {+ completed: number;+ total: number;+}++/** A {@link Face} annotated with data needed during clustering. */+export type ClusterFace = Omit<Face, "embedding"> & {+ embedding: Float32Array;+ isBadFace: boolean;+};++/**+ * Generates clusters from the given faces using a batched form of linear+ * clustering, with a bit of lookback (and a dollop of heuristics) to get the+ * clusters to merge across batches.+ *+ * The same logic is used for both the initial clustering and subsequent+ * incremental updates, just that the incremental updates will be much faster+ * since most of the files will be skipped (as they already have a cluster+ * assigned to them).+ *+ * [Note: Draining the event loop during clustering]+ *+ * The clustering is a synchronous operation, but we make it async to+ * artificially drain the worker's event loop after each mini-batch so that+ * other interactions with the worker (where this code runs) do not get stalled+ * while clustering is in progress.+ */+export const _clusterFaces = async (+ faceIndexes: FaceIndex[],+ localFiles: EnteFile[],+ onProgress: (progress: ClusteringProgress) => void,+) => {+ const startTime = Date.now();++ // A flattened array of filtered and annotated faces.+ const filteredFaces = [...enumerateFaces(faceIndexes)];++ // Sort faces temporally (a heuristic for better clusters), with the newest+ // ones first.+ const faces = sortFacesNewestOnesFirst(filteredFaces, localFiles);++ // Start with clusters we have currently (whether from remote or from a+ // previous local run, but preferring the remote ones).+ let clusters: FaceCluster[] = [];++ // Get the locally available remote cluster groups.+ const cgroups = await savedCGroups();++ // Sort them so that the latest ones are first.+ //+ // This is not expected to be something that makes a functional difference+ // but is done as part of a general theme of not making strict assumptions+ // about the clusters we get from remote.+ //+ // In particular, the same face ID can be in different clusters. In such+ // cases we should assign it arbitrarily assign it to the last cluster we+ // find it in. Such leeway is intentionally provided to allow clients some+ // slack in how they implement the sync without needing to make an blocking+ // API request for every user interaction.++ const sortedCGroups = cgroups.sort((a, b) => b.updatedAt - a.updatedAt);++ // Fill in clusters from remote cgroups, and also construct rejected lookup.+ const rejectedClusterIDsForFaceID = new Map<string, Set<string>>();+ for (const cgroup of sortedCGroups) {+ if (cgroup.data.rejectedFaceIDs.length == 0) {+ clusters = clusters.concat(cgroup.data.assigned);+ } else {+ const rejectedFaceIDs = new Set(cgroup.data.rejectedFaceIDs);+ clusters = clusters.concat(+ cgroup.data.assigned.map((cluster) => ({+ ...cluster,+ faces: cluster.faces.filter((f) => !rejectedFaceIDs.has(f)),+ })),+ );+ for (const faceID of rejectedFaceIDs) {+ const s = rejectedClusterIDsForFaceID.get(faceID) ?? new Set();+ cgroup.data.assigned.forEach(({ id }) => s.add(id));+ rejectedClusterIDsForFaceID.set(faceID, s);+ }+ }+ }++ // Add on the clusters we have available locally.+ clusters = clusters.concat(await savedFaceClusters());++ // For fast reverse lookup - map from the id of a face to the id of the+ // cluster to which it belongs.+ const faceIDToClusterID = new Map<string, string>();++ // For fast reverse lookup - map from the id of a face to the index of its+ // corresponding cluster in the clusters array.+ const faceIDToClusterIndex = new Map<string, number>();++ // Fill in the maps with the existing data. Since the remote clusters come+ // first, they'll be preferred over any existing local clusters for the same+ // face (as is the desired behaviour).++ for (const [i, cluster] of clusters.entries()) {+ for (const faceID of cluster.faces) {+ if (!faceIDToClusterID.has(faceID)) {+ faceIDToClusterID.set(faceID, cluster.id);+ faceIDToClusterIndex.set(faceID, i);+ }+ }+ }++ // IDs of the clusters which were modified. We use this information to+ // determine which cgroups need to be updated on remote.+ const modifiedClusterIDs = new Set<string>();++ const state = {+ faceIDToClusterID,+ faceIDToClusterIndex,+ clusters,+ modifiedClusterIDs,+ };++ // Process the faces in batches, but keep an overlap between batches to+ // allow "links" to form with existing clusters.++ const total = faces.length;+ const batchSize = 10000;+ const offsetIncrement = 7500;++ for (let offset = 0; offset < total; offset += offsetIncrement) {+ await clusterBatchLinear(+ faces.slice(offset, offset + batchSize),+ state,+ rejectedClusterIDsForFaceID,+ ({ completed }) =>+ onProgress({ completed: offset + completed, total }),+ );+ }++ const t = `(${Date.now() - startTime} ms)`;+ log.info(`Refreshed ${clusters.length} clusters from ${total} faces ${t}`);++ return { clusters, modifiedClusterIDs };+};++/**+ * A generator function that returns a stream of eligible {@link ClusterFace}s+ * by flattening all the the faces present in the given {@link faceIndices}.+ *+ * During this, it also converts the embeddings to Float32Arrays to speed up the+ * dot product calculations that will happen during clustering and attaches+ * other information that the clustering algorithm needs.+ */+function* enumerateFaces(faceIndices: FaceIndex[]) {+ for (const fi of faceIndices) {+ for (const face of fi.faces) {+ if (face.blur > 10 && face.score > 0.8) {+ yield {+ ...face,+ embedding: new Float32Array(face.embedding),+ isBadFace: isBadFace(face),+ };+ }+ }+ }+}++/**+ * Sort faces by the creation time of the file which contains them. The sorting+ * is in descending order, so the newest file is first.+ *+ * Sorting faces temporally is meant as a heuristic for better clusters.+ */+const sortFacesNewestOnesFirst = (+ faces: ClusterFace[],+ localFiles: EnteFile[],+) => {+ const localFileByID = new Map(localFiles.map((f) => [f.id, f]));+ const fileForFaceID = new Map(+ faces.map(({ faceID }) => [+ faceID,+ localFileByID.get(fileIDFromFaceID(faceID)!),+ ]),+ );++ // In unexpected scenarios, we might run clustering without having the+ // corresponding EnteFile available locally. This shouldn't happen, so log+ // an warning, but meanwhile let the clustering proceed by assigning such+ // files an arbitrary creationTime.+ const sortTimeForFace = ({ faceID }: { faceID: string }) => {+ const file = fileForFaceID.get(faceID);+ if (!file) {+ assertionFailed(`Did not find a local file for faceID ${faceID}`);+ return 0;+ }+ return fileCreationTime(file);+ };++ return faces.sort((a, b) => sortTimeForFace(b) - sortTimeForFace(a));+};++/**+ * Return true if the given face is above the minimum inclusion thresholds, but+ * is otherwise heuristically determined to be possibly spurious face detection.+ *+ * We apply a higher threshold when clustering such faces.+ */+const isBadFace = (face: Face) =>+ face.blur < 50 ||+ (face.blur < 200 && face.blur < 0.85) ||+ isSidewaysFace(face);++const isSidewaysFace = (face: Face) =>+ faceDirection(face.detection) != "straight";++/** Generate a new cluster ID. */+const newClusterID = () => newNonSecureID("cluster_");++interface ClusteringState {+ faceIDToClusterID: Map<string, string>;+ faceIDToClusterIndex: Map<string, number>;+ clusters: FaceCluster[];+ modifiedClusterIDs: Set<string>;+}++const clusterBatchLinear = async (+ batch: ClusterFace[],+ state: ClusteringState,+ rejectedClusterIDsForFaceID: Map<string, Set<string>>,+ onProgress: (progress: ClusteringProgress) => void,+) => {+ const [clusteredFaces, unclusteredFaces] = batch.reduce<+ [ClusterFace[], ClusterFace[]]+ >(+ (split, face) => (+ split[state.faceIDToClusterID.has(face.faceID) ? 0 : 1].push(face),+ split+ ),+ [[], []],+ );++ if (!unclusteredFaces.length) {+ // Optimization: early exit if nothing in batch is unclustered. In a+ // single test (so it might be not be a universal benefit) of ~8k faces,+ // it helped reduce the no-op time by 10x.+ onProgress({ completed: batch.length, total: batch.length });+ return;+ }++ // Sort the faces so that the already clustered ones are at the front.+ const faces = clusteredFaces.concat(unclusteredFaces);++ // For each face in the batch+ for (const [i, fi] of faces.entries()) {+ if (i % 100 == 0) {+ onProgress({ completed: i, total: batch.length });+ // See: [Note: Draining the event loop during clustering]+ await wait(0);+ }++ // If the face is already part of a cluster, then skip it.+ if (state.faceIDToClusterID.has(fi.faceID)) continue;++ const rejectedClusters = rejectedClusterIDsForFaceID.get(fi.faceID);++ // Find the nearest neighbour among the previous faces in this batch.+ let nnIndex: number | undefined;+ let nnCosineSimilarity = 0;+ for (let j = i - 1; j >= 0; j--) {+ // ! This is an O(n^2) loop, be careful when adding more code here.++ const fj = faces[j]!;++ // The vectors are already normalized, so we can directly use their+ // dot product as their cosine similarity.+ const csim = dotProduct(fi.embedding, fj.embedding);+ if (csim <= nnCosineSimilarity) continue;++ const threshold = fj.isBadFace ? 0.84 : 0.76;+ if (csim < threshold) continue;++ // Don't add the face back to a cluster it has been rejected from.+ if (rejectedClusters) {+ const cjx = state.faceIDToClusterIndex.get(fj.faceID);+ if (cjx !== undefined) {+ const cj = state.clusters[cjx]!;+ if (rejectedClusters.has(cj.id)) {+ continue;+ }+ }+ }++ nnIndex = j;+ nnCosineSimilarity = csim;+ }++ if (nnIndex !== undefined) {+ // Found a neighbour close enough, add ourselves to its cluster.+ const nnFace = faces[nnIndex]!;+ const nnClusterIndex = state.faceIDToClusterIndex.get(+ nnFace.faceID,+ )!;+ const nnCluster = state.clusters[nnClusterIndex]!;++ state.faceIDToClusterID.set(fi.faceID, nnCluster.id);+ state.faceIDToClusterIndex.set(fi.faceID, nnClusterIndex);+ nnCluster.faces.push(fi.faceID);+ state.modifiedClusterIDs.add(nnCluster.id);+ } else {+ // No neighbour within the threshold. Create a new cluster.+ const clusterID = newClusterID();+ const clusterIndex = state.clusters.length;+ const cluster = { id: clusterID, faces: [fi.faceID] };++ state.faceIDToClusterID.set(fi.faceID, cluster.id);+ state.faceIDToClusterIndex.set(fi.faceID, clusterIndex);+ state.clusters.push(cluster);+ state.modifiedClusterIDs.add(cluster.id);+ }+ }+};++/**+ * Use the output of the clustering phase to (a) update any remote cgroups that+ * have changed, and (b) update our locally persisted clusters.+ *+ * @param masterKey The user's master key (as a base64 string), required for+ * updating the cgroups on remote if needed.+ */+export const reconcileClusters = async (+ clusters: FaceCluster[],+ modifiedClusterIDs: Set<string>,+ masterKey: string,+) => {+ // Index clusters by their ID for fast lookup.+ const clusterByID = new Map(clusters.map((c) => [c.id, c]));++ // Get the existing remote cluster groups.+ const cgroups = await savedCGroups();++ // Find the cgroups that have changed since we started.+ const changedCGroups = cgroups+ .map((cgroup) => {+ for (const cluster of cgroup.data.assigned) {+ if (modifiedClusterIDs.has(cluster.id)) {+ return {+ ...cgroup,+ data: {+ ...cgroup.data,+ // Map assigned cluster IDs to latest cluster objects.+ // If any referenced cluster is missing, throw to avoid+ // silently losing data or writing nulls to remote.+ assigned: cgroup.data.assigned.map(({ id }) => {+ const c = clusterByID.get(id);+ if (!c)+ throw new Error(+ `reconcileClusters: missing cluster ${id} for cgroup ${cgroup.id}`,+ );+ return c;+ }),+ },+ };+ }+ }+ return undefined;+ })+ .filter((g) => !!g);++ // Update remote if needed.+ if (changedCGroups.length) {+ await updateOrCreateUserEntities("cgroup", changedCGroups, masterKey);+ log.info(`Updated ${changedCGroups.length} remote cgroups`);+ }++ // Find which clusters are part of remote cgroups.+ const isRemoteClusterID = new Set<string>();+ for (const cgroup of cgroups) {+ for (const cluster of cgroup.data.assigned)+ isRemoteClusterID.add(cluster.id);+ }++ // Locally save clusters that are not part of any remote cgroup.+ await saveFaceClusters(+ clusters.filter(({ id }) => !isRemoteClusterID.has(id)),+ );++ // Refresh our local state if we'd updated remote.+ if (changedCGroups.length) await pullUserEntities("cgroup", masterKey);+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/crop.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/crop.tsnew file mode 100644index 0000000000..b6dcf31cfe--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/crop.ts@@ -0,0 +1,114 @@+import { blobCache } from "ente-base/blob-cache";+import type { EnteFile } from "ente-media/file";+import { fetchRenderableEnteFileBlob } from "./blob";+import { type Box, type FaceIndex } from "./face";+import { clamp } from "./math";++/**+ * Regenerate and locally save face crops for faces in the given file.+ *+ * Face crops (the rectangular regions of the original image where a particular+ * face was detected) are not stored on remote and are generated on demand. On+ * the client where the indexing occurred, they get generated during the face+ * indexing pipeline itself. But we need to regenerate them locally if the user+ * views that item on any other client.+ *+ * @param file The {@link EnteFile} whose face crops we want to generate.+ *+ * @param faceIndex The {@link FaceIndex} containing information about the faces+ * detected in the given image.+ *+ * The generated face crops are saved in a local cache and can subsequently be+ * retrieved from the {@link BlobCache} named "face-crops".+ */+export const regenerateFaceCrops = async (+ file: EnteFile,+ faceIndex: FaceIndex,+) => {+ const renderableBlob = await fetchRenderableEnteFileBlob(file);+ const imageBitmap = await createImageBitmap(renderableBlob);++ try {+ await saveFaceCrops(imageBitmap, faceIndex);+ } finally {+ imageBitmap.close();+ }+};++/**+ * Extract and locally save the face crops (the rectangle of the original image+ * that contain the detected face) for each of the faces detected in an image.+ *+ * @param imageBitmap The original image.+ *+ * @param faceIndex The {@link FaceIndex} containing information about the faces+ * detected in the given image.+ *+ * The face crops are saved in a local cache and can subsequently be retrieved+ * from the {@link BlobCache} named "face-crops".+ */+export const saveFaceCrops = async (+ imageBitmap: ImageBitmap,+ faceIndex: FaceIndex,+) => {+ const cache = await blobCache("face-crops");++ return Promise.all(+ faceIndex.faces.map(({ faceID, detection }) =>+ extractFaceCrop(imageBitmap, detection.box).then((b) =>+ cache.put(faceID, b),+ ),+ ),+ );+};++/**+ * Return the face crops corresponding to each of the given face detections.+ *+ * @param imageBitmap The original image.+ *+ * @param faceBox A box (a rectangle relative to the image size) marking the+ * bounds of face in the given image.+ *+ * @returns a JPEG blob.+ */+export const extractFaceCrop = (imageBitmap: ImageBitmap, faceBox: Box) => {+ const { width: imageWidth, height: imageHeight } = imageBitmap;++ // The faceBox coordinates are normalized 0-1 relative to the image size,+ // and we need to convert them back to absolute values first.+ const faceX = faceBox.x * imageWidth;+ const faceY = faceBox.y * imageHeight;+ const faceWidth = faceBox.width * imageWidth;+ const faceHeight = faceBox.height * imageHeight;++ // Calculate the crop values by adding some padding around the face and+ // making sure it's centered.+ const regularPadding = 0.4;+ const minimumPadding = 0.1;+ const xCrop = faceX - faceWidth * regularPadding;+ const xOvershoot = Math.abs(Math.min(0, xCrop)) / faceWidth;+ const widthCrop =+ faceWidth * (1 + 2 * regularPadding) -+ 2 * Math.min(xOvershoot, regularPadding - minimumPadding) * faceWidth;++ const yCrop = faceY - faceHeight * regularPadding;+ const yOvershoot = Math.abs(Math.min(0, yCrop)) / faceHeight;+ const heightCrop =+ faceHeight * (1 + 2 * regularPadding) -+ 2 * Math.min(yOvershoot, regularPadding - minimumPadding) * faceHeight;++ // Prevent the crop from going out of image bounds.+ const x = clamp(xCrop, 0, imageWidth);+ const y = clamp(yCrop, 0, imageHeight);+ const width = clamp(widthCrop, 0, imageWidth - x);+ const height = clamp(heightCrop, 0, imageHeight - y);++ const canvas = new OffscreenCanvas(width, height);+ const ctx = canvas.getContext("2d")!;+ ctx.imageSmoothingQuality = "high";++ ctx.drawImage(imageBitmap, x, y, width, height, 0, 0, width, height);++ return canvas.convertToBlob({ type: "image/jpeg", quality: 0.8 });+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/db.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/db.tsnew file mode 100644index 0000000000..6372313f6f--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/db.ts@@ -0,0 +1,406 @@+import log from "ente-base/log";+import { deleteDB, openDB, type DBSchema } from "idb";+import type { LocalCLIPIndex } from "./clip";+import type { FaceCluster } from "./cluster";+import type { LocalFaceIndex } from "./face";++/**+ * ML DB schema.+ *+ * The "ML" database is made of the lower level "index" object stores, and+ * higher level "cluster" object stores.+ *+ * The index related object stores are the following:+ *+ * - "file-status": Contains {@link FileStatus} objects, one for each+ * {@link EnteFile} that the ML subsystem knows about. Periodically (and when+ * required), this is synced with the list of files that the current client+ * knows about locally.+ *+ * - "face-index": Contains {@link LocalFaceIndex} objects, either indexed+ * locally or fetched from remote.+ *+ * - "clip-index": Contains {@link LocalCLIPIndex} objects, either indexed+ * locally or fetched from remote.+ *+ * These three stores are keyed by {@link fileID}. The "file-status" contains+ * book-keeping about the indexing process (whether or not a file needs+ * indexing, or if there were errors doing so), while the other stores contain+ * the actual indexing results.+ *+ * In tandem, these serve as the underlying storage for the indexes maintained+ * in the ML database.+ *+ * The face clustering related object stores are the following:+ *+ * - "face-cluster": Contains {@link FaceCluster} objects, one for each cluster+ * of faces that either the clustering algorithm produced locally. It is+ * indexed by the cluster ID.+ */+interface MLDBSchema extends DBSchema {+ "file-status": {+ key: number;+ value: FileStatus;+ indexes: { status: FileStatus["status"] };+ };+ "face-index": { key: number; value: LocalFaceIndex };+ "clip-index": { key: number; value: LocalCLIPIndex };+ "face-cluster": { key: string; value: FaceCluster };+ /* Unused */+ "cluster-group": { key: string; value: unknown };+}++interface FileStatus {+ /** The ID of the {@link EnteFile} whose indexing status we represent. */+ fileID: number;+ /**+ * The status of the file.+ *+ * - "indexable" - This file is something that we can index, but it is yet+ * to be indexed.+ *+ * - "indexed" - We have a corresponding entry for this file in the+ * "face-index" _and_ "clip-index" object stores (either indexed locally+ * or fetched from remote).+ *+ * - "failed" - Indexing was attempted but failed.+ *+ * If you haven't heard the word "index" to the point of zoning out, we also+ * have a (IndexedDB) "index" on the status field to allow us to efficiently+ * select or count {@link fileIDs} that fall into various buckets.+ */+ status: "indexable" | "indexed" | "failed";+ /**+ * The number of times attempts to index this file failed.+ *+ * It counts failure across all index types.+ *+ * This is guaranteed to be `0` for files with status "indexed".+ */+ failureCount: number;+}++/**+ * A lazily-created, cached promise for ML DB.+ *+ * See: [Note: Caching IDB instances in separate execution contexts].+ */+let _mlDB: ReturnType<typeof openMLDB> | undefined;++const openMLDB = async () => {+ const db = await openDB<MLDBSchema>("ml", 1, {+ upgrade(db, oldVersion, newVersion) {+ log.info(`Upgrading ML DB ${oldVersion} => ${newVersion}`);+ if (oldVersion < 1) {+ db.createObjectStore("file-status", {+ keyPath: "fileID",+ }).createIndex("status", "status");+ db.createObjectStore("face-index", { keyPath: "fileID" });+ db.createObjectStore("clip-index", { keyPath: "fileID" });+ db.createObjectStore("face-cluster", { keyPath: "id" });+ db.createObjectStore("cluster-group", { keyPath: "id" });+ }+ },+ blocking() {+ log.info(+ "Another client is attempting to open a new version of ML DB",+ );+ db.close();+ _mlDB = undefined;+ },+ blocked() {+ log.warn(+ "Waiting for an existing client to close their connection so that we can update the ML DB version",+ );+ },+ terminated() {+ log.warn("Our connection to ML DB was unexpectedly terminated");+ _mlDB = undefined;+ },+ });+ return db;+};++/**+ * @returns a lazily created, cached connection to the ML DB.+ */+const mlDB = () => (_mlDB ??= openMLDB());++/**+ * Clear any data stored in the ML DB.+ *+ * This is meant to be called during logout on the main thread.+ */+export const clearMLDB = async () => {+ try {+ if (_mlDB) (await _mlDB).close();+ } catch (e) {+ log.warn("Ignoring error when trying to close ML DB", e);+ }+ _mlDB = undefined;++ return deleteDB("ml", {+ blocked() {+ log.warn(+ "Waiting for an existing client to close their connection so that we can delete the ML DB",+ );+ },+ });+};++/**+ * Save the given {@link faceIndex} and {@link clipIndex}, and mark the file as+ * "indexed".+ *+ * This function adds a new entry for the indexes, overwriting any existing ones+ * (No merging is performed, the existing entry is unconditionally overwritten).+ * The file status is also updated to "indexed", and the failure count is reset+ * to 0.+ */+export const saveIndexes = async (+ faceIndex: LocalFaceIndex,+ clipIndex: LocalCLIPIndex,+) => {+ const { fileID } = faceIndex;++ const db = await mlDB();+ const tx = db.transaction(+ ["file-status", "face-index", "clip-index"],+ "readwrite",+ );++ await Promise.all([+ tx+ .objectStore("file-status")+ .put({ fileID, status: "indexed", failureCount: 0 }),+ tx.objectStore("face-index").put(faceIndex),+ tx.objectStore("clip-index").put(clipIndex),+ tx.done,+ ]);+};++/**+ * Return a new object suitable for use as the initial value of the entry for a+ * file in the file status store.+ */+const newFileStatus = (fileID: number): FileStatus => ({+ fileID,+ status: "indexable",+ failureCount: 0,+});++/**+ * Return the {@link FaceIndex}, if any, for {@link fileID}.+ */+export const savedFaceIndex = async (fileID: number) => {+ const db = await mlDB();+ return db.get("face-index", fileID);+};++/**+ * Return all face indexes present locally.+ */+export const savedFaceIndexes = async () => {+ const db = await mlDB();+ return await db.getAll("face-index");+};++/**+ * Return all CLIP indexes present locally.+ */+export const savedCLIPIndexes = async () => {+ const db = await mlDB();+ return await db.getAll("clip-index");+};++/**+ * Record the existence of a file so that entities in the ML universe know about+ * it (e.g. can index it if it is new and it needs indexing).+ *+ * @param fileID The ID of an {@link EnteFile}.+ *+ * This function does not overwrite existing entries. If an entry already exists+ * for the given {@link fileID} (e.g. if it was indexed and+ * {@link saveFaceIndex} called with the result), its existing status remains+ * unperturbed.+ */+export const addFileEntry = async (fileID: number) => {+ const db = await mlDB();+ const tx = db.transaction("file-status", "readwrite");+ if ((await tx.store.getKey(fileID)) === undefined)+ await tx.store.put(newFileStatus(fileID));+ return tx.done;+};++/**+ * Update entries in ML DB to align with the state of local files outside ML DB.+ *+ * @param localFileIDs IDs of all the files that the client is aware of.+ *+ * @param localTrashFilesIDs IDs of all the files in trash.+ *+ * This function then updates the state of file entries in ML DB to the be in+ * sync with these provided local file IDs.+ *+ * - Files that are present locally but are not yet in ML DB get a fresh entry+ * in face DB (and are marked as indexable).+ *+ * - Files that are not present locally (nor are in trash) but still exist in ML+ * DB are removed from ML DB (including any indexes).+ *+ * - Files that are not present locally but are in the trash are retained in ML+ * DB if their status is "indexed"; otherwise they too are removed. This is to+ * prevent churn, otherwise they'll get unnecessarily reindexed again if the+ * user restores them from trash before permanent deletion.+ */+export const updateAssumingLocalFiles = async (+ localFileIDs: number[],+ localTrashFilesIDs: Set<number>,+) => {+ const db = await mlDB();+ const tx = db.transaction(+ ["file-status", "face-index", "clip-index"],+ "readwrite",+ );+ const fdbFileIDs = await tx.objectStore("file-status").getAllKeys();+ const fdbIndexedFileIDs = await tx+ .objectStore("file-status")+ .getAllKeys(IDBKeyRange.only("indexed"));++ const local = new Set(localFileIDs);+ const fdb = new Set(fdbFileIDs);+ const fdbIndexed = new Set(fdbIndexedFileIDs);++ const newFileIDs = localFileIDs.filter((id) => !fdb.has(id));+ const removedFileIDs = fdbFileIDs.filter((id) => {+ if (local.has(id)) return false; // Still exists.+ if (localTrashFilesIDs.has(id)) {+ // Exists in trash.+ if (fdbIndexed.has(id)) {+ // But is already indexed, so let it be.+ return false;+ }+ }+ return true; // Remove.+ });++ await Promise.all(+ [+ newFileIDs.map((id) =>+ tx.objectStore("file-status").put(newFileStatus(id)),+ ),+ removedFileIDs.map((id) =>+ tx.objectStore("file-status").delete(id),+ ),+ removedFileIDs.map((id) => tx.objectStore("face-index").delete(id)),+ removedFileIDs.map((id) => tx.objectStore("clip-index").delete(id)),+ tx.done,+ ].flat(),+ );+};++/**+ * Remove all "failed" file status entries so that we again attempt to index+ * those files the next time indexing happens.+ */+export const resetFailedFileStatuses = async () => {+ const db = await mlDB();+ const tx = db.transaction("file-status", "readwrite");+ const ids = await tx.store+ .index("status")+ .getAllKeys(IDBKeyRange.only("failed"));++ await Promise.all([ids.map((id) => tx.store.delete(id)), tx.done].flat());+};++/**+ * Return the count of files that can be indexed, have been indexed, and which+ * have been marked as having failed when attempting to index them.+ *+ * The total number of files that are within the purview of the indexer is+ * indexable + indexed + failed.+ */+export const savedIndexCounts = async () => {+ const db = await mlDB();+ const tx = db.transaction("file-status", "readonly");+ const indexableCount = await tx.store+ .index("status")+ .count(IDBKeyRange.only("indexable"));+ const indexedCount = await tx.store+ .index("status")+ .count(IDBKeyRange.only("indexed"));+ const failedCount = await tx.store+ .index("status")+ .count(IDBKeyRange.only("failed"));+ return { indexableCount, indexedCount, failedCount };+};++/**+ * Return a list of fileIDs that need to be indexed.+ *+ * This list is from the universe of the file IDs that the face DB knows about+ * (we can use {@link addFileEntry} to inform it about new files). From this+ * universe, we filter out fileIDs the files corresponding to which have already+ * been indexed, or which should be ignored.+ *+ * @param count Limit the result to up to {@link count} items. If there are more+ * than {@link count} items present, the files with the higher file IDs (which+ * can be taken as a approximate for their creation order) are preferred.+ */+export const readNextIndexableFileIDs = async (count: number) => {+ const db = await mlDB();+ const tx = db.transaction("file-status", "readonly");+ let cursor = await tx.store+ .index("status")+ .openKeyCursor(IDBKeyRange.only("indexable"), "prev");+ const result: number[] = [];+ while (cursor && count > 0) {+ result.push(cursor.primaryKey);+ cursor = await cursor.continue();+ count -= 1;+ }+ return result;+};++/**+ * Increment the failure count associated with the given {@link fileID}.+ *+ * @param fileID The ID of an {@link EnteFile}.+ *+ * If an entry does not exist yet for the given file, then a new one is created+ * and its failure count is set to 1. Otherwise the failure count of the+ * existing entry is incremented.+ *+ * This count is across all different types of indexing (face, CLIP) that happen+ * on the file.+ */+export const markIndexingFailed = async (fileID: number) => {+ const db = await mlDB();+ const tx = db.transaction("file-status", "readwrite");+ const fileStatus = (await tx.store.get(fileID)) ?? newFileStatus(fileID);+ fileStatus.status = "failed";+ fileStatus.failureCount = fileStatus.failureCount + 1;+ await Promise.all([tx.store.put(fileStatus), tx.done]);+};++/**+ * Return all face clusters present locally.+ */+export const savedFaceClusters = async () => {+ const db = await mlDB();+ return db.getAll("face-cluster");+};++/**+ * Replace the face clusters stored locally with the given ones.+ *+ * This function deletes all entries from the face cluster object store, and+ * then inserts the given {@link clusters} into it.+ */+export const saveFaceClusters = async (clusters: FaceCluster[]) => {+ const db = await mlDB();+ const tx = db.transaction("face-cluster", "readwrite");+ await tx.store.clear();+ await Promise.all(clusters.map((cluster) => tx.store.put(cluster)));+ return tx.done;+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/decode.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/decode.tsnew file mode 100644index 0000000000..66844b01dc--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/decode.ts@@ -0,0 +1,41 @@+/**+ * An image bitmap and its RGBA data.+ *+ * This is data structure containing data about an image in all formats that the+ * various indexing steps need.+ */+export interface ImageBitmapAndData {+ /**+ * An {@link ImageBitmap} from the original or converted image.+ *+ * This bitmap is constructed from the original file's data if the+ * browser knows how to handle it; otherwise we first convert it to a JPEG+ * and then create the bitmap from that.+ */+ bitmap: ImageBitmap;+ /**+ * The RGBA {@link ImageData} of the {@link bitmap}, obtained by rendering+ * it to an offscreen canvas.+ */+ data: ImageData;+}++/**+ * Create an {@link ImageBitmap} from the given {@link imageBlob}, and return+ * both the image bitmap and its {@link ImageData}.+ */+export const createImageBitmapAndData = async (+ imageBlob: Blob,+): Promise<ImageBitmapAndData> => {+ const imageBitmap = await createImageBitmap(imageBlob);++ const { width, height } = imageBitmap;++ // Use an OffscreenCanvas to get the bitmap's data.+ const offscreenCanvas = new OffscreenCanvas(width, height);+ const ctx = offscreenCanvas.getContext("2d")!;+ ctx.drawImage(imageBitmap, 0, 0, width, height);+ const imageData = ctx.getImageData(0, 0, width, height);++ return { bitmap: imageBitmap, data: imageData };+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/face.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/face.tsnew file mode 100644index 0000000000..e3f4c4a94b--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/face.ts@@ -0,0 +1,831 @@+import { assertionFailed } from "ente-base/assert";+import type { ElectronMLWorker } from "ente-base/types/ipc";+import type { EnteFile } from "ente-media/file";+import { Matrix } from "ml-matrix";+import { getSimilarityTransformation } from "similarity-transformation";+import type { ImageBitmapAndData } from "./blob";+import {+ grayscaleIntMatrixFromNormalized2List,+ warpAffineFloat32List,+} from "./image";+import { clamp } from "./math";++/**+ * The version of the face indexing pipeline implemented by the current client.+ */+export const faceIndexingVersion = 1;++/**+ * The faces in a file (and an embedding for each of them).+ *+ * This interface describes the format of face related data (aka "face index")+ * for a file. This is the common subset that is present in both the fields that+ * are persisted on remote ({@link RemoteFaceIndex}) and locally+ * ({@link LocalFaceIndex}).+ *+ * - Face detections and embeddings (collectively called as the face index) are+ * generated by the current client when uploading a file, or when noticing a+ * file which doesn't yet have a face index. They are then uploaded (E2EE) to+ * remote, and the relevant bits also saved locally in the ML DB for+ * subsequent lookup or clustering.+ *+ * - This face index is then fetched by subsequent clients to avoid them having+ * to reindex (indexing faces is a costly operation, esp. for mobile clients).+ *+ * In both these scenarios (whether generated locally or fetched from remote),+ * we end up with an some data described by this {@link FaceIndex} interface. We+ * modify it slightly, adding envelopes, when saving them locally or uploading+ * them to remote - those variations are described by the {@link LocalFaceIndex}+ * and {@link RemoteFaceIndex} types respectively.+ */+export interface FaceIndex {+ /**+ * The width (in px) of the image (file).+ *+ * Having the image dimensions here is useful since the coordinates inside+ * the {@link Face}s are all normalized (0 to 1) to the width and height of+ * the image.+ */+ width: number;+ /**+ * The height (in px) of the image (file).+ */+ height: number;+ /**+ * The list of faces (and their embeddings) detected in the file.+ *+ * Each of the items is a {@link Face}, containing the result of a face+ * detection, and an embedding for that detected face.+ */+ faces: Face[];+}++export type RemoteFaceIndex = FaceIndex & {+ /**+ * An integral version number of the indexing algorithm / pipeline.+ *+ * [Note: Embedding versions]+ *+ * Embeddings have an associated version so it is possible for us to make+ * backward compatible updates to the indexing process on newer clients.+ *+ * Clients agree out of band what a particular version means, and guarantee+ * that an embedding with a particular version will be the same (to epsilon+ * cosine similarity) irrespective of the client that indexed the file.+ *+ * If we bump the version of same model (say when indexing on a newer+ * client), we will do it in a manner that older client will be able to+ * consume the response. The schema should not change in non-additive+ * manners. For example, say if we improve blur detection, older client+ * should just consume embeddings with a newer version and not try to index+ * the file again locally.+ *+ * When fetching from remote, if we get an embedding with version that is+ * older than the version the client supports, then the client should ignore+ * it. This way, the file will get reindexed locally and an embedding with a+ * newer version will also get saved to remote.+ *+ * In the case where the changes are not backward compatible and can only be+ * consumed by clients by making code changes, then we will introduce a new+ * subtype (top level key) in the derived data.+ */+ version: number;+ /**+ * The UA for the client which generated this embedding.+ */+ client: string;+};++export type LocalFaceIndex = FaceIndex & {+ /**+ * The ID of the {@link EnteFile} whose index this is.+ *+ * This is used as the primary key when storing the index locally (An+ * {@link EnteFile} is guaranteed to have its fileID be unique in the+ * namespace of the user. Even if someone shares a file with the user the+ * user will get a file entry with a fileID unique to them).+ */+ fileID: number;+};++/**+ * A face detected in a file, and an embedding for this detected face.+ *+ * During face indexing, we first detect all the faces in a particular file.+ * Then for each such detected region, we compute an embedding of that part of+ * the file. Together, this detection region and the emedding travel together in+ * this {@link Face} interface.+ */+export interface Face {+ /**+ * A unique identifier for the face.+ *+ * This ID is guaranteed to be unique for all the faces detected in all the+ * files for the user. In particular, each file can have multiple faces but+ * they all will get their own unique {@link faceID}.+ *+ * This ID is also meant to be stable across reindexing. That is, if the+ * same algorithm and hyperparameters are used to reindex the file, then it+ * should result in the same face IDs. This allows us leeway in letting+ * unnecessary reindexing happen in rare cases without invalidating the+ * clusters that rely on the presence of the given face ID.+ *+ * Finally, this face ID is not completely opaque. It consists of underscore+ * separated components, the first of which is the ID of the+ * {@link EnteFile} to which this face belongs. Client code can rely on this+ * structure and can parse it if needed using {@link fileIDFromFaceID}.+ */+ faceID: string;+ /**+ * The face detection. Describes the region within the image that was+ * detected to be a face, and a set of landmarks (e.g. "eyes") of the+ * detection.+ *+ * All coordinates are relative to and normalized by the image's dimension,+ * i.e. they have been normalized to lie between 0 and 1, with 0 being the+ * left (or top) and 1 being the width (or height) of the image.+ */+ detection: {+ /**+ * The region within the image that contains the face.+ *+ * All coordinates and sizes are between 0 and 1, normalized by the+ * dimensions of the image.+ * */+ box: Box;+ /**+ * Face "landmarks", e.g. eyes.+ *+ * The exact landmarks and their order depends on the face detection+ * algorithm being used.+ *+ * The coordinatesare between 0 and 1, normalized by the dimensions of+ * the image.+ */+ landmarks: Point[];+ };+ /**+ * An correctness probability (0 to 1) that the face detection algorithm+ * gave to the detection. Higher values are better.+ */+ score: number;+ /**+ * The computed blur for the detected face.+ *+ * The exact semantics and range for these (floating point) values depend on+ * the face indexing algorithm / pipeline version being used.+ * */+ blur: number;+ /**+ * An embedding for the face.+ *+ * This is an opaque numeric (signed floating point) vector whose semantics+ * and length depend on the version of the face indexing algorithm /+ * pipeline that we are using. However, within a set of embeddings with the+ * same version, the property is that two such embedding vectors will be+ * "cosine similar" to each other if they are both faces of the same person.+ */+ embedding: number[];+}++/** The x and y coordinates of a point. */+export interface Point {+ x: number;+ y: number;+}++/** The dimensions of something, say an image. */+export interface Dimensions {+ width: number;+ height: number;+}++/** A rectangle given by its top left coordinates and dimensions. */+export interface Box {+ /** The x coordinate of the the top left (xMin). */+ x: number;+ /** The y coordinate of the top left (yMin). */+ y: number;+ /** The width of the box. */+ width: number;+ /** The height of the box. */+ height: number;+}++/**+ * Extract the fileID of the {@link EnteFile} to which the face belongs from its+ * faceID.+ */+export const fileIDFromFaceID = (faceID: string) => {+ const fileID = parseInt(faceID.split("_")[0] ?? "");+ if (isNaN(fileID)) {+ assertionFailed(`Ignoring attempt to parse invalid faceID ${faceID}`);+ return undefined;+ }+ return fileID;+};++/**+ * Index faces in the given file.+ *+ * This function is the entry point to the face indexing pipeline. The file goes+ * through various stages:+ *+ * 1. Detect faces using ONNX/YOLO+ * 2. Align the face rectangles, compute blur.+ * 3. Compute embeddings using ONNX/MFNT for the detected face (crop).+ *+ * Once all of it is done, it returns the face rectangles and embeddings so that+ * they can be saved locally (for offline use), and also uploaded to the user's+ * remote storage so that their other devices can download them instead of+ * needing to reindex.+ *+ * @param file The {@link EnteFile} to index.+ *+ * @param image The file's contents.+ *+ * @param electron The {@link ElectronMLWorker} instance that allows us to call+ * our Node.js layer to run the ONNX inference.+ */+export const indexFaces = async (+ file: EnteFile,+ { data: imageData }: ImageBitmapAndData,+ electron: ElectronMLWorker,+): Promise<FaceIndex> => ({+ width: imageData.width,+ height: imageData.height,+ faces: await indexFaces_(file.id, imageData, electron),+});++const indexFaces_ = async (+ fileID: number,+ imageData: ImageData,+ electron: ElectronMLWorker,+): Promise<Face[]> => {+ const { width, height } = imageData;+ const imageDimensions = { width, height };++ const yoloFaceDetections = await detectFaces(imageData, electron);+ const partialResult = yoloFaceDetections.map(+ ({ box, landmarks, score }) => {+ const faceID = makeFaceID(fileID, box, imageDimensions);+ const detection = { box, landmarks };+ return { faceID, detection, score };+ },+ );++ const allAlignments = partialResult.map(({ detection }) =>+ computeFaceAlignment(detection),+ );++ let embeddings: Float32Array[] = [];+ let blurs: number[] = [];++ // Process the faces in batches of 50 to:+ //+ // 1. Avoid memory pressure (as on ONNX 1.80.0, we can reproduce a crash if+ // we try to compute MFNet embeddings for a file with ~280 faces).+ //+ // 2. Reduce the time the main (Node.js) process is unresponsive (whenever+ // the main thread of the Node.js process is CPU bound, the renderer also+ // becomes unresponsive since events are routed via the main process).+ //+ const batchSize = 50;+ for (let i = 0; i < yoloFaceDetections.length; i += batchSize) {+ const alignments = allAlignments.slice(i, i + batchSize);+ const detections = partialResult+ .slice(i, i + batchSize)+ .map((f) => f.detection);++ const alignedFacesData = convertToMobileFaceNetInput(+ imageData,+ alignments,+ );++ embeddings = embeddings.concat(+ await computeEmbeddings(alignedFacesData, electron),+ );+ blurs = blurs.concat(detectBlur(alignedFacesData, detections));+ }++ return partialResult.map(({ faceID, detection, score }, i) => ({+ faceID,+ detection: normalizeByImageDimensions(detection, imageDimensions),+ score,+ blur: blurs[i]!,+ embedding: Array.from(embeddings[i]!),+ }));+};++/**+ * Detect faces in the given image.+ *+ * The model used is YOLOv5Face, running in an ONNX runtime.+ */+const detectFaces = async (+ imageData: ImageData,+ electron: ElectronMLWorker,+): Promise<YOLOFaceDetection[]> => {+ // The image pre-preprocessing happens within the model itself, using ONNX+ // primitives. This is more performant and also saves us from having to+ // reinvent (say) the antialiasing wheels.+ const {+ height: imageHeight,+ width: imageWidth,+ data: pixelData,+ } = imageData;+ const inputShape = [imageHeight, imageWidth, 4]; // [H, W, C]++ const scaledSize = getScaledSize(imageWidth, imageHeight);+ const yoloOutput = await electron.detectFaces(pixelData, inputShape);+ const faces = filterExtractDetectionsFromYOLOOutput(yoloOutput);+ const faceDetections = transformYOLOFaceDetections(+ faces,+ {+ x: (640 - scaledSize.width) / 2,+ y: (640 - scaledSize.height) / 2,+ width: scaledSize.width,+ height: scaledSize.height,+ },+ { x: 0, y: 0, width: imageWidth, height: imageHeight },+ );++ return faceDetections;+};++/**+ * Calculate image scaling done inside ONNX model run preprocessing. Needed to+ * correct the output.+ */+const getScaledSize = (imageWidth: number, imageHeight: number) => {+ const requiredWidth = 640;+ const requiredHeight = 640;++ const scale = Math.min(+ requiredWidth / imageWidth,+ requiredHeight / imageHeight,+ );+ const scaledWidth = clamp(Math.round(imageWidth * scale), 0, requiredWidth);+ const scaledHeight = clamp(+ Math.round(imageHeight * scale),+ 0,+ requiredHeight,+ );+ return { width: scaledWidth, height: scaledHeight };+};++interface YOLOFaceDetection {+ box: Box;+ landmarks: Point[];+ score: number;+}++/**+ * Extract detected faces from the YOLOv5Face's output.+ *+ * Only detections that exceed a minimum score are returned.+ *+ * @param rows A Float32Array of shape [25200, 16], where each row represents a+ * face detection.+ *+ * YOLO detects a fixed number of faces, 25200, always from the input it is+ * given. Each detection is a "row" of 16 bytes, containing the bounding box,+ * score, and landmarks of the detection.+ *+ * We prune out detections with a score lower than our threshold. However, we+ * will still be left with some overlapping detections of the same face: these+ * we will deduplicate in {@link removeDuplicateDetections}.+ */+const filterExtractDetectionsFromYOLOOutput = (+ rows: Float32Array,+): YOLOFaceDetection[] => {+ const faces: YOLOFaceDetection[] = [];+ // Iterate over each row.+ for (let i = 0; i < rows.length; i += 16) {+ const score = rows[i + 4]!;+ if (score < 0.7) continue;++ const xCenter = rows[i]!;+ const yCenter = rows[i + 1]!;+ const width = rows[i + 2]!;+ const height = rows[i + 3]!;+ const x = xCenter - width / 2.0; // topLeft+ const y = yCenter - height / 2.0; // topLeft++ const leftEyeX = rows[i + 5]!;+ const leftEyeY = rows[i + 6]!;+ const rightEyeX = rows[i + 7]!;+ const rightEyeY = rows[i + 8]!;+ const noseX = rows[i + 9]!;+ const noseY = rows[i + 10]!;+ const leftMouthX = rows[i + 11]!;+ const leftMouthY = rows[i + 12]!;+ const rightMouthX = rows[i + 13]!;+ const rightMouthY = rows[i + 14]!;++ const box = { x, y, width, height };+ const landmarks = [+ { x: leftEyeX, y: leftEyeY },+ { x: rightEyeX, y: rightEyeY },+ { x: noseX, y: noseY },+ { x: leftMouthX, y: leftMouthY },+ { x: rightMouthX, y: rightMouthY },+ ];+ faces.push({ box, landmarks, score });+ }+ return faces;+};++/**+ * Transform the given {@link yoloFaceDetections} from their coordinate system in+ * which they were detected ({@link inBox}) back to the coordinate system of the+ * original image ({@link toBox}).+ */+const transformYOLOFaceDetections = (+ yoloFaceDetections: YOLOFaceDetection[],+ inBox: Box,+ toBox: Box,+): YOLOFaceDetection[] => {+ const scaleX = toBox.width / inBox.width;+ const scaleY = toBox.height / inBox.height;+ const translateX = toBox.x - inBox.x;+ const translateY = toBox.y - inBox.y;++ const correctDetections: YOLOFaceDetection[] = [];++ for (const detection of yoloFaceDetections) {+ const score = detection.score;++ const box = detection.box;+ box.x = (box.x + translateX) * scaleX;+ box.y = (box.y + translateY) * scaleY;+ box.width *= scaleX;+ box.height *= scaleY;++ const landmarks = detection.landmarks;+ landmarks.forEach((p) => {+ p.x = (p.x + translateX) * scaleX;+ p.y = (p.y + translateY) * scaleY;+ });+ correctDetections.push({ score, box, landmarks });+ }++ return correctDetections;+};++const makeFaceID = (fileID: number, box: Box, image: Dimensions) => {+ const part = (v: number) => clamp(v, 0.0, 0.999999).toFixed(5).substring(2);+ const xMin = part(box.x / image.width);+ const yMin = part(box.y / image.height);+ const xMax = part((box.x + box.width) / image.width);+ const yMax = part((box.y + box.height) / image.height);+ return [`${fileID}`, xMin, yMin, xMax, yMax].join("_");+};++interface FaceAlignment {+ /**+ * An affine transformation matrix (rotation, translation, scaling) to align+ * the face extracted from the image.+ */+ affineMatrix: number[][];+ /**+ * The bounding box of the transformed box.+ *+ * The affine transformation shifts the original detection box a new,+ * transformed, box (possibly rotated). This property is the bounding box+ * of that transformed box. It is in the coordinate system of the original,+ * full, image on which the detection occurred.+ */+ boundingBox: Box;+}++/**+ * Compute and return an {@link FaceAlignment} for the given face detection.+ *+ * @param faceDetection A geometry indicating a face detected in an image.+ */+const computeFaceAlignment = (faceDetection: FaceDetection): FaceAlignment =>+ computeFaceAlignmentUsingSimilarityTransform(+ faceDetection,+ normalizeLandmarks(idealMobileFaceNetLandmarks, mobileFaceNetFaceSize),+ );++/**+ * The ideal location of the landmarks (eye etc) that the MobileFaceNet+ * embedding model expects.+ */+const idealMobileFaceNetLandmarks: [number, number][] = [+ [38.2946, 51.6963],+ [73.5318, 51.5014],+ [56.0252, 71.7366],+ [41.5493, 92.3655],+ [70.7299, 92.2041],+];++const normalizeLandmarks = (+ landmarks: [number, number][],+ faceSize: number,+): [number, number][] =>+ landmarks.map(([x, y]) => [x / faceSize, y / faceSize]);++const computeFaceAlignmentUsingSimilarityTransform = (+ faceDetection: FaceDetection,+ alignedLandmarks: [number, number][],+): FaceAlignment => {+ const landmarksMat = new Matrix(+ faceDetection.landmarks+ .map((p) => [p.x, p.y])+ .slice(0, alignedLandmarks.length),+ ).transpose();+ const alignedLandmarksMat = new Matrix(alignedLandmarks).transpose();++ const simTransform = getSimilarityTransformation(+ landmarksMat,+ alignedLandmarksMat,+ );++ const RS = Matrix.mul(simTransform.rotation, simTransform.scale);+ const TR = simTransform.translation;++ const affineMatrix = [+ [RS.get(0, 0), RS.get(0, 1), TR.get(0, 0)],+ [RS.get(1, 0), RS.get(1, 1), TR.get(1, 0)],+ [0, 0, 1],+ ];++ const size = 1 / simTransform.scale;+ const meanTranslation = simTransform.toMean.sub(0.5).mul(size);+ const centerMat = simTransform.fromMean.sub(meanTranslation);+ const center = { x: centerMat.get(0, 0), y: centerMat.get(1, 0) };++ const boundingBox = {+ x: center.x - size / 2,+ y: center.y - size / 2,+ width: size,+ height: size,+ };++ return { affineMatrix, boundingBox };+};++const convertToMobileFaceNetInput = (+ imageData: ImageData,+ faceAlignments: FaceAlignment[],+): Float32Array => {+ const faceSize = mobileFaceNetFaceSize;+ const faceData = new Float32Array(+ faceAlignments.length * faceSize * faceSize * 3,+ );+ for (let i = 0; i < faceAlignments.length; i++) {+ const { affineMatrix } = faceAlignments[i]!;+ const faceDataOffset = i * faceSize * faceSize * 3;+ warpAffineFloat32List(+ imageData,+ affineMatrix,+ faceSize,+ faceData,+ faceDataOffset,+ );+ }+ return faceData;+};++interface FaceDetection {+ box: Box;+ landmarks: Point[];+}++/**+ * Laplacian blur detection.+ *+ * Return an array of detected blur values, one for each face detection in+ * {@link faceDetections}. The face data is taken from the slice of+ * {@link alignedFacesData} corresponding to the face of {@link faceDetections}.+ */+const detectBlur = (+ alignedFacesData: Float32Array,+ faceDetections: FaceDetection[],+): number[] =>+ faceDetections.map((d, i) => {+ const faceImage = grayscaleIntMatrixFromNormalized2List(+ alignedFacesData,+ i,+ mobileFaceNetFaceSize,+ mobileFaceNetFaceSize,+ );+ return matrixVariance(applyLaplacian(faceImage, faceDirection(d)));+ });++type FaceDirection = "left" | "right" | "straight";++export const faceDirection = ({ landmarks }: FaceDetection): FaceDirection => {+ const leftEye = landmarks[0]!;+ const rightEye = landmarks[1]!;+ const nose = landmarks[2]!;+ const leftMouth = landmarks[3]!;+ const rightMouth = landmarks[4]!;++ const eyeDistanceX = Math.abs(rightEye.x - leftEye.x);+ const eyeDistanceY = Math.abs(rightEye.y - leftEye.y);+ const mouthDistanceY = Math.abs(rightMouth.y - leftMouth.y);++ const faceIsUpright =+ Math.max(leftEye.y, rightEye.y) + 0.5 * eyeDistanceY < nose.y &&+ nose.y + 0.5 * mouthDistanceY < Math.min(leftMouth.y, rightMouth.y);++ const noseStickingOutLeft =+ nose.x < Math.min(leftEye.x, rightEye.x) &&+ nose.x < Math.min(leftMouth.x, rightMouth.x);++ const noseStickingOutRight =+ nose.x > Math.max(leftEye.x, rightEye.x) &&+ nose.x > Math.max(leftMouth.x, rightMouth.x);++ const noseCloseToLeftEye =+ Math.abs(nose.x - leftEye.x) < 0.2 * eyeDistanceX;+ const noseCloseToRightEye =+ Math.abs(nose.x - rightEye.x) < 0.2 * eyeDistanceX;++ if (noseStickingOutLeft || (faceIsUpright && noseCloseToLeftEye)) {+ return "left";+ } else if (noseStickingOutRight || (faceIsUpright && noseCloseToRightEye)) {+ return "right";+ }++ return "straight";+};++/**+ * Return a new image by applying a Laplacian blur kernel to each pixel.+ */+const applyLaplacian = (+ image: number[][],+ direction: FaceDirection,+): number[][] => {+ const paddedImage = padImage(image, direction);+ const numRows = paddedImage.length - 2;+ const numCols = paddedImage[0]!.length - 2;++ // Create an output image initialized to 0.+ const outputImage = Array.from(+ { length: numRows },+ () => new Array(numCols).fill(0) as number[],+ );++ // Define the Laplacian kernel.+ const kernel = [+ [0, 1, 0],+ [1, -4, 1],+ [0, 1, 0],+ ];++ // Apply the kernel to each pixel+ for (let i = 0; i < numRows; i++) {+ for (let j = 0; j < numCols; j++) {+ let sum = 0;+ for (let ki = 0; ki < 3; ki++) {+ for (let kj = 0; kj < 3; kj++) {+ sum += paddedImage[i + ki]![j + kj]! * kernel[ki]![kj]!;+ }+ }+ // Adjust the output value if necessary (e.g., clipping).+ outputImage[i]![j] = sum;+ }+ }++ return outputImage;+};++const padImage = (image: number[][], direction: FaceDirection): number[][] => {+ const removeSideColumns = 56; /* must be even */++ const numRows = image.length;+ const numCols = image[0]!.length;+ const paddedNumCols = numCols + 2 - removeSideColumns;+ const paddedNumRows = numRows + 2;++ // Create a new matrix with extra padding.+ const paddedImage = Array.from(+ { length: paddedNumRows },+ () => new Array(paddedNumCols).fill(0) as number[],+ );++ if (direction == "straight") {+ // Copy original image into the center of the padded image.+ for (let i = 0; i < numRows; i++) {+ for (let j = 0; j < paddedNumCols - 2; j++) {+ paddedImage[i + 1]![j + 1] =+ image[i]![j + Math.round(removeSideColumns / 2)]!;+ }+ }+ } else if (direction == "left") {+ // If the face is facing left, we only take the right side of the face+ // image.+ for (let i = 0; i < numRows; i++) {+ for (let j = 0; j < paddedNumCols - 2; j++) {+ paddedImage[i + 1]![j + 1] = image[i]![j + removeSideColumns]!;+ }+ }+ } else {+ // If the face is facing right, we only take the left side of the face+ // image.+ for (let i = 0; i < numRows; i++) {+ for (let j = 0; j < paddedNumCols - 2; j++) {+ paddedImage[i + 1]![j + 1] = image[i]![j]!;+ }+ }+ }++ // Reflect padding+ // - Top and bottom rows+ for (let j = 1; j <= paddedNumCols - 2; j++) {+ // Top row+ paddedImage[0]![j] = paddedImage[2]![j]!;+ // Bottom row+ paddedImage[numRows + 1]![j] = paddedImage[numRows - 1]![j]!;+ }+ // - Left and right columns+ for (let i = 0; i < numRows + 2; i++) {+ // Left column+ paddedImage[i]![0] = paddedImage[i]![2]!;+ // Right column+ paddedImage[i]![paddedNumCols - 1] =+ paddedImage[i]![paddedNumCols - 3]!;+ }++ return paddedImage;+};++const matrixVariance = (matrix: number[][]): number => {+ const numRows = matrix.length;+ const numCols = matrix[0]!.length;+ const totalElements = numRows * numCols;++ // Calculate the mean.+ let mean = 0;+ matrix.forEach((row) => {+ row.forEach((value) => {+ mean += value;+ });+ });+ mean /= totalElements;++ // Calculate the variance.+ let variance = 0;+ matrix.forEach((row) => {+ row.forEach((value) => {+ const diff: number = value - mean;+ variance += diff * diff;+ });+ });+ variance /= totalElements;++ return variance;+};++const mobileFaceNetFaceSize = 112;+const mobileFaceNetEmbeddingSize = 192;++/**+ * Compute embeddings for the given {@link faceData}.+ *+ * The model used is MobileFaceNet, running in an ONNX runtime.+ */+const computeEmbeddings = async (+ faceData: Float32Array,+ electron: ElectronMLWorker,+): Promise<Float32Array[]> => {+ const outputData = await electron.computeFaceEmbeddings(faceData);++ const embeddingSize = mobileFaceNetEmbeddingSize;+ const embeddings = new Array<Float32Array>(+ outputData.length / embeddingSize,+ );+ for (let i = 0; i < embeddings.length; i++) {+ embeddings[i] = new Float32Array(+ outputData.slice(i * embeddingSize, (i + 1) * embeddingSize),+ );+ }+ return embeddings;+};++/**+ * Convert the coordinates to between 0-1, normalized by the image's dimensions.+ */+const normalizeByImageDimensions = (+ faceDetection: FaceDetection,+ { width, height }: Dimensions,+): FaceDetection => {+ const oldBox: Box = faceDetection.box;+ const box = {+ x: oldBox.x / width,+ y: oldBox.y / height,+ width: oldBox.width / width,+ height: oldBox.height / height,+ };+ const landmarks = faceDetection.landmarks.map((l) => ({+ x: l.x / width,+ y: l.y / height,+ }));+ return { box, landmarks };+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/image.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/image.tsnew file mode 100644index 0000000000..8d91842922--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/image.ts@@ -0,0 +1,238 @@+import { Matrix, inverse } from "ml-matrix";+import { clamp } from "./math";++const pixelRGBA = (+ imageData: Uint8ClampedArray,+ width: number,+ height: number,+ x: number,+ y: number,+) => {+ if (x < 0 || x >= width || y < 0 || y >= height) {+ return { r: 114, g: 114, b: 114, a: 0 };+ }+ const index = (y * width + x) * 4;+ return {+ r: imageData[index]!,+ g: imageData[index + 1]!,+ b: imageData[index + 2]!,+ a: imageData[index + 3]!,+ };+};++/**+ * Returns the pixel value (RGB) at the given coordinates ({@link fx},+ * {@link fy}) using bicubic interpolation.+ */+export const pixelRGBBicubic = (+ fx: number,+ fy: number,+ imageData: Uint8ClampedArray,+ imageWidth: number,+ imageHeight: number,+) => {+ // Clamp to image boundaries.+ fx = clamp(fx, 0, imageWidth - 1);+ fy = clamp(fy, 0, imageHeight - 1);++ const x = Math.trunc(fx) - (fx >= 0.0 ? 0 : 1);+ const px = x - 1;+ const nx = x + 1;+ const ax = x + 2;+ const y = Math.trunc(fy) - (fy >= 0.0 ? 0 : 1);+ const py = y - 1;+ const ny = y + 1;+ const ay = y + 2;+ const dx = fx - x;+ const dy = fy - y;++ const cubic = (+ dx: number,+ ipp: number,+ icp: number,+ inp: number,+ iap: number,+ ) =>+ icp ++ 0.5 *+ (dx * (-ipp + inp) ++ dx * dx * (2 * ipp - 5 * icp + 4 * inp - iap) ++ dx * dx * dx * (-ipp + 3 * icp - 3 * inp + iap));++ const icc = pixelRGBA(imageData, imageWidth, imageHeight, x, y);++ const ipp =+ px < 0 || py < 0+ ? icc+ : pixelRGBA(imageData, imageWidth, imageHeight, px, py);+ const icp =+ px < 0 ? icc : pixelRGBA(imageData, imageWidth, imageHeight, x, py);+ const inp =+ py < 0 || nx >= imageWidth+ ? icc+ : pixelRGBA(imageData, imageWidth, imageHeight, nx, py);+ const iap =+ ax >= imageWidth || py < 0+ ? icc+ : pixelRGBA(imageData, imageWidth, imageHeight, ax, py);++ const ip0 = cubic(dx, ipp.r, icp.r, inp.r, iap.r);+ const ip1 = cubic(dx, ipp.g, icp.g, inp.g, iap.g);+ const ip2 = cubic(dx, ipp.b, icp.b, inp.b, iap.b);+ // const ip3 = cubic(dx, ipp.a, icp.a, inp.a, iap.a);++ const ipc =+ px < 0 ? icc : pixelRGBA(imageData, imageWidth, imageHeight, px, y);+ const inc =+ nx >= imageWidth+ ? icc+ : pixelRGBA(imageData, imageWidth, imageHeight, nx, y);+ const iac =+ ax >= imageWidth+ ? icc+ : pixelRGBA(imageData, imageWidth, imageHeight, ax, y);++ const ic0 = cubic(dx, ipc.r, icc.r, inc.r, iac.r);+ const ic1 = cubic(dx, ipc.g, icc.g, inc.g, iac.g);+ const ic2 = cubic(dx, ipc.b, icc.b, inc.b, iac.b);+ // const ic3 = cubic(dx, ipc.a, icc.a, inc.a, iac.a);++ const ipn =+ px < 0 || ny >= imageHeight+ ? icc+ : pixelRGBA(imageData, imageWidth, imageHeight, px, ny);+ const icn =+ ny >= imageHeight+ ? icc+ : pixelRGBA(imageData, imageWidth, imageHeight, x, ny);+ const inn =+ nx >= imageWidth || ny >= imageHeight+ ? icc+ : pixelRGBA(imageData, imageWidth, imageHeight, nx, ny);+ const ian =+ ax >= imageWidth || ny >= imageHeight+ ? icc+ : pixelRGBA(imageData, imageWidth, imageHeight, ax, ny);++ const in0 = cubic(dx, ipn.r, icn.r, inn.r, ian.r);+ const in1 = cubic(dx, ipn.g, icn.g, inn.g, ian.g);+ const in2 = cubic(dx, ipn.b, icn.b, inn.b, ian.b);+ // const in3 = cubic(dx, ipn.a, icn.a, inn.a, ian.a);++ const ipa =+ px < 0 || ay >= imageHeight+ ? icc+ : pixelRGBA(imageData, imageWidth, imageHeight, px, ay);+ const ica =+ ay >= imageHeight+ ? icc+ : pixelRGBA(imageData, imageWidth, imageHeight, x, ay);+ const ina =+ nx >= imageWidth || ay >= imageHeight+ ? icc+ : pixelRGBA(imageData, imageWidth, imageHeight, nx, ay);+ const iaa =+ ax >= imageWidth || ay >= imageHeight+ ? icc+ : pixelRGBA(imageData, imageWidth, imageHeight, ax, ay);++ const ia0 = cubic(dx, ipa.r, ica.r, ina.r, iaa.r);+ const ia1 = cubic(dx, ipa.g, ica.g, ina.g, iaa.g);+ const ia2 = cubic(dx, ipa.b, ica.b, ina.b, iaa.b);+ // const ia3 = cubic(dx, ipa.a, ica.a, ina.a, iaa.a);++ const c0 = Math.trunc(clamp(cubic(dy, ip0, ic0, in0, ia0), 0, 255));+ const c1 = Math.trunc(clamp(cubic(dy, ip1, ic1, in1, ia1), 0, 255));+ const c2 = Math.trunc(clamp(cubic(dy, ip2, ic2, in2, ia2), 0, 255));+ // const c3 = cubic(dy, ip3, ic3, in3, ia3);++ return { r: c0, g: c1, b: c2 };+};++/**+ * Transform {@link inputData} starting at {@link inputStartIndex}.+ *+ * @param imageData The {@link ImageData} from which these alignments originate.+ */+export const warpAffineFloat32List = (+ imageData: ImageData,+ faceAlignmentAffineMatrix: number[][],+ faceSize: number,+ inputData: Float32Array,+ inputStartIndex: number,+): void => {+ const { width, height, data: pixelData } = imageData;++ const transformationMatrix = faceAlignmentAffineMatrix.map((row) =>+ row.map((val) => (val != 1.0 ? val * faceSize : 1.0)),+ ); // 3x3++ const A: Matrix = new Matrix([+ [transformationMatrix[0]![0]!, transformationMatrix[0]![1]!],+ [transformationMatrix[1]![0]!, transformationMatrix[1]![1]!],+ ]);+ const Ainverse = inverse(A);++ const b00 = transformationMatrix[0]![2]!;+ const b10 = transformationMatrix[1]![2]!;+ const a00Prime = Ainverse.get(0, 0);+ const a01Prime = Ainverse.get(0, 1);+ const a10Prime = Ainverse.get(1, 0);+ const a11Prime = Ainverse.get(1, 1);++ for (let yTrans = 0; yTrans < faceSize; ++yTrans) {+ for (let xTrans = 0; xTrans < faceSize; ++xTrans) {+ // Perform inverse affine transformation.+ const xOrigin =+ a00Prime * (xTrans - b00) + a01Prime * (yTrans - b10);+ const yOrigin =+ a10Prime * (xTrans - b00) + a11Prime * (yTrans - b10);++ // Get the pixel RGB using bicubic interpolation.+ const { r, g, b } = pixelRGBBicubic(+ xOrigin,+ yOrigin,+ pixelData,+ width,+ height,+ );++ // Set the pixel in the input data.+ const index = (yTrans * faceSize + xTrans) * 3;+ inputData[inputStartIndex + index] = rgbToBipolarFloat(r);+ inputData[inputStartIndex + index + 1] = rgbToBipolarFloat(g);+ inputData[inputStartIndex + index + 2] = rgbToBipolarFloat(b);+ }+ }+};++/** Convert a RGB component 0-255 to a floating point value between -1 and 1. */+const rgbToBipolarFloat = (pixelValue: number) => pixelValue / 127.5 - 1.0;++/** Convert a floating point value between -1 and 1 to a RGB component 0-255. */+const bipolarFloatToRGB = (pixelValue: number) =>+ clamp(Math.round((pixelValue + 1.0) * 127.5), 0, 255);++export const grayscaleIntMatrixFromNormalized2List = (+ imageList: Float32Array,+ faceNumber: number,+ width: number,+ height: number,+): number[][] => {+ const startIndex = faceNumber * width * height * 3;+ return Array.from({ length: height }, (_, y) =>+ Array.from({ length: width }, (_, x) => {+ // 0.299 ∙ Red + 0.587 ∙ Green + 0.114 ∙ Blue+ const pixelIndex = startIndex + 3 * (y * width + x);+ return clamp(+ Math.round(+ 0.299 * bipolarFloatToRGB(imageList[pixelIndex]!) ++ 0.587 * bipolarFloatToRGB(imageList[pixelIndex + 1]!) ++ 0.114 * bipolarFloatToRGB(imageList[pixelIndex + 2]!),+ ),+ 0,+ 255,+ );+ }),+ );+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/index.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/index.tsnew file mode 100644index 0000000000..d5c23bf421--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/index.ts@@ -0,0 +1,1005 @@+/**+ * @file Main thread interface to the ML subsystem.+ */++import { proxy, transfer } from "comlink";+import { ensureLocalUser } from "ente-accounts/services/user";+import { isDesktop } from "ente-base/app";+import { blobCache } from "ente-base/blob-cache";+import { ensureElectron } from "ente-base/electron";+import log from "ente-base/log";+import { ensureMasterKeyFromSession } from "ente-base/session";+import { ComlinkWorker } from "ente-base/worker/comlink-worker";+import { type ProcessableUploadItem } from "ente-gallery/services/upload";+import { createUtilityProcess } from "ente-gallery/utils/native-worker";+import type { EnteFile } from "ente-media/file";+import { FileType } from "ente-media/file-type";+import { throttled } from "ente-utils/promise";+import pDebounce from "p-debounce";+import { getRemoteFlag, updateRemoteFlag } from "../remote-store";+import { setSearchPeople } from "../search";+import {+ addUserEntity,+ pullUserEntities,+ savedCGroups,+ updateOrCreateUserEntities,+ type CGroup,+} from "../user-entity";+import { deleteUserEntity } from "../user-entity/remote";+import type { FaceCluster } from "./cluster";+import { regenerateFaceCrops } from "./crop";+import {+ clearMLDB,+ resetFailedFileStatuses,+ savedFaceIndex,+ savedIndexCounts,+} from "./db";+import { fileIDFromFaceID } from "./face";+import {+ _applyPersonSuggestionUpdates,+ filterNamedPeople,+ reconstructPeopleState,+ type CGroupPerson,+ type PeopleState,+ type PersonSuggestionUpdates,+} from "./people";+import { MLWorker } from "./worker";+import type { CLIPMatches } from "./worker-types";++/**+ * Internal state of the ML subsystem.+ *+ * These are essentially cached values used by the functions of this module.+ *+ * They will be cleared on logout.+ */+class MLState {+ /**+ * In-memory flag that tracks if ML is enabled.+ *+ * - On app start, this is read from local storage during {@link initML}.+ *+ * - It gets updated when we pull from remote (so if the user+ * enables/disables ML on a different device, this local value will also+ * become true/false).+ *+ * - It gets updated when the user enables/disables ML on this device.+ *+ * - It is cleared in {@link logoutML}.+ */+ isMLEnabled = false;++ /**+ * Cached instance of the {@link ComlinkWorker} that wraps our web worker.+ */+ comlinkWorker: Promise<ComlinkWorker<typeof MLWorker>> | undefined;++ /**+ * `true` if a sync is currently in progress.+ */+ isSyncing = false;++ /**+ * Subscriptions to {@link MLStatus} updates attached using+ * {@link mlStatusSubscribe}.+ */+ mlStatusListeners: (() => void)[] = [];++ /**+ * Snapshot of the {@link MLStatus} returned by the {@link mlStatusSnapshot}+ * function.+ */+ mlStatusSnapshot: MLStatus | undefined;++ /**+ * Subscriptions to updates to the {@link PeopleState} attached using+ * {@link peopleStateSubscribe}.+ */+ peopleStateListeners: (() => void)[] = [];++ /**+ * Snapshot of the {@link PeopleState} return by the+ * {@link peopleStateSnapshot} function.+ *+ * It will be `undefined` only if ML is disabled. Otherwise, it will be an+ * empty array even if the snapshot is pending its first sync.+ */+ peopleStateSnapshot: PeopleState | undefined;++ /**+ * `true` if a reset has been requested via+ * {@link retryIndexingFailuresIfNeeded}.+ */+ needsResetFailures = false;++ /**+ * In flight face crop regeneration promises indexed by the IDs of the files+ * whose faces we are regenerating.+ */+ inFlightFaceCropRegens = new Map<number, Promise<void>>();++ /**+ * Cached object URLs to face crops that we have previously vended out.+ *+ * The cache is only cleared on logout.+ */+ faceCropObjectURLCache = new Map<string, string>();+}++/** State shared by the functions in this module. See {@link MLState}. */+let _state = new MLState();+/**+ * Tracks if {@link initML} has already run for the current session.+ *+ * Some callers (notably the Next.js app shell) can end up invoking+ * {@link initML} multiple times because of re-renders or hot reloads. Without+ * this guard we'd reset {@link peopleStateSnapshot} on every invocation and+ * discard the list of people until the next sync repopulates it.+ */+let _didInitML = false;++/** Lazily created, cached, instance of {@link MLWorker}. */+const worker = () =>+ (_state.comlinkWorker ??= createComlinkWorker()).then((cw) => cw.remote);++const createComlinkWorker = async () => {+ const electron = ensureElectron();+ const delegate = { workerDidUpdateStatus, workerDidUnawaitedIndex };++ // Obtain a message port from the Electron layer.+ const messagePort = await createUtilityProcess(electron, "ml");++ const cw = new ComlinkWorker<typeof MLWorker>(+ "ML",+ new Worker(new URL("worker.ts", import.meta.url)),+ );++ await cw.remote.then((w) =>+ // Forward the port to the web worker.+ w.init(transfer(messagePort, [messagePort]), proxy(delegate)),+ );++ return cw;+};++/**+ * Terminate {@link worker} (if any).+ *+ * This is useful during logout to immediately stop any background ML operations+ * that are in-flight for the current user. After the user logs in again, a new+ * {@link worker} will be created on demand for subsequent usage.+ *+ * It is also called when the user pauses or disables ML.+ */+export const terminateMLWorker = async () => {+ if (_state.comlinkWorker) {+ await _state.comlinkWorker.then((cw) => cw.terminate());+ _state.comlinkWorker = undefined;+ }+};++/**+ * Return true if the current client supports ML.+ *+ * ML currently only works when we're running in our desktop app.+ */+export const isMLSupported = isDesktop;++/**+ * Initialize the ML subsystem if the user has enabled it in preferences.+ */+export const initML = () => {+ if (_didInitML) return;+ _state.isMLEnabled = isMLEnabledLocal();+ resetPeopleStateSnapshot();+ _didInitML = true;+};++export const logoutML = async () => {+ // `terminateMLWorker` is conceptually also part of this sequence, but for+ // the reasons mentioned in [Note: Caching IDB instances in separate+ // execution contexts], it gets called first in the logout sequence, and+ // then this function (`logoutML`) gets called at a later point in time.++ [..._state.faceCropObjectURLCache.values()].forEach((url) =>+ URL.revokeObjectURL(url),+ );+ _state = new MLState();+ _didInitML = false;+ await clearMLDB();+};++/**+ * Return true if the user has enabled machine learning in their preferences.+ *+ * Enabling ML enables in both locally by persisting a local storage flag, and+ * sets a flag on remote so that the user's other devices can also enable it+ * when they next sync with remote.+ */+export const isMLEnabled = () =>+ // Implementation note: Keep it fast, it might be called frequently.+ _state.isMLEnabled;++/**+ * Enable ML.+ *+ * Persist the user's preference both locally and on remote, and trigger a sync.+ */+export const enableML = async () => {+ await updateIsMLEnabledRemote(true);+ setIsMLEnabledLocal(true);+ _state.isMLEnabled = true;+ setInterimScheduledStatus();+ resetPeopleStateSnapshot();+ // Trigger updates, but don't wait for them to finish.+ void updateMLStatusSnapshot().then(mlSync);+};++/**+ * Disable ML.+ *+ * Stop any in-progress ML tasks, and persist the user's preference both locally+ * and on remote.+ */+export const disableML = async () => {+ await updateIsMLEnabledRemote(false);+ setIsMLEnabledLocal(false);+ _state.isMLEnabled = false;+ _state.isSyncing = false;+ await terminateMLWorker();+ triggerStatusUpdate();+ resetPeopleStateSnapshot();+};++/**+ * Local storage key for {@link isMLEnabledLocal}.+ */+const mlLocalKey = "mlEnabled";++/**+ * Return true if our local persistence thinks that ML is enabled.+ *+ * This setting is persisted locally (in local storage). It is not synced with+ * remote and only tracks if ML is enabled locally.+ *+ * The remote status is tracked with a separate {@link isMLEnabledRemote} flag+ * that is synced with remote.+ */+const isMLEnabledLocal = () => localStorage.getItem(mlLocalKey) == "1";++/**+ * Update the (locally stored) value of {@link isMLEnabledLocal}.+ */+const setIsMLEnabledLocal = (enabled: boolean) =>+ enabled+ ? localStorage.setItem(mlLocalKey, "1")+ : localStorage.removeItem(mlLocalKey);++/**+ * For historical reasons, this is called "faceSearchEnabled" (it started off as+ * a flag to ensure we have taken the face recognition consent from the user).+ *+ * Now it tracks the status of ML in general (which includes faces + consent).+ */+const mlRemoteKey = "faceSearchEnabled";++/**+ * Return `true` if the flag to enable ML is set on remote.+ */+const getIsMLEnabledRemote = () => getRemoteFlag(mlRemoteKey);++/**+ * Update the remote flag that tracks the user's ML preference.+ */+const updateIsMLEnabledRemote = (enabled: boolean) =>+ updateRemoteFlag(mlRemoteKey, enabled);++/**+ * Reset failures so that indexing is attempted again.+ *+ * When indexing of some individual files fails for non-retriable reasons, we+ * mark those as failures locally.+ *+ * See: [Note: Transient and permanent indexing failures].+ *+ * Sometimes we might wish to reattempt these though (e.g. when adding support+ * for more file formats).+ *+ * In such cases, this function can be called early on (during an app version+ * upgrade) to set an in-memory flag which tell us that before attemepting a+ * sync, we should reset existing failed statii.+ *+ * Since this is not a critical operation, we only keep this as an in-memory+ * flag, failure to honor this will not have permanent repercussions (e.g. the+ * file would eventually get indexed on mobile, or during logout / login, or+ * during the next time an reattempt is made).+ */+export const retryIndexingFailuresIfNeeded = () => {+ _state.needsResetFailures = true;+};++/**+ * Update our local ML status with the latest value from remote.+ *+ * This is called an at early point in the global sync sequence, without waiting+ * for the potentially long file information sync to complete.+ *+ * It checks with remote if the ML flag is set, and updates our local flag to+ * reflect that value.+ *+ * To perform the actual ML data pull, use {@link mlSync}.+ */+export const pullMLStatus = async () => {+ _state.isMLEnabled = await getIsMLEnabledRemote();+ setIsMLEnabledLocal(_state.isMLEnabled);+ return updateMLStatusSnapshot();+};++/**+ * Perform a ML sync, whatever is applicable.+ *+ * This is called during the global pull sequence, after files information have+ * been pulled with remote.+ *+ * If ML is enabled, it pulls any missing embeddings from remote and starts+ * indexing to backfill any missing values. It also pulls cgroups and updates+ * the search service to use the latest values. Finally, it uses the latest+ * files, faces and cgroups to update the people shown in the UI.+ *+ * This will only have an effect if {@link pullMLStatus} has been called at+ * least once prior to calling this in the pull sequence.+ */+export const mlSync = async () => {+ if (!_state.isMLEnabled) return;+ if (_state.isSyncing) return;+ _state.isSyncing = true;++ if (_state.needsResetFailures) {+ // CAS. See documentation for retryIndexingFailures why swapping the+ // flag before performing the operation is fine.+ _state.needsResetFailures = false;+ await resetFailedFileStatuses();+ }++ // Dependency order for the sync+ //+ // files -> faces -> cgroups -> clusters -> people+ //++ // Fetch indexes, or index locally if needed.+ await worker().then((w) => w.index());++ await updateClustersAndPeople();++ _state.isSyncing = false;+};++const updateClustersAndPeople = async () => {+ const masterKey = await ensureMasterKeyFromSession();++ // Fetch existing cgroups from remote.+ await pullUserEntities("cgroup", masterKey);++ // Generate or update local clusters.+ await (await worker()).clusterFaces(masterKey);++ // Update the people shown in the UI.+ await updatePeopleState();+};++/**+ * A debounced variant of {@link updateClustersAndPeople} suitable for use+ * during potential in-progress uploads.+ *+ * The debounce uses a long interval (30 seconds) to avoid unnecessary reruns of+ * the expensive clustering as individual files get uploaded. Usually we+ * wouldn't get here as the live queue will keep getting refilled and the worker+ * would keep ticking, but it is possible, depending on timing, for the queue to+ * drain in the middle of uploads too.+ *+ * Ideally, we'd like to do the cluster update just once when the upload has+ * completed, however currently we don't have access to {@link uploadManager}+ * from here. So this gets us near that ideal, without adding too much impact or+ * requiring us to be aware of the uploadManager status.+ */+const debounceUpdateClustersAndPeople = pDebounce(+ updateClustersAndPeople,+ 30 * 1e3,+);++const workerDidUnawaitedIndex = () => void debounceUpdateClustersAndPeople();++/**+ * Run indexing on a file which was uploaded from this client.+ *+ * Indexing only happens if ML is enabled and we're running in the desktop app+ * as it is resource intensive.+ *+ * This function is called by the uploader when it uploads a new file from this+ * client, giving us the opportunity to index it live. This is only an+ * optimization - if we don't index it now it'll anyways get indexed later as+ * part of the batch jobs, but that might require downloading the file's+ * contents again.+ *+ * @param file The {@link EnteFile} that got uploaded.+ *+ * @param processableItem The item that was uploaded. This can be used to get at+ * the contents of the file that got uploaded. In case of live photos, this is+ * the image part of the live photo that was uploaded.+ */+export const indexNewUpload = (+ file: EnteFile,+ processableUploadItem: ProcessableUploadItem,+) => {+ if (!isMLEnabled()) return;+ if (!isDesktop) return;+ if (file.metadata.fileType != FileType.image) return;+ log.debug(() => ["ml/liveq", { file, processableUploadItem }]);+ void worker().then((w) => w.onUpload(file, processableUploadItem));+};++export type MLStatus =+ | { phase: "disabled" /* The ML remote flag is off */ }+ | {+ /**+ * Which phase we are in within the indexing pipeline when viewed+ * across the user's entire library:+ *+ * - "scheduled": A ML job is scheduled. Likely there are files we+ * know of that have not been indexed, but is also the state before+ * the first run of the indexer after app start.+ *+ * - "indexing": The indexer is currently running.+ *+ * - "fetching": The indexer is currently running, but we're primarily+ * fetching indexes for existing files.+ *+ * - "clustering": All files we know of have been indexed, and we are+ * now clustering the faces that were found.+ *+ * - "done": ML indexing and face clustering is complete for the+ * user's library.+ */+ phase: "scheduled" | "indexing" | "fetching" | "clustering" | "done";+ /**+ * `true` if the phase is "done" but a significant fraction of files+ * were marked as failed when indexing.+ *+ * This is not expected to happen normally, and points to a some+ * systematic error in the environment (e.g. ONNX couldn't run).+ */+ phaseFailed?: boolean;+ /**+ * The number of files that have already been indexed.+ */+ nSyncedFiles: number;+ /**+ * The total number of files that are eligible for indexing.+ */+ nTotalFiles: number;+ };++/**+ * A function that can be used to subscribe to updates in the ML status.+ *+ * See: [Note: Snapshots and useSyncExternalStore].+ */+export const mlStatusSubscribe = (onChange: () => void): (() => void) => {+ _state.mlStatusListeners.push(onChange);+ return () => {+ _state.mlStatusListeners = _state.mlStatusListeners.filter(+ (l) => l != onChange,+ );+ };+};++/**+ * Return the last known, cached {@link MLStatus}.+ *+ * See also {@link mlStatusSubscribe}.+ *+ * This function can be safely called even if {@link isMLSupported} is `false`+ * (in such cases, it will always return `undefined`). This is so that it can be+ * unconditionally called as part of a React hook.+ *+ * A return value of `undefined` indicates that we're still performing the+ * asynchronous tasks that are needed to get the status.+ */+export const mlStatusSnapshot = (): MLStatus | undefined => {+ if (!isMLSupported) return undefined;++ const result = _state.mlStatusSnapshot;+ // We don't have it yet, trigger an update.+ if (!result) triggerStatusUpdate();+ return result;+};++/**+ * Trigger an asynchronous update of the {@link MLStatus} snapshot, and return+ * without waiting for it to finish.+ */+const triggerStatusUpdate = () => void updateMLStatusSnapshot();++/** Unconditionally update of the {@link MLStatus} snapshot. */+const updateMLStatusSnapshot = async () =>+ setMLStatusSnapshot(await getMLStatus());++const setMLStatusSnapshot = (snapshot: MLStatus) => {+ _state.mlStatusSnapshot = snapshot;+ _state.mlStatusListeners.forEach((l) => l());+};++/**+ * Compute the current state of the ML subsystem.+ */+const getMLStatus = async (): Promise<MLStatus> => {+ if (!_state.isMLEnabled) return { phase: "disabled" };++ const w = await worker();++ // The worker has a clustering progress set iff it is clustering. This+ // overrides other behaviours.+ const clusteringProgress = await w.clusteringProgress;+ if (clusteringProgress) {+ return {+ phase: "clustering",+ nSyncedFiles: clusteringProgress.completed,+ nTotalFiles: clusteringProgress.total,+ };+ }++ const { indexedCount, indexableCount, failedCount } =+ await savedIndexCounts();++ // During live uploads, the indexable count remains zero even as the indexer+ // is processing the newly uploaded items. This is because these "live+ // queue" items do not yet have a "file-status" entry.+ //+ // So use the state of the worker as a guide for the phase, not the+ // indexable count.++ let phase: MLStatus["phase"];+ let phaseFailed = false;+ const state = await w.state;+ if (state == "indexing" || state == "fetching") {+ phase = state;+ } else if (state == "init" || indexableCount > 0) {+ phase = "scheduled";+ } else {+ phase = "done";+ phaseFailed = failedCount > indexedCount && failedCount > 500;+ }++ return {+ phase,+ phaseFailed,+ nSyncedFiles: indexedCount,+ nTotalFiles: indexableCount + indexedCount,+ };+};++/**+ * When the user enables or resumes ML, we wish to give immediate feedback.+ *+ * So this is an intermediate state with possibly incorrect counts (but correct+ * phase) that is set immediately to trigger a UI update. It uses the counts+ * from the last known status, and just updates the phase.+ *+ * Once the worker is initialized and the correct counts fetched, this will+ * update to the correct state (should take less than a second).+ */+const setInterimScheduledStatus = () => {+ let nSyncedFiles = 0,+ nTotalFiles = 0;+ if (+ _state.mlStatusSnapshot &&+ _state.mlStatusSnapshot.phase != "disabled"+ ) {+ ({ nSyncedFiles, nTotalFiles } = _state.mlStatusSnapshot);+ }+ setMLStatusSnapshot({ phase: "scheduled", nSyncedFiles, nTotalFiles });+};++const workerDidUpdateStatus = throttled(updateMLStatusSnapshot, 2000);++/**+ * A function that can be used to subscribe to updates to {@link Person}s.+ *+ * See: [Note: Snapshots and useSyncExternalStore].+ */+export const peopleStateSubscribe = (onChange: () => void): (() => void) => {+ _state.peopleStateListeners.push(onChange);+ return () => {+ _state.peopleStateListeners = _state.peopleStateListeners.filter(+ (l) => l != onChange,+ );+ };+};++/**+ * If ML is enabled, set the people snapshot to an empty array to indicate that+ * ML is enabled, but we're still reading in the set of people.+ *+ * Otherwise, if ML is disabled, set the people snapshot to `undefined`.+ */+const resetPeopleStateSnapshot = () =>+ setPeopleStateSnapshot(+ _state.isMLEnabled+ ? { people: [], visiblePeople: [], personByFaceID: new Map() }+ : undefined,+ );++/**+ * Return the last known, cached {@link PeopleState}.+ *+ * See also {@link peopleStateSubscribe}.+ *+ * A return value of `undefined` indicates that ML is disabled. In all other+ * cases, the list of people will be either empty (if we're either still loading+ * the initial list of people, or if the user doesn't have any people), or,+ * well, non-empty.+ */+export const peopleStateSnapshot = () => _state.peopleStateSnapshot;++// Update our, and the search subsystem's, snapshot of people state by+// reconstructing it from the latest local state.+const updatePeopleState = async () => {+ const state = await reconstructPeopleState();++ // Notify the search subsystem of the update (search only uses named ones).+ setSearchPeople(filterNamedPeople(state.visiblePeople));++ // Update our in-memory state.+ setPeopleStateSnapshot(state);+};++const setPeopleStateSnapshot = (snapshot: PeopleState | undefined) => {+ _state.peopleStateSnapshot = snapshot;+ _state.peopleStateListeners.forEach((l) => l());+};++/**+ * Use CLIP to perform a natural language search over image embeddings.+ *+ * @param searchPhrase Normalized (trimmed and lowercased) search phrase.+ *+ * It returns file (IDs) that should be shown in the search results, each+ * annotated with its score.+ *+ * The result can also be `undefined`, which indicates that the download for the+ * ML model is still in progress (trying again later should succeed).+ */+export const clipMatches = (+ searchPhrase: string,+): Promise<CLIPMatches | undefined> =>+ worker().then((w) => w.clipMatches(searchPhrase));++/**+ * A face ID annotated with the ID of the person or cluster with which it is+ * associated.+ */+export interface AnnotatedFaceID {+ faceID: string;+ personID: string;+ personName: string | undefined;+}++/**+ * Return the list of faces found in the given {@link file}.+ */+export const getAnnotatedFacesForFile = async (+ file: EnteFile,+): Promise<AnnotatedFaceID[]> => {+ if (!isMLEnabled()) return [];++ const index = await savedFaceIndex(file.id);+ if (!index) return [];++ const personByFaceID = _state.peopleStateSnapshot?.personByFaceID;+ if (!personByFaceID) return [];++ const sortableFaces: [AnnotatedFaceID, number][] = [];+ for (const { faceID } of index.faces) {+ const person = personByFaceID.get(faceID);+ if (!person) continue;+ sortableFaces.push([+ { faceID, personID: person.id, personName: person.name },+ person.fileIDs.length,+ ]);+ }++ sortableFaces.sort((a, b) => {+ // If only one has a person name, prefer it.+ if (a[0].personName && !b[0].personName) return -1;+ if (!a[0].personName && b[0].personName) return 1;+ // Otherwise (both named or both unnamed) sort by their number of files.+ return b[1] - a[1];+ });+ return sortableFaces.map(([f]) => f);+};++/**+ * Return a URL to the face crop for the given face, regenerating it if needed.+ *+ * The resultant URL is cached (both the object URL itself, and the underlying+ * file crop blob used to generete it).+ *+ * @param faceID The id of the face whose face crop we want.+ *+ * @param file The {@link EnteFile} that contains this face.+ */+export const faceCrop = async (faceID: string, file: EnteFile) => {+ let inFlight = _state.inFlightFaceCropRegens.get(file.id);++ if (!inFlight) {+ inFlight = regenerateFaceCropsIfNeeded(file);+ _state.inFlightFaceCropRegens.set(file.id, inFlight);+ }++ await inFlight;++ let url = _state.faceCropObjectURLCache.get(faceID);+ if (!url) {+ const cache = await blobCache("face-crops");+ const blob = await cache.get(faceID);+ if (blob) {+ url = URL.createObjectURL(blob);+ if (url) _state.faceCropObjectURLCache.set(faceID, url);+ }+ }++ return url;+};++/**+ * Check to see if any of the faces in the given file do not have a face crop+ * present locally. If so, then regenerate the face crops for all the faces in+ * the file (updating the "face-crops" {@link BlobCache}).+ */+const regenerateFaceCropsIfNeeded = async (file: EnteFile) => {+ const index = await savedFaceIndex(file.id);+ if (!index) return;++ const cache = await blobCache("face-crops");+ const faceIDs = index.faces.map((f) => f.faceID);+ let needsRegen = false;+ for (const id of faceIDs) if (!(await cache.has(id))) needsRegen = true;++ if (needsRegen) await regenerateFaceCrops(file, index);+};++/**+ * Convert a cluster into a named person, updating both remote and local state.+ *+ * @param name Name of the new cgroup user entity.+ *+ * @param cluster The underlying cluster to use to populate the cgroup.+ *+ * @returns The entity ID of the newly created cgroup.+ */+export const addCGroup = async (name: string, cluster: FaceCluster) => {+ const id = await addUserEntity(+ "cgroup",+ {+ name,+ assigned: [cluster],+ isHidden: false,+ isPinned: false,+ hideFromMemories: false,+ },+ await ensureMasterKeyFromSession(),+ );+ await mlSync();+ return id;+};++/**+ * Add a new cluster to an existing named person.+ *+ * If this cluster contains any faces that had previously been marked as not+ * belonging to the person, then they will be removed from the rejected list and+ * will get reassociated to the person.+ *+ * @param cgroup The existing cgroup underlying the person. This is the (remote)+ * user entity that will get updated.+ *+ * @param cluster The new cluster of faces to associate with this person.+ */+export const addClusterToCGroup = async (+ cgroup: CGroup,+ cluster: FaceCluster,+) => {+ const clusterFaceIDs = new Set(cluster.faces);+ const assigned = cgroup.data.assigned.concat([cluster]);+ const rejectedFaceIDs = cgroup.data.rejectedFaceIDs.filter(+ (id) => !clusterFaceIDs.has(id),+ );++ await updateOrCreateUserEntities(+ "cgroup",+ [{ ...cgroup, data: { ...cgroup.data, assigned, rejectedFaceIDs } }],+ await ensureMasterKeyFromSession(),+ );+ return mlSync();+};++/**+ * Rename an existing named person.+ *+ * @param name The new name to use.+ *+ * @param cgroup The existing cgroup underlying the person. This is the (remote)+ * user entity that will get updated.+ */+export const renameCGroup = async (cgroup: CGroup, name: string) => {+ await updateOrCreateUserEntities(+ "cgroup",+ [{ ...cgroup, data: { ...cgroup.data, name } }],+ await ensureMasterKeyFromSession(),+ );+ return mlSync();+};++/**+ * Delete an existing person.+ *+ * @param cgroup The existing cgroup underlying the person.+ */+export const deleteCGroup = async ({ id }: CGroup) => {+ await deleteUserEntity(id);+ return mlSync();+};++/**+ * Change the pinned state of a person.+ */+export const setCGroupPinned = async (cgroup: CGroup, isPinned: boolean) => {+ await updateOrCreateUserEntities(+ "cgroup",+ [{ ...cgroup, data: { ...cgroup.data, isPinned } }],+ await ensureMasterKeyFromSession(),+ );+ return mlSync();+};++export const pinCGroup = async (cgroup: CGroup) =>+ setCGroupPinned(cgroup, true);++export const unpinCGroup = async (cgroup: CGroup) =>+ setCGroupPinned(cgroup, false);++export interface ManualPersonAssignmentResult {+ /**+ * File IDs that were added to the person's manual assignment list.+ */+ addedFileIDs: number[];+ /**+ * File IDs that were already associated with the person (either via a+ * detected face or via an existing manual assignment).+ */+ alreadyAssignedFileIDs: number[];+}++/**+ * Manually associate the given {@link fileIDs} with a remote cgroup ("person").+ *+ * The manual assignment is stored in the cgroup user entity data as an+ * unordered set of file IDs ({@link CGroupUserEntityData.manuallyAssigned}).+ */+export const addManualFileAssignmentsToPerson = async (+ personID: string,+ fileIDs: Iterable<number>,+): Promise<ManualPersonAssignmentResult> => {+ if (!isMLEnabled()) return { addedFileIDs: [], alreadyAssignedFileIDs: [] };++ const uniqueFileIDs = [...new Set(fileIDs)].filter(+ (id) => typeof id == "number" && !isNaN(id),+ );+ if (!uniqueFileIDs.length)+ return { addedFileIDs: [], alreadyAssignedFileIDs: [] };++ const cgroup = (await savedCGroups()).find((c) => c.id == personID);+ if (!cgroup)+ throw new Error(+ `addManualFileAssignmentsToPerson: missing cgroup ${personID}`,+ );++ // File IDs already associated with the person via detected faces.+ const existingClusterFileIDs = new Set<number>();+ for (const cluster of cgroup.data.assigned) {+ for (const faceID of cluster.faces) {+ const fileID = fileIDFromFaceID(faceID);+ if (fileID) existingClusterFileIDs.add(fileID);+ }+ }++ const manualFileIDs = new Set(cgroup.data.manuallyAssigned);++ const addedFileIDs: number[] = [];+ const alreadyAssignedFileIDs: number[] = [];+ for (const id of uniqueFileIDs) {+ if (existingClusterFileIDs.has(id) || manualFileIDs.has(id)) {+ alreadyAssignedFileIDs.push(id);+ } else {+ addedFileIDs.push(id);+ }+ }++ if (!addedFileIDs.length) return { addedFileIDs, alreadyAssignedFileIDs };++ const masterKey = await ensureMasterKeyFromSession();+ await updateOrCreateUserEntities(+ "cgroup",+ [+ {+ ...cgroup,+ data: {+ ...cgroup.data,+ manuallyAssigned: [...manualFileIDs, ...addedFileIDs],+ },+ },+ ],+ masterKey,+ );++ // Pull the updated entity to keep local updatedAt state in sync, and+ // reconstruct people state to reflect the new manual associations.+ await pullUserEntities("cgroup", masterKey);+ await updatePeopleState();++ return { addedFileIDs, alreadyAssignedFileIDs };+};++/**+ * Return suggestions for the given {@link person}.+ *+ * The suggestion computation happens in a web worker.+ *+ * Since the computation is happening in a web worker, and it doesn't+ * have access to any localStorage, we need to pass the currentUserID explicitly.+ * for the isHiddenCollection checks in the process.+ * */+export const suggestionsAndChoicesForPerson = async (person: CGroupPerson) =>+ worker().then((w) =>+ w.suggestionsAndChoicesForPerson(person, ensureLocalUser().id),+ );++/**+ * Implementation for the "save" action on the SuggestionsDialog.+ *+ * See {@link _applyPersonSuggestionUpdates} for more details.+ */+export const applyPersonSuggestionUpdates = async (+ cgroup: CGroup,+ updates: PersonSuggestionUpdates,+) => {+ await _applyPersonSuggestionUpdates(+ cgroup,+ updates,+ await ensureMasterKeyFromSession(),+ );+ return mlSync();+};++/**+ * Ignore/hide a cluster.+ *+ * This converts the cluster into a cgroup so that it can be synced with remote,+ * setting the hidden flag so that it is not surfaced in the UI.+ *+ * @param cluster The {@link FaceCluster} to hide.+ */+export const ignoreCluster = async (cluster: FaceCluster) => {+ await addUserEntity(+ "cgroup",+ {+ name: "",+ assigned: [cluster],+ isHidden: true,+ isPinned: false,+ hideFromMemories: false,+ },+ await ensureMasterKeyFromSession(),+ );+ return mlSync();+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/kvdb.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/kvdb.tsnew file mode 100644index 0000000000..9792514d7f--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/kvdb.ts@@ -0,0 +1,60 @@+import { getKV, setKV } from "ente-base/kv";+import { z } from "zod";++/**+ * Zod schema for {@link ClusterIDsByCGroupID}.+ */+const ClusterIDsByCGroupID = z.record(z.string(), z.array(z.string()));++/**+ * cgroupID -> clusterIDs+ *+ * A record containing an array of clusters (represented by their IDs), keyed by+ * the corresponding cgroup ID.+ */+export type ClusterIDsByCGroupID = z.infer<typeof ClusterIDsByCGroupID>;++/**+ * Return the locally persisted record of clusters per cgroup that the user has+ * rejected as not belonging to that cgroup.+ *+ * [Note: Persistent KV pairs related to ML]+ *+ * Conceptually, these could be part of ML DB. Practically, that'd would require+ * us to create a "kv" store within the ML DB, which seems both unnecessary, and+ * also potentially problematic since we'll have to introduce a version+ * migration (IndexedDB is finicky, and we've had better luck not poking it when+ * possible. See [Note: Avoiding IndexedDB flakiness by avoiding indexes]).+ */+export const savedRejectedClusters = async (): Promise<ClusterIDsByCGroupID> =>+ ClusterIDsByCGroupID.parse((await getKV("rejectedClusters")) ?? {});++/**+ * Update the locally persisted record of rejected clusters.+ *+ * Sibling of {@link savedRejectedClusters}.+ */+export const saveRejectedClusters = (entries: ClusterIDsByCGroupID) =>+ setKV("rejectedClusters", entries);++/**+ * Return the list of locally persisted clusters that the user has rejected as+ * not belonging to a particular cgroup (as identified by its {@link cgroupID}).+ */+export const savedRejectedClustersForCGroup = async (+ cgroupID: string,+): Promise<string[]> =>+ savedRejectedClusters().then((cs) => cs[cgroupID] ?? []);++/**+ * Update the locally persisted record of rejected clusters for the given cgroup+ * (as identified by its {@link cgroupID}).+ */+export const saveRejectedClustersForCGroup = async (+ cgroupID: string,+ clusterIDs: string[],+) => {+ const rejectedClusters = await savedRejectedClusters();+ rejectedClusters[cgroupID] = clusterIDs;+ return saveRejectedClusters(rejectedClusters);+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/math.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/math.tsnew file mode 100644index 0000000000..b4506f0fff--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/math.ts@@ -0,0 +1,76 @@+/**+ * Clamp {@link value} to between {@link min} and {@link max}, inclusive.+ */+export const clamp = (value: number, min: number, max: number) =>+ Math.min(max, Math.max(min, value));++/**+ * Return the dot-product of two vectors.+ *+ * Dot product is the component-wise product of the corresponding elements of+ * the two given vectors.+ *+ * Precondition: The two vectors must be of the same length.+ *+ * ---+ *+ * [Note: Dot product is cosine similarity for normalized vectors]+ *+ * The cosine similarity of two vectors is defined as+ *+ * dotProduct(v1, v2) / (norm(v1) * norm(v2));+ *+ * In particular, when both the vectors are normalized, this is equal to the dot+ * product. When we're computing dot products in a hot loop, skipping over that+ * unnecessary renormalization matters.+ *+ * When comparing embeddings we usually want is the cosine similarity, but if+ * both the embeddings involved are already normalized, we can save the norm+ * calculations and directly do their `dotProduct`.+ *+ * Such code is often on the hot path, so these optimizations help.+ *+ * ---+ *+ * [Note: Cosine similarity and cosine distance]+ *+ * The cosine similarity of two vectors is [-1, 1] (inclusive), indicating how+ * similar (1), orthogonal (0) and dissimilar (1) the two vectors are in+ * direction. A related concept is cosine distance, which is defined as+ *+ * 1 - cosine similarity+ *+ * in an attempt to convert it into a (pseudo) distance metric.+ *+ * ---+ *+ * [Note: Dot product performance]+ *+ * In theory, Wasm SIMD instructions should give us a huge boost for computing+ * dot products. In practice, we can get to roughly around the same performance+ * by using Float32Arrays instead of number[], and letting the JS JIT do the+ * optimizations for us (This assertion was made on Chrome on macOS on Sep 2023,+ * and may not hold in the future).+ *+ * We can get a further 2x speedup over this by using some library that directly+ * uses the SIMD intrinsics provided by the architecture instead of limiting+ * itself to Wasm's set. But that'll require bundling native code, so as a+ * tradeoff to avoid complexity we currently leave that 1x on the table.+ */+export const dotProduct = (v1: Float32Array, v2: Float32Array) => {+ if (v1.length != v2.length)+ throw new Error(`Length mismatch ${v1.length} ${v2.length}`);+ let d = 0;+ for (let i = 0; i < v1.length; i++) d += v1[i]! * v2[i]!;+ return d;+};++/**+ * Return the L2-norm ("magnitude") of the given vector.+ *+ * L2-norm is the sqrt of the sum of the squares of the components of the+ * vector. It can also be thought of as the sqrt of the dot product of the+ * vector with itself.+ */+export const norm = (v: Float32Array) =>+ Math.sqrt(v.reduce((a, x) => a + x * x, 0));diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/ml-data.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/ml-data.tsnew file mode 100644index 0000000000..6d04b619f9--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/ml-data.ts@@ -0,0 +1,226 @@+import { decryptBlobBytes } from "ente-base/crypto";+import log from "ente-base/log";+import { fetchFilesData, putFileData } from "ente-gallery/services/file-data";+import type { EnteFile } from "ente-media/file";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";+import { gunzip, gzip } from "../../utils/gzip";+import { type RemoteCLIPIndex } from "./clip";+import { type RemoteFaceIndex } from "./face";++/**+ * The decrypted payload of a {@link RemoteFileData} for the "mldata"+ * {@link FileDataType}.+ *+ * [Note: "mldata" format]+ *+ * The file data of type "mldata" contains various embeddings and other metadata+ * generated by the ML indexing for a given file.+ *+ * For example, the face indexing process generates multiple face embeddings per+ * file (one for each face), each with an associated detection box. So instead+ * of storing just a singular embedding, the data is an entire face index+ * structure containing multiple embeddings and associated data.+ *+ * Similarly, the CLIP indexing process generates a CLIP embedding with some+ * associated data.+ *+ * All such indexes are merge into a single object of the form:+ *+ * {+ * "face": ... the face indexing result ...+ * "clip": ... the CLIP indexing result ...+ * ... more in the future ...+ * }+ *+ * which is then gzipped to get the plaintext data to upload.+ *+ * [Note: Preserve unknown ML data fields]+ *+ * The (unzipped) remote mldata can contain arbitrary keys at the top level+ * apart from the ones that the current client knows about. We need to preserve+ * these verbatim when we use {@link putMLData}.+ *+ * Thus we return two separate results from {@link fetchMLData}:+ *+ * - {@link RawRemoteMLData}: The original, unmodified JSON.+ *+ * - {@link ParsedRemoteMLData}: The particular fields that the current client+ * knows about, parsed according to their expected structure.+ *+ * When integrating this information into our local state, we use the parsed+ * version. And if we need to update the state on remote (e.g. if the current+ * client notices an particular type of index was missing), then we use the+ * original JSON as the base.+ */+export interface RemoteMLData {+ raw: RawRemoteMLData;+ parsed: ParsedRemoteMLData | undefined;+ // See: [Note: PUT "mldata" version check]+ updatedAt: number | undefined;+}++export type RawRemoteMLData = Record<string, unknown>;++export type ParsedRemoteMLData = Partial<{+ face: RemoteFaceIndex;+ clip: RemoteCLIPIndex;+}>;++/**+ * Zod schema for the {@link RemoteFaceIndex} type.+ *+ * [Note: Duplicated Zod schema and TypeScript type]+ *+ * Usually we define a Zod schema, and then infer the corresponding TypeScript+ * type for it using `z.infer`. This works great except that the docstrings+ * don't show up: Docstrings get added to the Zod schema, but usually the code+ * using the parsed data will reference the TypeScript type, and the docstrings+ * added to the fields in the Zod schema won't show up.+ *+ * We usually live with this infelicity since the alternative is code+ * duplication: Defining a TypeScript type (putting the docstrings therein)+ * _and_ also a corresponding Zod schema. The duplication is needed because it+ * is not possible to go the other way (TypeScript type => Zod schema).+ *+ * However, in some cases having when the TypeScript type under consideration is+ * used pervasively in code, having a standalone TypeScript type with attached+ * docstrings is worth the code duplication.+ *+ * Note that this'll just be syntactic duplication - if the two definitions get+ * out of sync in the shape of the types they represent, the TypeScript compiler+ * will flag it for us.+ */+const RemoteFaceIndex = z.object({+ version: z.number(),+ client: z.string(),+ width: z.number(),+ height: z.number(),+ faces: z.array(+ z.object({+ faceID: z.string(),+ detection: z.object({+ box: z.object({+ x: z.number(),+ y: z.number(),+ width: z.number(),+ height: z.number(),+ }),+ landmarks: z.array(z.object({ x: z.number(), y: z.number() })),+ }),+ score: z.number(),+ blur: z.number(),+ embedding: z.array(z.number()),+ }),+ ),+});++/**+ * Zod schema for the {@link RemoteCLIPIndex} type.+ *+ * See: [Note: Duplicated Zod schema and TypeScript type]+ */+const RemoteCLIPIndex = z.object({+ version: z.number(),+ client: z.string(),+ embedding: z.array(z.number()),+});++/**+ * Zod schema for the {@link RawRemoteMLData} type.+ */+const RawRemoteMLData = z.looseObject({});++/**+ * Zod schema for the {@link ParsedRemoteMLData} type.+ */+const ParsedRemoteMLData = z.object({+ face: RemoteFaceIndex.nullish().transform(nullToUndefined),+ clip: RemoteCLIPIndex.nullish().transform(nullToUndefined),+});++/**+ * Fetch ML data for the given files from remote.+ *+ * @param filesByID A map containing the files whose ML data we want to fetch.+ * Each entry is keyed the the file's ID, and the value is the file.+ *+ * @returns a map containing the (decrypted) ML data for each file for which+ * remote returned the corresponding ML data.+ *+ * Each entry in the map is keyed by file's ID, and each value is a+ * {@link RemoteMLData} that contains both the original JSON, and parsed+ * representation of ML data keys that we know about.+ */+export const fetchMLData = async (+ filesByID: Map<number, EnteFile>,+): Promise<Map<number, RemoteMLData>> => {+ const remoteFileDatas = await fetchFilesData("mldata", [+ ...filesByID.keys(),+ ]);++ const result = new Map<number, RemoteMLData>();+ for (const remoteFileData of remoteFileDatas) {+ const { fileID, updatedAt } = remoteFileData;+ const file = filesByID.get(fileID);+ if (!file) {+ log.warn(`Ignoring ML data for unknown file id ${fileID}`);+ continue;+ }++ try {+ const decryptedBytes = await decryptBlobBytes(+ remoteFileData,+ file.key,+ );+ const jsonString = await gunzip(decryptedBytes);+ result.set(+ fileID,+ remoteMLDataFromJSONString(jsonString, updatedAt),+ );+ } catch (e) {+ // This shouldn't happen. Best guess is that some client has+ // uploaded a corrupted ML index. Ignore it so that it gets+ // reindexed and uploaded correctly again.+ log.warn(`Ignoring unparseable ML data for file id ${fileID}`, e);+ }+ }+ log.debug(() => `Fetched ML data for ${result.size} files`);+ return result;+};++const remoteMLDataFromJSONString = (+ jsonString: string,+ updatedAt: number | undefined,+) => {+ const raw = RawRemoteMLData.parse(JSON.parse(jsonString));+ const parseResult = ParsedRemoteMLData.safeParse(raw);+ const parsed = parseResult.success+ ? (parseResult.data as ParsedRemoteMLData)+ : undefined;+ return { raw, parsed, updatedAt };+};++/**+ * Update the ML data stored for given {@link file} on remote.+ *+ * This allows other clients to directly pull the ML data instead of needing to+ * re-index.+ *+ * The data on remote will be replaced unconditionally, and it is up to the+ * client (us) to ensure that we preserve the parts of the pre-existing ML data+ * (if any) that we did not understand or touch.+ *+ * See: [Note: Preserve unknown ML data fields].+ */+export const putMLData = async (+ file: EnteFile,+ mlData: RawRemoteMLData,+ lastUpdatedAt: number,+) =>+ putFileData(+ file,+ "mldata",+ await gzip(JSON.stringify(mlData)),+ lastUpdatedAt,+ );diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/people.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/people.tsnew file mode 100644index 0000000000..189be16169--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/people.ts@@ -0,0 +1,840 @@+import { assertionFailed } from "ente-base/assert";+import log from "ente-base/log";+import type { EnteFile } from "ente-media/file";+import { fileCreationTime } from "ente-media/file-metadata";+import { randomSample } from "ente-utils/array";+import { computeNormalCollectionFilesFromSaved } from "../file";+import {+ savedCGroups,+ updateOrCreateUserEntities,+ type CGroup,+} from "../user-entity";+import type { FaceCluster } from "./cluster";+import { savedFaceClusters, savedFaceIndexes, saveFaceClusters } from "./db";+import { fileIDFromFaceID } from "./face";+import {+ savedRejectedClustersForCGroup,+ saveRejectedClustersForCGroup,+} from "./kvdb";+import { dotProduct } from "./math";++/**+ * A cgroup ("cluster group") is a group of clusters (possibly containing just a+ * single cluster) that the user has interacted with.+ *+ * Interactions include hiding, merging and giving a name and/or a cover photo.+ *+ * The most frequent interaction is naming a {@link FaceCluster}, which promotes+ * it to a become a {@link CGroup}. The promotion comes with the+ * ability to be synced with remote (as a "cgroup" user entity).+ *+ * There after, the user may attach more clusters to the same cgroup.+ *+ * > A named cluster group can be thought of as a "person", though this is not+ * > necessarily an accurate characterization. e.g. there can be a named cluster+ * > group that contains face clusters of pets.+ *+ * The other form of interaction is hiding. The user may hide a single (unnamed)+ * cluster, or they may hide an named cgroup. In both cases, we promote the+ * cluster to a cgroup if needed so that their request to hide gets synced.+ *+ * The user can see both the cgroups and clusters in the UI, but only the+ * cgroups are synced with remote.+ */+export interface CGroupUserEntityData {+ /**+ * A name assigned by the user to this cluster group.+ *+ * The client should handle both empty strings and undefined as indicating a+ * cgroup without a name. When the client needs to set this to an <empty>+ * value, which happens when hiding an unnamed cluster, it should it to an+ * empty string. That is, expect `"" | undefined`, but set `""`.+ *+ * [Note: Mark optional for Zod/exactOptionalPropertyTypes]+ *+ * The type is marked as an optional (?) because currently Zod does not+ * differentiate between optionals and undefined-valued properties as+ * required by exactOptionalPropertyTypes.+ */+ name?: string | undefined;+ /**+ * An unordered set of clusters that have been assigned to this group.+ *+ * For ease of transportation and persistence this is an array, but it+ * should conceptually be thought of as a set.+ */+ assigned: FaceCluster[];+ /**+ * An unordered set of faces (IDs) that the user has manually marked as not+ * belonging to this group.+ *+ * For ease of transportation and persistence this is an array, but it+ * should conceptually be thought of as a set.+ */+ rejectedFaceIDs: string[];+ /**+ * An unordered set of file IDs that the user has manually tagged as+ * belonging to this group.+ *+ * For ease of transportation and persistence this is an array, but it+ * should conceptually be thought of as a set.+ */+ manuallyAssigned: number[];+ /**+ * True if this cluster group should be hidden.+ *+ * The user can hide both named cluster groups and single unnamed clusters.+ * If the user hides a single cluster that was offered as a suggestion to+ * them on a client, the client will create a new unnamed cgroup containing+ * it, and set its hidden flag to sync it with remote (so that other clients+ * can also stop showing this cluster).+ */+ isHidden: boolean;+ /**+ * The ID of the face that should be used as the cover photo for this+ * cluster group. Optional.+ *+ * This is similar to the [@link displayFaceID}, the difference being:+ *+ * - {@link avatarFaceID} is the face selected by the user.+ *+ * - {@link displayFaceID} is the automatic placeholder, and only comes into+ * effect if the user has not explicitly selected a face.+ *+ * Also, see: [Note: Mark optional for Zod/exactOptionalPropertyTypes]+ */+ avatarFaceID?: string | undefined;+ /**+ * True if this cluster group has been pinned by the user.+ */+ isPinned?: boolean | undefined;+ /**+ * True if this cluster group should not be surfaced in memories.+ *+ * Desktop does not currently surface memories, but we still need to+ * preserve this flag so that it continues to sync correctly with mobile.+ */+ hideFromMemories?: boolean | undefined;+}++/**+ * A massaged version of {@link CGroup} or a {@link FaceCluster} suitable for+ * being shown in the UI.+ *+ * We transform both both remote cluster groups and local-only face clusters+ * into the same "person" object that can be shown in the UI.+ *+ * The cgroups synced with remote do not directly correspond to "people".+ * CGroups represent both positive and negative feedback (i.e, the user does not+ * wish a particular cluster group to be shown in the UI).+ *+ * So while each person has an underlying cgroups, not all cgroups have a+ * corresponding person.+ *+ * Beyond this semantic difference, there is also data massaging: a+ * {@link Person} has data converted into a format that the UI can directly and+ * efficiently use, as compared to a {@link CGroup}, which is tailored for+ * transmission and storage.+ */+export type Person = (+ | { type: "cgroup"; cgroup: CGroup; isHidden: boolean }+ | { type: "cluster"; cluster: FaceCluster }+) & {+ /**+ * Nanoid of the underlying cgroup or {@link FaceCluster}.+ */+ id: string;+ /**+ * The name of the person.+ *+ * This will only be set for named cgroups.+ */+ name: string | undefined;+ /**+ * IDs of the (unique) files in which this face occurs.+ */+ fileIDs: number[];+ /**+ * True if the person has been pinned by the user.+ */+ isPinned: boolean;+ /**+ * True if the person should be hidden from memories.+ */+ hideFromMemories: boolean;+ /**+ * The face that should be used as the "cover" face to represent this+ * {@link Person} in the UI.+ */+ displayFaceID: string;+ /**+ * The {@link EnteFile} which contains the display face.+ */+ displayFaceFile: EnteFile;+};++/**+ * A person of type "cgroup".+ */+export type CGroupPerson = Exclude<Person, { type: "cluster" }>;++/**+ * A person of type "cluster".+ */+export type ClusterPerson = Exclude<Person, { type: "cgroup" }>;++/**+ * A {@link Person} whose name is not empty.+ */+export type NamedPerson = Person & { name: string };++/**+ * A face ID annotated with the {@link EnteFile} that contains it.+ *+ * Both these pieces of information are needed for a UI element to show the+ * face.+ */+export interface PreviewableFace {+ /** The ID of the face to display. */+ faceID: string;+ /** The {@link EnteFile} which contains this face. */+ file: EnteFile;+}++/**+ * Pre-computed in-memory state for UI that deals with people.+ */+export interface PeopleState {+ /**+ * List of all people.+ *+ * The list is sorted such that named people are first, then the local only+ * unnamed clusters. Within each section, people are sorted by the number of+ * files that they reference.+ */+ people: Person[];+ /**+ * List of all people who should be normally shown in the UI.+ *+ * By default, people derived from small, local-only clusters are not+ * surfaced in the UI. Such people will be present in the {@link people}+ * list, but not in the {@link visiblePeople} list. The user can still see+ * these people by clicking on one of the faces they contain from a photo's+ * info view.+ */+ visiblePeople: Person[];+ /**+ * faceID => person+ *+ * {@link people}, but indexed by face (ids).+ */+ personByFaceID: Map<string, Person>;+}++/**+ * Construct an in-memory people state using the data present locally, ignoring+ * faces belonging to deleted and hidden files.+ *+ * This function is meant to run after files, cgroups and faces have been synced+ * with remote, and clustering has completed. It uses the current local state to+ * construct an in-memory list of {@link Person}s on which the UI will operate.+ */+export const reconstructPeopleState = async (): Promise<PeopleState> => {+ const normalCollectionFiles = await computeNormalCollectionFilesFromSaved();+ const fileByID = new Map(normalCollectionFiles.map((f) => [f.id, f]));++ // "Person face"s are faces annotated with their corresponding local files.+ //+ // Note that since we ignore deleted and hidden files, it is possible that+ // there might not be an entry for a particular face in this map even if its+ // file is otherwise existent.+ const personFaceByID = new Map<+ string,+ { faceID: string; file: EnteFile; score: number }+ >();++ const faceIndexes = await savedFaceIndexes();+ for (const { faces } of faceIndexes) {+ for (const { faceID, score } of faces) {+ const fileID = fileIDFromFaceID(faceID);+ if (!fileID) continue;+ const file = fileByID.get(fileID);+ if (!file) continue;+ personFaceByID.set(faceID, { faceID, file, score });+ }+ }++ // Return annotated "person faces" corresponding to the given face ids,+ // sorting them by the creation time of the file they belong to.+ //+ // Within the same file, sort by the face score.+ const personFacesSortedNewestFirst = (faceIDs: string[]) =>+ faceIDs+ .map((faceID) => personFaceByID.get(faceID))+ .filter((pf) => !!pf)+ .sort((a, b) => {+ const at = fileCreationTime(a.file);+ const bt = fileCreationTime(b.file);+ return bt == at ? b.score - a.score : bt - at;+ });++ // Help out tsc.+ type Interim = (Person | undefined)[];++ // Convert cgroups to people.+ const cgroups = await savedCGroups();+ const cgroupPeople: Interim = cgroups.map((cgroup) => {+ const { id, data } = cgroup;+ const { name, assigned } = data;++ let isHidden = data.isHidden;++ // Older versions of the mobile app marked hidden cgroups by setting+ // their name to an empty string.+ if (!name) isHidden = true;++ let assignedFaceIDs: string[][];+ if (data.rejectedFaceIDs.length == 0) {+ // Fast path for when there are no rejected faces.+ assignedFaceIDs = assigned.map(({ faces }) => faces);+ } else {+ const rejectedFaceIDs = new Set(data.rejectedFaceIDs);+ assignedFaceIDs = assigned.map(({ faces }) =>+ faces.filter((id) => !rejectedFaceIDs.has(id)),+ );+ }++ // Person faces from all the clusters assigned to this cgroup, sorted by+ // recency (then score).+ const faces = personFacesSortedNewestFirst(assignedFaceIDs.flat());++ // Ignore this cgroup if we don't have visible faces left in it.+ const mostRecentFace = faces[0];+ if (!mostRecentFace) return undefined;++ // IDs of the files containing this face, plus any files manually+ // associated with this person.+ const fileIDsSet = new Set(faces.map((f) => f.file.id));+ for (const fileID of data.manuallyAssigned) {+ // Only include normal (non-hidden, non-deleted) files.+ if (fileByID.has(fileID)) fileIDsSet.add(fileID);+ }+ const fileIDs = [...fileIDsSet];++ // Avatar face ID, or the highest scoring face.+ let avatarFile: EnteFile | undefined;+ const avatarFaceID = resolvedAvatarFaceID(data.avatarFaceID);+ if (avatarFaceID) {+ const avatarFileID = fileIDFromFaceID(avatarFaceID);+ if (avatarFileID) avatarFile = fileByID.get(avatarFileID);+ }++ let displayFaceID: string;+ let displayFaceFile: EnteFile;+ if (avatarFaceID && avatarFile) {+ displayFaceID = avatarFaceID;+ displayFaceFile = avatarFile;+ } else {+ displayFaceID = mostRecentFace.faceID;+ displayFaceFile = mostRecentFace.file;+ }++ const isPinned = data.isPinned ?? false;+ const hideFromMemories = data.hideFromMemories ?? false;++ return {+ type: "cgroup",+ cgroup,+ id,+ name,+ fileIDs,+ displayFaceID,+ displayFaceFile,+ isHidden,+ isPinned,+ hideFromMemories,+ };+ });++ // Convert local-only clusters to people.+ const localClusters = await savedFaceClusters();+ const clusterPeople: Interim = localClusters.map((cluster) => {+ const faces = personFacesSortedNewestFirst(cluster.faces);++ // Ignore this cluster if we don't have visible faces left in it.+ const mostRecentFace = faces[0];+ if (!mostRecentFace) return undefined;++ return {+ type: "cluster",+ cluster,+ id: cluster.id,+ name: undefined,+ fileIDs: [...new Set(faces.map((f) => f.file.id))],+ displayFaceID: mostRecentFace.faceID,+ displayFaceFile: mostRecentFace.file,+ isPinned: false,+ hideFromMemories: false,+ };+ });++ const sorted = (ps: Interim) =>+ ps+ .filter((c): c is Person => !!c)+ .sort((a, b) =>+ a.isPinned == b.isPinned+ ? b.fileIDs.length - a.fileIDs.length+ : a.isPinned+ ? -1+ : 1,+ );++ const people = sorted(cgroupPeople).concat(sorted(clusterPeople));++ const visiblePeople = people.filter((p) => {+ switch (p.type) {+ case "cgroup":+ // Hidden cgroups are clusters specifically marked so as to not+ // be shown in the UI. The user can still see them from within+ // file info if they wish.+ if (p.isHidden) return false;+ break;++ case "cluster":+ // Ignore local only clusters with too few visible faces.+ if (p.cluster.faces.length < 10) return false;+ break;+ }++ // Show it.+ return true;+ });++ // Reverse map for easy lookup.+ const personByFaceID = new Map<string, Person>();+ for (const person of people) {+ const faceIDs =+ person.type == "cgroup"+ ? person.cgroup.data.assigned.map((c) => c.faces).flat()+ : person.cluster.faces;+ for (const faceID of faceIDs) {+ personByFaceID.set(faceID, person);+ }+ }++ return { people, visiblePeople, personByFaceID };+};++/**+ * Older versions of the mobile app set the avatarFileID as the avatarFaceID.+ * Use the format of the string to detect such cases, and as a workaround,+ * ignore the avatarID in such cases.+ */+const resolvedAvatarFaceID = (avatarFaceID: string | undefined) =>+ avatarFaceID?.split("_").length == 1 ? undefined : avatarFaceID;++/**+ * Return only those from amongst {@link people} that have a name defined.+ *+ * @param people List of all people, named and unnamed.+ */+export const filterNamedPeople = (people: Person[]): NamedPerson[] => {+ const namedPeople: NamedPerson[] = [];+ for (const person of people) {+ const name = person.name;+ if (name) {+ namedPeople.push({ ...person, name });+ }+ }+ return namedPeople;+};++export type PreviewableCluster = FaceCluster & {+ /**+ * A list of up to 3 "preview" faces for the cluster, each annotated with+ * the corresponding {@link EnteFile} that contains them.+ */+ previewFaces: PreviewableFace[];+};++export interface PersonSuggestionsAndChoices {+ /**+ * Previously saved choices.+ *+ * These are clusters (sorted by size) that the user had previously assigned+ * to or explicitly rejected from the person under consideration.+ *+ * The {@link assigned} flag will true for the entries that correspond to+ * assigned clusters, and false for those that the user had rejected.+ *+ * This array is guaranteed to be non-empty, and it is guaranteed that the+ * first item is a merged cluster (i.e. a cluster for which assigned is+ * true), even if there exists an ignored cluster with a larger size. The+ * rest of the entries are intermixed and sorted by size normally.+ *+ * For convenience of the UI, the first entry will have also have the+ * {@link fixed} flag set.+ */+ choices: (PreviewableCluster & { fixed?: boolean; assigned: boolean })[];+ /**+ * New suggestions to offer to the user.+ */+ suggestions: PreviewableCluster[];+}++/**+ * Returns suggestions and existing choices for the given person.+ */+export const _suggestionsAndChoicesForPerson = async (+ person: CGroupPerson,+ currentUserID: number,+): Promise<PersonSuggestionsAndChoices> => {+ const startTime = Date.now();++ const rejectedFaceIDs = new Set(person.cgroup.data.rejectedFaceIDs);+ const personClusters = person.cgroup.data.assigned.map((cluster) => ({+ ...cluster,+ faces: cluster.faces.filter((id) => !rejectedFaceIDs.has(id)),+ }));++ const rejectedClusterIDs = new Set(+ await savedRejectedClustersForCGroup(person.cgroup.id),+ );++ const localClusters = await savedFaceClusters();+ const faceIndexes = await savedFaceIndexes();++ const embeddingByFaceID = new Map(+ faceIndexes+ .map(({ faces }) =>+ faces.map(+ (f) => [f.faceID, new Float32Array(f.embedding)] as const,+ ),+ )+ .flat(),+ );++ const personFaceEmbeddings = personClusters+ .map(({ faces }) => faces.map((id) => embeddingByFaceID.get(id)))+ .flat()+ .filter((e) => !!e);++ // Randomly sample faces to limit the O(n^2) cost.+ const sampledPersonEmbeddings = randomSample(personFaceEmbeddings, 50);++ const strictMedianSimilarityThreshold = 0.48;+ const relaxedMedianSimilarityThreshold = 0.46;++ const multiFaceClusters: FaceCluster[] = [];+ const singletonClusters: FaceCluster[] = [];+ const rejectedClusters: FaceCluster[] = [];+ for (const cluster of localClusters) {+ const { id, faces } = cluster;++ // User has explicitly asked us to ignore this cluster. Add it to the+ // list of rejected clusters that we return to the UI for listing out.+ // Keep this check first so that we pick these up even if we get e.g.+ // singleton clusters from remote.+ if (rejectedClusterIDs.has(id)) {+ rejectedClusters.push(cluster);+ continue;+ }++ if (faces.length < 2) {+ singletonClusters.push(cluster);+ continue;+ }+ multiFaceClusters.push(cluster);+ }++ const scoreClustersByMedianSimilarity = (clusters: FaceCluster[]) => {+ const clustersAndSimilarity: [FaceCluster, number][] = [];+ for (const cluster of clusters) {+ const { faces } = cluster;++ const sampledOtherEmbeddings = randomSample(faces, 50)+ .map((id) => embeddingByFaceID.get(id))+ .filter((e) => !!e);++ // Sort all cosine similarities pairs, and consider their median.+ const csims: number[] = [];+ for (const other of sampledOtherEmbeddings) {+ for (const embedding of sampledPersonEmbeddings) {+ csims.push(dotProduct(embedding, other));+ }+ }+ csims.sort();++ if (csims.length == 0) continue;++ const medianSim = csims[Math.floor(csims.length / 2)]!;+ clustersAndSimilarity.push([cluster, medianSim]);+ }+ // Sort suggestions by the (median) cosine similarity.+ clustersAndSimilarity.sort(([, a], [, b]) => b - a);+ return clustersAndSimilarity;+ };++ const selectCandidateClusters = ({+ candidates,+ minMedianSimilarity,+ }: {+ candidates: [FaceCluster, number][];+ minMedianSimilarity: number;+ }) =>+ candidates+ .filter(+ ([, medianSimilarity]) =>+ medianSimilarity > minMedianSimilarity,+ )+ .map(([cluster]) => cluster);++ // Keep singleton suggestions as a last resort to minimize regressions while+ // still reducing "no suggestions" outcomes.+ const multiFaceCandidateClustersAndSimilarity =+ scoreClustersByMedianSimilarity(multiFaceClusters);+ let suggestionMode = "strict_non_singleton";+ let suggestedClusters = selectCandidateClusters({+ candidates: multiFaceCandidateClustersAndSimilarity,+ minMedianSimilarity: strictMedianSimilarityThreshold,+ });+ if (suggestedClusters.length == 0) {+ suggestionMode = "relaxed_non_singleton";+ suggestedClusters = selectCandidateClusters({+ candidates: multiFaceCandidateClustersAndSimilarity,+ minMedianSimilarity: relaxedMedianSimilarityThreshold,+ });+ }+ if (suggestedClusters.length == 0) {+ suggestionMode = "strict_with_singletons";+ const singletonCandidateClustersAndSimilarity =+ scoreClustersByMedianSimilarity(singletonClusters);+ suggestedClusters = selectCandidateClusters({+ candidates: singletonCandidateClustersAndSimilarity,+ minMedianSimilarity: strictMedianSimilarityThreshold,+ });+ }++ // Annotate the clusters with the information that the UI needs to show its+ // preview faces.+ const normalCollectionFiles =+ await computeNormalCollectionFilesFromSaved(currentUserID);+ const fileByID = new Map(normalCollectionFiles.map((f) => [f.id, f]));++ const toPreviewable = (cluster: FaceCluster) => {+ const previewFaces: PreviewableFace[] = [];+ for (const faceID of cluster.faces) {+ const fileID = fileIDFromFaceID(faceID);+ if (!fileID) {+ assertionFailed();+ continue;+ }++ const file = fileByID.get(fileID);+ if (!file) {+ // This might be a hidden/trash file, and it is thus not+ // appropriate to use it as a preview file anyway.+ continue;+ }++ previewFaces.push({ file, faceID });++ if (previewFaces.length == 4) break;+ }++ if (previewFaces.length == 0) return undefined;++ return { ...cluster, previewFaces };+ };++ const toPreviewableList = (clusters: FaceCluster[]) =>+ clusters.map(toPreviewable).filter((p) => !!p);++ const sortBySize = (entries: { faces: unknown[] }[]) =>+ entries.sort((a, b) => b.faces.length - a.faces.length);++ const assignedChoices = toPreviewableList(personClusters).map((p) => ({+ ...p,+ assigned: true,+ }));++ sortBySize(assignedChoices);++ const rejectedChoices = toPreviewableList(rejectedClusters).map((p) => ({+ ...p,+ assigned: false,+ }));++ // Ensure that the first item in the choices is not an ignored one, even if+ // that is what we'd have ended up with if we sorted by size.++ const firstChoice = { ...assignedChoices[0]!, fixed: true };+ const restChoices = assignedChoices.slice(1).concat(rejectedChoices);+ sortBySize(restChoices);++ const choices = [firstChoice, ...restChoices];++ // Limit to the number of suggestions shown in a single go.+ const suggestions = toPreviewableList(suggestedClusters.slice(0, 80));++ log.info(+ `Generated ${suggestions.length} suggestions for ${person.id} using ${suggestionMode} (${Date.now() - startTime} ms)`,+ );++ return { choices, suggestions };+};++/**+ * A map specifying the changes to make when the user presses the save button on+ * the people suggestions dialog.+ *+ * Each entry is a (clusterID, update) pair.+ *+ * * Clusters with "assign" should be assigned to the cgroup,+ * * Clusters with "rejectSuggestion" should be rejected from the cgroup+ * locally. These correspond to suggestions which the user did not accept.+ * * Clusters with "rejectSavedChoice" should be rejected from the cgroup both+ * locally and on remote. These correspond to saved choices which the user+ * went on to explicitly reject.+ * * Clusters with "reset" should be reset - i.e. should be removed from both+ * the assigned and rejected choices associated with the cgroup (if needed).+ */+export type PersonSuggestionUpdates = Map<+ string,+ "assign" | "rejectSuggestion" | "rejectSavedChoice" | "reset"+>;++/**+ * Implementation for the "save" action on the SuggestionsDialog.+ *+ * This function modifies remote and local state to reflect the given+ * {@link updates} for {@link cgroup}.+ *+ * @param cgroup The cgroup that we want to update.+ *+ * @param updates The changes to make. See {@link PersonSuggestionUpdates}.+ *+ * @param masterKey The user's masterKey (as a base64 string), which is is used+ * to encrypt and decrypt the entity key associated with cgroups.+ */+export const _applyPersonSuggestionUpdates = async (+ cgroup: CGroup,+ updates: PersonSuggestionUpdates,+ masterKey: string,+) => {+ const localClusters = await savedFaceClusters();++ let assignedClusters = [...cgroup.data.assigned];+ let rejectedClusterIDs = await savedRejectedClustersForCGroup(cgroup.id);+ let newlyRejectedFaceIDs: string[] = [];++ let assignUpdateCount = 0;+ let rejectUpdateCount = 0;++ const clusterWithID = (clusterID: string) =>+ localClusters.find((c) => c.id == clusterID)!;++ // Add cluster with `clusterID` to the list of assigned clusters.+ const assign = (clusterID: string) => {+ const cluster = clusterWithID(clusterID);+ assignedClusters.push(cluster);+ assignUpdateCount += 1;+ };++ // Remove cluster with `clusterID` from the list of assigned clusters (if+ // needed).+ const unassignIfNeeded = (clusterID: string) => {+ if (assignedClusters.find(({ id }) => id == clusterID)) {+ const [updatedAssignedClusters, cluster] = assignedClusters.reduce<+ [FaceCluster[], FaceCluster | undefined]+ >(+ ([clusters, foundCluster], c) => {+ if (c.id == clusterID) return [clusters, c];+ clusters.push(c);+ return [clusters, foundCluster];+ },+ [[], undefined],+ );++ assignedClusters = updatedAssignedClusters;+ assignUpdateCount += 1;+ // Prior to this, this cluster was not saved locally since it was+ // part of the remote data. Since we're removing it from the remote+ // state, add it to the local state instead so that the user can see+ // it in their saved choices (local only).+ localClusters.push(cluster!);+ }+ };++ // Add `clusterID` to the list of rejected clusters locally.+ const rejectClusterLocal = (clusterID: string) => {+ rejectedClusterIDs.push(clusterID);+ rejectUpdateCount += 1;+ };++ // Mark the faces in `clusterID` as rejected on remote.+ const rejectFacesRemote = (clusterID: string) => {+ const cluster = clusterWithID(clusterID);+ newlyRejectedFaceIDs = newlyRejectedFaceIDs.concat(cluster.faces);+ };++ // Remove `clusterID` from the list of rejected clusters (if needed).+ const unrejectIfNeeded = (clusterID: string) => {+ if (rejectedClusterIDs.includes(clusterID)) {+ rejectedClusterIDs = rejectedClusterIDs.filter(+ (id) => id != clusterID,+ );+ rejectUpdateCount += 1;+ }+ };++ for (const [clusterID, assigned] of updates.entries()) {+ switch (assigned) {+ case "assign":+ assign(clusterID);+ unrejectIfNeeded(clusterID);+ break;++ case "rejectSuggestion":+ unassignIfNeeded(clusterID);+ rejectClusterLocal(clusterID);+ break;++ case "rejectSavedChoice":+ unassignIfNeeded(clusterID);+ rejectClusterLocal(clusterID);+ rejectFacesRemote(clusterID);+ break;++ case "reset":+ unassignIfNeeded(clusterID);+ unrejectIfNeeded(clusterID);+ break;+ }+ }++ if (assignUpdateCount > 0 || newlyRejectedFaceIDs.length > 0) {+ const assigned = assignedClusters;+ const rejectedFaceIDs =+ cgroup.data.rejectedFaceIDs.concat(newlyRejectedFaceIDs);+ await updateOrCreateUserEntities(+ "cgroup",+ [+ {+ ...cgroup,+ data: { ...cgroup.data, assigned, rejectedFaceIDs },+ },+ ],+ masterKey,+ );+ await saveFaceClusters(localClusters);+ }++ if (rejectUpdateCount > 0) {+ await saveRejectedClustersForCGroup(cgroup.id, rejectedClusterIDs);+ }++ log.info(+ `Updated ${assignUpdateCount} assigns and ${rejectUpdateCount} rejects for ${cgroup.id}`,+ );+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/worker-types.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/worker-types.tsnew file mode 100644index 0000000000..16153b3b2b--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/worker-types.ts@@ -0,0 +1,40 @@+/**+ * @file Types for the objects shared between the main thread and the ML worker.+ */++/**+ * Callbacks invoked by the worker at various points in the indexing and+ * clustering pipeline to notify the main thread of events it might be+ * interested in.+ */+export interface MLWorkerDelegate {+ /**+ * Called whenever the worker does some action that might need the UI state+ * indicating the indexing or clustering status to be updated.+ */+ workerDidUpdateStatus: () => void;+ /**+ * Called when the worker indexes some files, but then notices that the main+ * thread was not awaiting the indexing (e.g. it was not initiated by the+ * main thread during a sync, but happened because of a live upload).+ *+ * In such cases, it uses this method to inform the main thread that some+ * files were indexed, so that it can update any dependent state (e.g.+ * clusters).+ *+ * It doesn't always call this because otherwise the main thread would need+ * some extra code to avoid updating the dependent state twice.+ */+ workerDidUnawaitedIndex: () => void;+}++/**+ * The result of file ids that should be considered as matches for a particular+ * search phrase, each with their associated score.+ *+ * This is a map of file (IDs) that should be shown in the search results.+ * They're returned as a map from fileIDs to the scores they got (higher is+ * better). This map will only contains entries whose score was above our+ * minimum threshold.+ */+export type CLIPMatches = Map<number, number>;diff --git a/web/apps/albums/vendor/ente-new/photos/services/ml/worker.ts b/web/apps/albums/vendor/ente-new/photos/services/ml/worker.tsnew file mode 100644index 0000000000..919f9fef77--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/ml/worker.ts@@ -0,0 +1,653 @@+import { expose, wrap } from "comlink";+import { clientIdentifier } from "ente-base/app";+import { assertionFailed } from "ente-base/assert";+import { isHTTP4xxError, isHTTPErrorWithStatus } from "ente-base/http";+import log from "ente-base/log";+import { logUnhandledErrorsAndRejectionsInWorker } from "ente-base/log-web";+import type { ElectronMLWorker } from "ente-base/types/ipc";+import { isNetworkDownloadError } from "ente-gallery/services/download";+import type { ProcessableUploadItem } from "ente-gallery/services/upload";+import { fileLogID, type EnteFile } from "ente-media/file";+import { savedTrashItemFileIDs } from "ente-new/photos/services/trash";+import { wait } from "ente-utils/promise";+import { savedCollectionFiles } from "../photos-fdb";+import {+ createImageBitmapAndData,+ fetchRenderableBlob,+ type ImageBitmapAndData,+} from "./blob";+import {+ _clipMatches,+ clearCachedCLIPIndexes,+ clipIndexingVersion,+ indexCLIP,+ type CLIPIndex,+} from "./clip";+import {+ _clusterFaces,+ reconcileClusters,+ type ClusteringProgress,+} from "./cluster";+import { saveFaceCrops } from "./crop";+import {+ markIndexingFailed,+ readNextIndexableFileIDs,+ savedFaceIndexes,+ saveIndexes,+ updateAssumingLocalFiles,+} from "./db";+import { faceIndexingVersion, indexFaces, type FaceIndex } from "./face";+import {+ fetchMLData,+ putMLData,+ type RawRemoteMLData,+ type RemoteMLData,+} from "./ml-data";+import { _suggestionsAndChoicesForPerson, type CGroupPerson } from "./people";+import type { CLIPMatches, MLWorkerDelegate } from "./worker-types";++/**+ * A rough hint at what the worker is up to.+ *+ * - "init": Worker has been created but hasn't done anything yet.+ * - "idle": Not doing anything+ * - "tick": Transitioning to a new state+ * - "indexing": Indexing+ * - "fetching": A subset of indexing+ *+ * During indexing, the state is set to "fetching" whenever remote provided us+ * data for more than 50% of the files that we requested from it in the last+ * fetch during indexing.+ */+export type WorkerState = "init" | "idle" | "tick" | "indexing" | "fetching";++const idleDurationStart = 5; /* 5 seconds */+const idleDurationMax = 16 * 60; /* 16 minutes */++interface IndexableItem {+ /**+ * The {@link EnteFile} to (potentially) index.+ */+ file: EnteFile;+ /**+ * If the file was uploaded from the current client, then its contents.+ */+ processableUploadItem: ProcessableUploadItem | undefined;+ /**+ * The existing ML data (if any) on remote corresponding to this file.+ */+ remoteMLData: RemoteMLData | undefined;+}++/**+ * Run operations related to machine learning (e.g. indexing) in a Web Worker.+ *+ * This is a normal class that is however exposed (via comlink) as a proxy+ * running inside a Web Worker. This way, we do not bother the main thread with+ * tasks that might degrade interactivity.+ *+ * Conceptually, the MLWorker state machine is as follows:+ *+ * ext. event state then state+ * ------------- --------------- --------------+ * sync -> "backfillq" -> "idle"+ * upload -> "liveq" -> "idle"+ * idleTimeout -> "backfillq" -> "idle"+ *+ * where:+ *+ * - "liveq": indexing items that are being uploaded,+ * - "backfillq": index unindexed items otherwise.+ * - "idle": in between state transitions.+ *+ * In addition, MLWorker can also be invoked for interactive tasks: in+ * particular, for finding the closest CLIP match when the user does a search.+ */+export class MLWorker {+ /** The last known state of the worker. */+ public state: WorkerState = "init";+ /** If the worker is currently clustering, then its last known progress. */+ public clusteringProgress: ClusteringProgress | undefined;++ private electron: ElectronMLWorker | undefined;+ private delegate: MLWorkerDelegate | undefined;+ private liveQ: IndexableItem[] = [];+ private idleTimeout: ReturnType<typeof setTimeout> | undefined;+ private idleDuration = idleDurationStart; /* unit: seconds */+ /** Resolvers for pending promises returned from calls to {@link index}. */+ private onNextIdles: ((count: number) => void)[] = [];+ /**+ * Number of items processed since the last time {@link onNextIdles} was+ * drained.+ */+ private countSinceLastIdle = 0;++ /**+ * Initialize a new {@link MLWorker}.+ *+ * This is conceptually the constructor, however it is easier to have this+ * as a separate function to avoid complicating the comlink types further.+ *+ * @param port A {@link MessagePort} that allows us to communicate with an+ * Electron utility process running in the Node.js layer of our desktop app,+ * exposing an object that conforms to the {@link ElectronMLWorker}+ * interface.+ *+ * @param delegate The {@link MLWorkerDelegate} the worker can use to inform+ * the main thread of interesting events.+ */+ init(port: MessagePort, delegate: MLWorkerDelegate) {+ this.electron = wrap<ElectronMLWorker>(port);+ this.delegate = delegate;+ }++ /**+ * Start backfilling if needed, and return after there are no more items+ * remaining to backfill.+ *+ * During a backfill, we first attempt to fetch ML data for files which+ * don't have that data locally. If on fetching we find what we need, we+ * save it locally. Otherwise we index them.+ *+ * @return The count of items processed since the last last time we were+ * idle.+ */+ index() {+ const nextIdle = new Promise<number>((resolve) =>+ this.onNextIdles.push(resolve),+ );+ this.wakeUp();+ return nextIdle;+ }++ /** Invoked in response to external events. */+ private wakeUp() {+ if (this.state == "init" || this.state == "idle") {+ // We are currently paused. Get back to work.+ if (this.idleTimeout) clearTimeout(this.idleTimeout);+ this.idleTimeout = undefined;+ // Change state so that multiple calls to `wakeUp` don't cause+ // multiple calls to `tick`.+ this.state = "tick";+ // Enqueue a tick.+ void this.tick();+ } else {+ // In the middle of a task. Do nothing, `this.tick` will+ // automatically be invoked when the current task finishes.+ }+ }++ /**+ * Called when a file is uploaded from the current client.+ *+ * This is a great opportunity to index since we already have the file with+ * us and won't need to download the file from remote.+ */+ onUpload(file: EnteFile, processableUploadItem: ProcessableUploadItem) {+ // Add the recently uploaded file to the live indexing queue.+ this.liveQ.push({+ file,+ processableUploadItem,+ remoteMLData: undefined,+ });+ this.wakeUp();+ }++ /**+ * Find {@link CLIPMatches} for a given normalized {@link searchPhrase}.+ */+ async clipMatches(searchPhrase: string): Promise<CLIPMatches | undefined> {+ return _clipMatches(searchPhrase, this.electron!);+ }++ private async tick() {+ log.debug(() => [+ "ml/tick",+ {+ state: this.state,+ liveQ: this.liveQ,+ idleDuration: this.idleDuration,+ },+ ]);++ const scheduleTick = () => void setTimeout(() => this.tick(), 0);++ const liveQ = this.liveQ;+ this.liveQ = [];++ // Retain the previous state if it was one of the indexing states. This+ // prevents jumping between "fetching" and "indexing" being shown in the+ // UI during the initial load.+ if (this.state != "fetching" && this.state != "indexing")+ this.state = "indexing";++ // Use the liveQ if present, otherwise get the next batch to backfill.+ const items = liveQ.length+ ? liveQ+ : await this.backfillQ().catch((e: unknown) => {+ // Ignore the error (e.g. a network failure) when determining+ // the items to backfill, and return an empty items array so+ // that the next retry happens after an exponential backoff.+ log.warn("Ignoring error when determining backfillQ", e);+ return [];+ });++ this.countSinceLastIdle += items.length;++ // If there is items remaining,+ if (items.length > 0) {+ // Index them.+ const indexedCount = await indexNextBatch(+ items,+ this.electron!,+ this.delegate,+ );+ if (indexedCount > 0) {+ // We made some progress, so there are no complete blockers+ // (e.g. network being offline). Reset the idle duration and+ // move on to the next batch (if any).+ this.idleDuration = idleDurationStart;+ // And tick again.+ scheduleTick();+ return;+ }+ }++ // We come here in three scenarios - either there is nothing left to do,+ // or we cannot currently do it (e.g. user is offline), or we+ // encountered failures during indexing.+ //+ // Failures are not really expected, so something unexpected might be+ // going on, or remote might be having issues.+ //+ // So in all cases, we pause for exponentially longer durations of time+ // (limited to some maximum).++ this.state = "idle";+ this.idleDuration = Math.min(this.idleDuration * 2, idleDurationMax);+ this.idleTimeout = setTimeout(scheduleTick, this.idleDuration * 1000);+ this.delegate?.workerDidUpdateStatus();++ // Resolve any awaiting promises returned from `index`.+ const onNextIdles = this.onNextIdles;+ const countSinceLastIdle = this.countSinceLastIdle;+ this.onNextIdles = [];+ this.countSinceLastIdle = 0;+ onNextIdles.forEach((f) => f(countSinceLastIdle));++ // If no one was waiting, then let the main thread know via a different+ // channel so that it can update the clusters and people.+ if (onNextIdles.length == 0 && countSinceLastIdle > 0) {+ this.delegate?.workerDidUnawaitedIndex();+ }+ }++ /** Return the next batch of items to backfill (if any). */+ private async backfillQ() {+ // Find files that our local DB thinks need syncing.+ const fileByID = await syncWithLocalFilesAndGetFilesToIndex(200);+ if (!fileByID.size) return [];++ // Fetch their existing ML data (if any).+ const mlDataByID = await fetchMLData(fileByID);++ // If the number of files for which remote gave us data is more than 50%+ // of what we asked of it, assume we are "fetching", not "indexing".+ // This is a heuristic to try and show a better indexing state in the UI+ // (so that the user does not think that their files are being+ // unnecessarily reindexed).+ if (this.state != "indexing" && this.state != "fetching")+ assertionFailed(`Unexpected state ${this.state}`);+ this.state =+ mlDataByID.size * 2 > fileByID.size ? "fetching" : "indexing";++ // Return files after annotating them with their existing ML data.+ return Array.from(fileByID, ([id, file]) => ({+ file,+ processableUploadItem: undefined,+ remoteMLData: mlDataByID.get(id),+ }));+ }++ /**+ * Run face clustering on all faces, and update both local and remote state+ * as appropriate.+ *+ * This should only be invoked when the face indexing (including syncing+ * with remote) is complete so that we cluster the latest set of faces, and+ * after we have fetched the latest cgroups from remote (so that we do no+ * overwrite any remote updates).+ *+ * @param masterKey The user's master key (as a base64 string), required for+ * updating remote cgroups if needed.+ */+ async clusterFaces(masterKey: string) {+ const { clusters, modifiedClusterIDs } = await _clusterFaces(+ await savedFaceIndexes(),+ await savedCollectionFiles(),+ (progress) => this.updateClusteringProgress(progress),+ );+ await reconcileClusters(clusters, modifiedClusterIDs, masterKey);+ this.updateClusteringProgress(undefined);+ }++ private updateClusteringProgress(progress: ClusteringProgress | undefined) {+ this.clusteringProgress = progress;+ this.delegate?.workerDidUpdateStatus();+ }++ /**+ * Return suggestions and choices for the given cgroup {@link person}.+ */+ async suggestionsAndChoicesForPerson(+ person: CGroupPerson,+ currentUserID: number,+ ) {+ return _suggestionsAndChoicesForPerson(person, currentUserID);+ }+}++expose(MLWorker);++logUnhandledErrorsAndRejectionsInWorker();++/**+ * Index the given batch of items.+ *+ * @returns the count of items which were indexed.+ */+const indexNextBatch = async (+ items: IndexableItem[],+ electron: ElectronMLWorker,+ delegate: MLWorkerDelegate | undefined,+) => {+ // Don't try to index if we wouldn't be able to upload them anyway. The+ // liveQ has already been drained, but that's fine, it'll be rare that we+ // were able to upload just a bit ago but don't have network now.+ if (!self.navigator.onLine) {+ log.info("Skipping ML indexing since we are not online");+ return 0;+ }++ // Keep track if any of the items failed.+ let failureCount = 0;++ // Index up to 4 items simultaneously.+ const tasks = new Array<Promise<void> | undefined>(4).fill(undefined);++ let i = 0;+ while (i < items.length) {+ for (let j = 0; j < tasks.length; j++) {+ if (i < items.length && !tasks[j]) {+ // Use an IIFE to capture the value of j at the time of+ // invocation.+ tasks[j] = ((item: IndexableItem, j: number) =>+ index(item, electron)+ .then(() => {+ tasks[j] = undefined;+ })+ .catch((e: unknown) => {+ const f = fileLogID(item.file);+ log.error(`Failed to index ${f}`, e);+ failureCount++;+ tasks[j] = undefined;+ }))(items[i++]!, j);+ }+ }++ // Wait for at least one to complete (the other runners continue running+ // even if one promise reaches the finish line).+ await Promise.race(tasks);++ // Let the main thread now we're doing something.+ delegate?.workerDidUpdateStatus();++ // Let us drain the microtask queue. This also gives a chance for other+ // interactive tasks like `clipMatches` to run.+ await wait(0);+ }++ // Wait for the pending tasks to drain out.+ await Promise.all(tasks);++ // Clear any cached CLIP indexes, since now we might have new ones.+ clearCachedCLIPIndexes();++ const indexedCount = items.length - failureCount;++ log.info(+ failureCount > 0+ ? `Indexed ${indexedCount} files (${failureCount} failed)`+ : `Indexed ${items.length} files`,+ );++ // Return the count of indexed files.+ return indexedCount;+};++/**+ * Sync face DB with the local (and potentially indexable) files that we know+ * about. Then return the next {@link count} files that still need to be+ * indexed.+ *+ * When returning from amongst pending files, prefer the most recent ones first.+ *+ * For specifics of what a "sync" entails, see {@link updateAssumingLocalFiles}.+ *+ * @param count Limit the resulting list of indexable files to {@link count}.+ */+const syncWithLocalFilesAndGetFilesToIndex = async (+ count: number,+): Promise<Map<number, EnteFile>> => {+ const collectionFiles = await savedCollectionFiles();+ const fileByID = new Map(collectionFiles.map((f) => [f.id, f]));++ await updateAssumingLocalFiles(+ Array.from(fileByID.keys()),+ await savedTrashItemFileIDs(),+ );++ const fileIDsToIndex = await readNextIndexableFileIDs(count);+ return new Map(fileIDsToIndex.map((id) => [id, fileByID.get(id)!]));+};++/**+ * Index file, save the persist the results locally, and put them on remote.+ *+ * Indexing a file involves computing its various ML embeddings: faces and CLIP.+ * Since we have the original file in memory, we also save the face crops.+ *+ * [Note: Transient and permanent indexing failures]+ *+ * We mark indexing for a file as having failed only if there is a good chance+ * that the indexing failed because of some inherent issue with that particular+ * file, and not if there were generic failures (like when trying to save the+ * indexes to remote).+ *+ * When we mark it as failed, then a flag is persisted corresponding to this+ * file in the ML DB so that it won't get reindexed in future runs. This are+ * thus considered as permanent failures.+ *+ * > We might retry these in future versions if we identify reasons for indexing+ * > to fail (it ideally shouldn't) and rectify them.+ *+ * On the other hand, saving the face index to remote might fail for transient+ * issues (network issues, or remote having hiccups). We don't mark a file as+ * failed permanently in such cases, so that it gets retried at some point.+ * These are considered as transient failures.+ *+ * However, it is vary hard to pre-emptively enumerate all possible failure+ * modes, and there is a the possibility of some non-transient failure getting+ * classified as a transient failure and causing the client to try and index the+ * same file again and again, when in fact there is a issue specific to that+ * file which is preventing the index from being saved. What exactly? We don't+ * know, but the possibility exists.+ *+ * To reduce the chances of this happening, we treat HTTP 4xx responses as+ * permanent failures too - there are no known cases where a client retrying a+ * 4xx response would work, and there are expected (but rare) cases where a+ * client might get a non-retriable 4xx (e.g. if the file has over ~700 faces,+ * then remote will return a 413 Request Entity Too Large).+ */+const index = async (+ { file, processableUploadItem, remoteMLData }: IndexableItem,+ electron: ElectronMLWorker,+) => {+ const f = fileLogID(file);+ const fileID = file.id;++ // Massage the existing data (if any) that we got from remote to the form+ // that the rest of this function operates on.+ //+ // Discard any existing data that is made by an older indexing pipelines.+ // See: [Note: Embedding versions]++ const existingRemoteFaceIndex = remoteMLData?.parsed?.face;+ const existingRemoteCLIPIndex = remoteMLData?.parsed?.clip;++ let existingFaceIndex: FaceIndex | undefined;+ if (+ existingRemoteFaceIndex &&+ existingRemoteFaceIndex.version >= faceIndexingVersion+ ) {+ // Destructure the data we got from remote so that we only retain the+ // fields we're interested in the object that gets put into indexed db.+ const { width, height, faces } = existingRemoteFaceIndex;+ existingFaceIndex = { width, height, faces };+ }++ let existingCLIPIndex: CLIPIndex | undefined;+ if (+ existingRemoteCLIPIndex &&+ existingRemoteCLIPIndex.version >= clipIndexingVersion+ ) {+ const { embedding } = existingRemoteCLIPIndex;+ existingCLIPIndex = { embedding };+ }++ // If we already have all the ML data types then just update our local db+ // and return.++ if (existingFaceIndex && existingCLIPIndex) {+ await saveIndexes(+ { fileID, ...existingFaceIndex },+ { fileID, ...existingCLIPIndex },+ );+ return;+ }++ // There is at least one ML data type that still needs to be indexed.++ let renderableBlob: Blob;+ try {+ renderableBlob = await fetchRenderableBlob(+ file,+ processableUploadItem,+ electron,+ );+ } catch (e) {+ // Network errors are transient and shouldn't be marked.+ //+ // See: [Note: Transient and permanent indexing failures]+ if (!isNetworkDownloadError(e)) await markIndexingFailed(fileID);+ throw e;+ }++ let image: ImageBitmapAndData;+ try {+ image = await createImageBitmapAndData(renderableBlob);+ } catch (e) {+ // If we cannot get the raw image data for the file, then retrying again+ // won't help (if in the future we enhance the underlying code for+ // `indexableBlobs` to handle this failing type we can trigger a+ // reindexing attempt for failed files).+ //+ // See: [Note: Transient and permanent indexing failures]+ await markIndexingFailed(fileID);+ throw e;+ }++ try {+ let faceIndex: FaceIndex;+ let clipIndex: CLIPIndex;++ const startTime = Date.now();++ try {+ [faceIndex, clipIndex] = await Promise.all([+ existingFaceIndex ?? indexFaces(file, image, electron),+ existingCLIPIndex ?? indexCLIP(image, electron),+ ]);+ } catch (e) {+ // See: [Note: Transient and permanent indexing failures]+ await markIndexingFailed(fileID);+ throw e;+ }++ log.debug(() => {+ const ms = Date.now() - startTime;+ const msg = [];+ if (!existingFaceIndex) msg.push(`${faceIndex.faces.length} faces`);+ if (!existingCLIPIndex) msg.push("clip");+ return `Indexed ${msg.join(" and ")} in ${f} (${ms} ms)`;+ });++ const remoteFaceIndex = existingRemoteFaceIndex ?? {+ version: faceIndexingVersion,+ client: clientIdentifier,+ ...faceIndex,+ };++ const remoteCLIPIndex = existingRemoteCLIPIndex ?? {+ version: clipIndexingVersion,+ client: clientIdentifier,+ ...clipIndex,+ };++ // Perform an "upsert" by using the existing raw data we got from the+ // remote as the base, and inserting or overwriting any newly indexed+ // parts. See: [Note: Preserve unknown ML data fields].++ const existingRawMLData = remoteMLData?.raw ?? {};+ const rawMLData: RawRemoteMLData = {+ ...existingRawMLData,+ face: remoteFaceIndex,+ clip: remoteCLIPIndex,+ };++ log.debug(() => ["Uploading ML data", rawMLData]);++ try {+ const lastUpdatedAt = remoteMLData?.updatedAt ?? 0;+ await putMLData(file, rawMLData, lastUpdatedAt);+ } catch (e) {+ // See: [Note: Transient and permanent indexing failures]+ if (isHTTP4xxError(e)) {+ // 409 Conflict indicates that we tried overwriting existing+ // mldata. Don't mark it as a failure, the file has already been+ // processed.+ if (!isHTTPErrorWithStatus(e, 409)) {+ await markIndexingFailed(fileID);+ }+ }+ throw e;+ }++ await saveIndexes({ fileID, ...faceIndex }, { fileID, ...clipIndex });++ // This step, saving face crops, is conceptually not part of the+ // indexing pipeline; we just do it here since we have already have the+ // ImageBitmap at hand.+ if (!existingFaceIndex) {+ try {+ await saveFaceCrops(image.bitmap, faceIndex);+ } catch (e) {+ // Ignore errors that happen during this since it does not+ // impact the generated face index.+ log.error(`Failed to save face crops for ${f}`, e);+ }+ }+ } finally {+ image.bitmap.close();+ }+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/photos-fdb.ts b/web/apps/albums/vendor/ente-new/photos/services/photos-fdb.tsnew file mode 100644index 0000000000..2b49a16bfd--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/photos-fdb.ts@@ -0,0 +1,259 @@+/**+ * @file Photos app specific files DB. See: [Note: Files DB].+ */++import {+ LocalCollections,+ LocalEnteFile,+ localForage,+ LocalTimestamp,+ transformFilesIfNeeded,+} from "ente-gallery/services/files-db";+import { type Collection } from "ente-media/collection";+import { type EnteFile } from "ente-media/file";+import { z } from "zod";+import type { TrashItem } from "./trash";++/**+ * Return all collections present in our local database.+ *+ * This includes both normal (non-hidden) and hidden collections.+ *+ * Use {@link saveCollections} to update the database.+ */+export const savedCollections = async (): Promise<Collection[]> =>+ LocalCollections.parse((await localForage.getItem("collections")) ?? []);++/**+ * Replace the list of collections stored in our local database.+ *+ * This is the setter corresponding to {@link savedCollections}.+ *+ * This updates the underlying storage of both normal (non-hidden) and hidden+ * collections (the split between normal and hidden is not at the database level+ * but is a filter when they are accessed).+ */+export const saveCollections = async (collections: Collection[]) => {+ await localForage.setItem("collections", collections);+};++/**+ * Return the locally persisted {@link updationTime} of the latest collection we+ * have pulled from remote.+ *+ * Use {@link saveCollectionsUpdationTime} to update the saved value.+ */+export const savedCollectionsUpdationTime = async () =>+ LocalTimestamp.parse(await localForage.getItem("collection-updation-time"));++/**+ * Update the locally persisted timestamp that will be returned by subsequent+ * calls to {@link savedCollectionsUpdationTime}.+ */+export const saveCollectionsUpdationTime = async (time: number) => {+ await localForage.setItem("collection-updation-time", time);+};++const TrashItemCollectionKey = z.object({+ /**+ * Collection ID.+ */+ id: z.number(),+ /**+ * Decrypted collection key.+ */+ key: z.string(),+});++const TrashItemCollectionKeys = TrashItemCollectionKey.array();++export type TrashItemCollectionKey = z.infer<typeof TrashItemCollectionKey>;++/**+ * Return keys of collections (including potentially deleted ones) referred to+ * by trash items present in our local database.+ *+ * Use {@link saveTrashItemCollectionKeys} to update the database.+ *+ * [Note: Trash item collection keys]+ *+ * Trash items are erstwhile files, and like collection files, they need a+ * collection key to decrypt them.+ *+ * However, it is possible that the collection which contained the file was also+ * deleted. Such deleted collections will not be present in the list returned by+ * {@link savedCollections}.+ *+ * So to still be able to access the collection keys in order to process the+ * trash item, we separately save a list of {collectionID, collectionKey} pairs.+ *+ * - This list contains only collectionsIDs for which there is a corresponding+ * local trash item.+ *+ * - During each trash sync, this list is seeded using {@link savedCollections}.+ * Then, whenever we encounter a collection which is not present locally+ * (since it might've been deleted), we fetch it from remote and add an entry+ * for it in {@link savedTrashItemCollectionKeys}.+ *+ * - Once the sync completes, we updated this list to retain only entries that+ * are still referred to by items remaining in the trash.+ */+export const savedTrashItemCollectionKeys = async (): Promise<+ TrashItemCollectionKey[]+> =>+ TrashItemCollectionKeys.parse(+ // This key name is not accurate, these are not deleted collections but+ // collections referred to by deleted items (so they can include deleted+ // collections, but not exclusively).+ //+ // But since the use of this key name is localized to this file so we+ // let the original name be.+ (await localForage.getItem("deleted-collection")) ?? [],+ );++/**+ * Replace the list of trash item collection keys stored in our local database.+ *+ * This is the setter corresponding to {@link saveTrashItemCollectionKeys}.+ */+export const saveTrashItemCollectionKeys = async (+ cks: TrashItemCollectionKey[],+) => {+ await localForage.setItem("deleted-collection", cks);+};++/**+ * Return all files present in our local database.+ *+ * These are "collection files", meaning that there might be multiple entries+ * for the same file, one for each collection that the file belongs to. For more+ * details, See: [Note: Collection File].+ *+ * Use {@link saveCollectionFiles} to update the database.+ */+export const savedCollectionFiles = async (): Promise<EnteFile[]> => {+ // [Note: Avoiding Zod parsing for large DB arrays]+ //+ // Zod can be used to validate that the value we read from the DB is indeed+ // the same as the type we expect, but for potentially very large arrays,+ // this has an overhead that is perhaps not justified when dealing with DB+ // entries we ourselves wrote.+ //+ // For example (as a non-rigorous benchmark) parsing 200k files took one+ // second. Zod is fast, just that these arrays are big and might be accessed+ // frequently, and the schemas are, while not too complicated, non-trivial.+ //+ // As an optimization, we skip the runtime check here and cast. This might+ // not be the most optimal choice in the future, so (a) use it sparingly,+ // and (b) mark all such cases with the title of this note.+ //+ // Note that the cast is happening inside the local forage code since we're+ // passing a type parameter.+ let files = (await localForage.getItem<EnteFile[]>("files")) ?? [];++ // Previously hidden files were stored separately. If that key is present,+ // also read those files, and migrate them (save the concatenation to disk+ // and delete the corresponding DB key).+ //+ // This migration was added Jun 2025, v1.7.14-beta (tag: Migration).+ const previousHiddenFiles =+ await localForage.getItem<EnteFile[]>("hidden-files");+ if (previousHiddenFiles) {+ files = files.concat(previousHiddenFiles);+ await saveCollectionFiles(files);+ await localForage.removeItem("hidden-files");+ // While we're cleaning up, also remove this unused field related to+ // hidden collections also being separately stored earlier.+ await localForage.removeItem("hidden-collection-ids");+ }++ return transformFilesIfNeeded(files);+};++/**+ * Replace the list of collection files stored in our local database.+ *+ * This is the setter corresponding to {@link savedCollectionFiles}.+ */+export const saveCollectionFiles = async (files: EnteFile[]) => {+ await localForage.setItem("files", transformFilesIfNeeded(files));+};++/**+ * Return the locally persisted "last sync time" for a collection that we have+ * pulled from remote. This can be used to perform a paginated delta pull from+ * the saved time onwards.+ *+ * > Specifically, this is the {@link updationTime} of the latest file from the+ * > {@link collection}, or the the collection itself if it is fully synced.+ *+ * Use {@link saveCollectionLastSyncTime} to update the value saved in the+ * database, and {@link removeCollectionIDLastSyncTime} to remove the saved+ * value from the database.+ */+export const savedCollectionLastSyncTime = async (collection: Collection) =>+ LocalTimestamp.parse(await localForage.getItem(`${collection.id}-time`));++/**+ * Update the locally persisted timestamp that will be returned by subsequent+ * calls to {@link savedCollectionLastSyncTime}.+ */+export const saveCollectionLastSyncTime = async (+ collection: Collection,+ time: number,+) => {+ await localForage.setItem(`${collection.id}-time`, time);+};++/**+ * Remove the locally persisted timestamp, if any, previously saved for a+ * collection with the given ID using {@link saveCollectionLastSyncTime}.+ */+export const removeCollectionIDLastSyncTime = async (collectionID: number) => {+ await localForage.removeItem(`${collectionID}-time`);+};++/**+ * Zod schema for a trash entry saved in our local database.+ */+const LocalTrashItem = z.looseObject({+ file: LocalEnteFile,+ updatedAt: z.number(),+ deleteBy: z.number(),+});++/**+ * Return all trash entries present in our local database.+ *+ * Use {@link saveTrashItems} to update the database+ */+export const savedTrashItems = async (): Promise<TrashItem[]> =>+ LocalTrashItem.array().parse(+ (await localForage.getItem("file-trash")) ?? [],+ );++/**+ * Replace the list of trash items stored in our local database.+ *+ * This is the setter corresponding to {@link savedTrashItems}.+ */+export const saveTrashItems = async (trashItems: TrashItem[]) => {+ await localForage.setItem("file-trash", trashItems);+};++/**+ * Return the updatedAt of the latest trash items we have obtained from remote.+ *+ * Use {@link saveTrashLastUpdatedAt} to update the database.+ */+export const savedTrashLastUpdatedAt = async (): Promise<number | undefined> =>+ LocalTimestamp.parse(await localForage.getItem("trash-time"));++/**+ * Update the updatedAt of the latest trash items we have obtained from remote.+ *+ * This is the setter corresponding to {@link savedTrashLastUpdatedAt}.+ */+export const saveTrashLastUpdatedAt = async (updatedAt: number) => {+ await localForage.setItem("trash-time", updatedAt);+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/reaction.ts b/web/apps/albums/vendor/ente-new/photos/services/reaction.tsnew file mode 100644index 0000000000..b39b769762--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/reaction.ts@@ -0,0 +1,107 @@+import { encryptBox } from "ente-base/crypto";+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { z } from "zod";++/**+ * Fixed length for padded reaction types.+ * All reactions are padded to this length before encryption to prevent+ * length-based analysis of the ciphertext.+ * Max emoji name is ~70 chars, so 100 provides a safe buffer.+ */+const paddedReactionLength = 100;++/**+ * Pad a reaction type to a fixed length using null bytes.+ */+const padReaction = (reactionType: string): string =>+ reactionType.padEnd(paddedReactionLength, "\0");++/**+ * Add a reaction to a file in a collection.+ *+ * @param collectionID The ID of the collection containing the file.+ * @param fileID The ID of the file to react to.+ * @param reactionType The type of reaction (e.g., "green_heart").+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns The ID of the created reaction.+ */+export const addReaction = async (+ collectionID: number,+ fileID: number,+ reactionType: string,+ collectionKey: string,+): Promise<string> => {+ const { encryptedData: cipher, nonce } = await encryptBox(+ new TextEncoder().encode(padReaction(reactionType)),+ collectionKey,+ );++ const res = await fetch(await apiURL("/reactions"), {+ method: "PUT",+ headers: {+ ...(await authenticatedRequestHeaders()),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ collectionID, fileID, cipher, nonce }),+ });+ ensureOk(res);+ const { id } = UpsertReactionResponse.parse(await res.json());+ return id;+};++/**+ * Add a reaction to a comment in a collection.+ *+ * @param collectionID The ID of the collection containing the comment.+ * @param commentID The ID of the comment to react to.+ * @param reactionType The type of reaction (e.g., "green_heart").+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @param fileID Optional file ID, required for file-scoped comments.+ * @returns The ID of the created reaction.+ */+export const addCommentReaction = async (+ collectionID: number,+ commentID: string,+ reactionType: string,+ collectionKey: string,+ fileID?: number,+): Promise<string> => {+ const { encryptedData: cipher, nonce } = await encryptBox(+ new TextEncoder().encode(padReaction(reactionType)),+ collectionKey,+ );++ const res = await fetch(await apiURL("/reactions"), {+ method: "PUT",+ headers: {+ ...(await authenticatedRequestHeaders()),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ collectionID,+ commentID,+ fileID,+ cipher,+ nonce,+ }),+ });+ ensureOk(res);+ const { id } = UpsertReactionResponse.parse(await res.json());+ return id;+};++const UpsertReactionResponse = z.object({ id: z.string() });++/**+ * Delete a reaction by its ID.+ *+ * @param reactionID The ID of the reaction to delete.+ */+export const deleteReaction = async (reactionID: string): Promise<void> => {+ const res = await fetch(await apiURL(`/reactions/${reactionID}`), {+ method: "DELETE",+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/remote-store.ts b/web/apps/albums/vendor/ente-new/photos/services/remote-store.tsnew file mode 100644index 0000000000..8bbe80c08e--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/remote-store.ts@@ -0,0 +1,75 @@+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { z } from "zod";++/**+ * [Note: Remote store]+ *+ * The remote store provides a unified interface for persisting varied "remote+ * flags":+ *+ * - User preferences like "mapEnabled"+ *+ * - Feature flags like "isInternalUser"+ *+ * There are two APIs to get the current state from remote:+ *+ * 1. GET /remote-store/feature-flags fetches the combined state (nb: even+ * though the name of the endpoint has the word feature-flags, it also+ * includes user preferences).+ *+ * 2. GET /remote-store fetches individual values.+ *+ * Usually 1 is what we use, since it gets us everything in a single go, and+ * which we can also easily cache in local storage by saving the entire response+ * JSON blob.+ *+ * There is a single API (/remote-store/update) to update the state on remote.+ */+export const fetchFeatureFlags = async () => {+ const res = await fetch(await apiURL("/remote-store/feature-flags"), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return res;+};++/**+ * Fetch the value for the given {@link key} from remote store.+ *+ * If the key is not present in the remote store, return {@link defaultValue}.+ */+export const getRemoteValue = async (key: string, defaultValue: string) => {+ const res = await fetch(+ await apiURL("/remote-store", { key, defaultValue }),+ { headers: await authenticatedRequestHeaders() },+ );+ ensureOk(res);+ return GetRemoteStoreResponse.parse(await res.json())?.value;+};++const GetRemoteStoreResponse = z.object({ value: z.string() }).nullable();++/**+ * Convenience wrapper over {@link getRemoteValue} that returns booleans.+ */+export const getRemoteFlag = async (key: string) =>+ (await getRemoteValue(key, "false")) == "true";++/**+ * Update or insert {@link value} for the given {@link key} into remote store.+ */+export const updateRemoteValue = async (key: string, value: string) =>+ ensureOk(+ await fetch(await apiURL("/remote-store/update"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ key, value }),+ }),+ );++/**+ * Convenience wrapper over {@link updateRemoteValue} that sets booleans.+ */+export const updateRemoteFlag = (key: string, value: boolean) =>+ updateRemoteValue(key, JSON.stringify(value));diff --git a/web/apps/albums/vendor/ente-new/photos/services/search/index.ts b/web/apps/albums/vendor/ente-new/photos/services/search/index.tsnew file mode 100644index 0000000000..da95a32bc1--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/search/index.ts@@ -0,0 +1,202 @@+import log from "ente-base/log";+import { ensureMasterKeyFromSession } from "ente-base/session";+import { ComlinkWorker } from "ente-base/worker/comlink-worker";+import { uniqueFilesByID } from "ente-gallery/utils/file";+import type { Collection } from "ente-media/collection";+import type { EnteFile } from "ente-media/file";+import { FileType } from "ente-media/file-type";+import i18n, { t } from "i18next";+import { clipMatches, isMLEnabled, isMLSupported } from "../ml";+import type { NamedPerson } from "../ml/people";+import type {+ LabelledFileType,+ LabelledSearchDateComponents,+ LocalizedSearchData,+ SearchSuggestion,+} from "./types";+import type { SearchWorker } from "./worker";++/**+ * Cached instance of the {@link ComlinkWorker} that wraps our web worker.+ */+let _comlinkWorker: ComlinkWorker<typeof SearchWorker> | undefined;++/**+ * Lazily created, cached, instance of {@link SearchWorker}.+ */+const worker = () => (_comlinkWorker ??= createComlinkWorker()).remote;++/**+ * Create a new instance of a comlink worker that wraps a {@link SearchWorker}+ * web worker.+ */+const createComlinkWorker = () =>+ new ComlinkWorker<typeof SearchWorker>(+ "search",+ new Worker(new URL("worker.ts", import.meta.url)),+ );++/**+ * Perform any logout specific cleanup for the search subsystem.+ */+export const logoutSearch = () => {+ if (_comlinkWorker) {+ _comlinkWorker.terminate();+ _comlinkWorker = undefined;+ }+ _localizedSearchData = undefined;+};++/**+ * Fetch any data that would be needed if the user were to search.+ */+export const searchDataSync = () =>+ worker().then((w) => ensureMasterKeyFromSession().then((k) => w.sync(k)));++/**+ * Update the collections and files over which we should search.+ */+export const updateSearchCollectionsAndFiles = (+ collections: Collection[],+ collectionFiles: EnteFile[],+ hiddenCollectionIDs: Set<number>,+ hiddenFileIDs: Set<number>,+) => {+ const normalCollections = collections.filter(+ (c) => !hiddenCollectionIDs.has(c.id),+ );+ const normalCollectionFiles = collectionFiles.filter(+ (f) => !hiddenFileIDs.has(f.id),+ );+ void worker().then((w) =>+ w.setCollectionsAndFiles({+ collections: normalCollections,+ files: uniqueFilesByID(normalCollectionFiles),+ collectionFiles: normalCollectionFiles,+ }),+ );+};++/**+ * Set the (named) people that we should search across.+ */+export const setSearchPeople = (people: NamedPerson[]) =>+ void worker().then((w) => w.setPeople(people));++/**+ * Convert a search string into (annotated) suggestions that can be shown in the+ * search results dropdown.+ *+ * @param searchString The string we want to search for.+ */+export const searchOptionsForString = async (searchString: string) => {+ const t = Date.now();+ const suggestions = await suggestionsForString(searchString);+ const options = await suggestionsToOptions(suggestions);+ log.debug(() => [+ "search",+ { searchString, options, duration: `${Date.now() - t} ms` },+ ]);+ return options;+};++const suggestionsForString = async (searchString: string) => {+ // Normalize it by trimming whitespace and converting to lowercase.+ const s = searchString.trim().toLowerCase();+ if (s.length == 0) return [];++ // The CLIP matching code already runs in the ML worker, so let that run+ // separately, in parallel with the rest of the search query construction in+ // the search worker, then combine the two.+ const [clip, [restPre, restPost]] = await Promise.all([+ clipSuggestion(s, searchString).then((s) => s ?? []),+ worker().then((w) =>+ w.suggestionsForString(s, searchString, localizedSearchData()),+ ),+ ]);+ return [restPre, clip, restPost].flat();+};++const clipSuggestion = async (+ s: string,+ searchString: string,+): Promise<SearchSuggestion | undefined> => {+ if (!isMLSupported) return undefined;+ if (!isMLEnabled()) return undefined;++ const matches = await clipMatches(s);+ if (!matches) return undefined;+ return { type: "clip", clipScoreForFileID: matches, label: searchString };+};++const suggestionsToOptions = (suggestions: SearchSuggestion[]) =>+ filterSearchableFilesMulti(suggestions).then((res) =>+ res.map(([files, suggestion]) => ({+ suggestion,+ fileCount: files.length,+ previewFiles: files.slice(0, 3),+ })),+ );++/**+ * Return the list of {@link EnteFile}s (from amongst the previously set+ * {@link SearchCollectionsAndFiles}) that match the given search {@link suggestion}.+ */+export const filterSearchableFiles = async (suggestion: SearchSuggestion) =>+ worker().then((w) => w.filterSearchableFiles(suggestion));++/**+ * A batched variant of {@link filterSearchableFiles}.+ *+ * This has drastically (10x) better performance when filtering files for a+ * large number of suggestions (e.g. single letter searches that lead to a large+ * number of city prefix matches), likely because of reduced worker IPC.+ */+const filterSearchableFilesMulti = async (suggestions: SearchSuggestion[]) =>+ worker().then((w) => w.filterSearchableFilesMulti(suggestions));++/**+ * Cached value of {@link localizedSearchData}.+ */+let _localizedSearchData: LocalizedSearchData | undefined;++/*+ * For searching, the web worker needs a bunch of otherwise static data that has+ * names and labels formed by localized strings.+ *+ * Since it would be tricky to get the t() function to work in a web worker, we+ * instead pass this from the main thread (lazily initialized and cached).+ *+ * Note that these need to be evaluated at runtime, and cannot be static+ * constants since t() depends on the user's locale.+ *+ * We currently clear the cached data on logout, but this is not necessary. The+ * only point we necessarily need to clear this data is if the user changes their+ * preferred locale, but currently we reload the page in such cases so any in+ * memory state would be reset that way.+ */+const localizedSearchData = () =>+ (_localizedSearchData ??= {+ locale: i18n.language,+ holidays: holidays(),+ labelledFileTypes: labelledFileTypes(),+ });++/**+ * A list of holidays - their yearly dates and localized names.+ */+const holidays = (): LabelledSearchDateComponents[] => [+ { components: { month: 12, day: 25 }, label: t("christmas") },+ { components: { month: 12, day: 24 }, label: t("christmas_eve") },+ { components: { month: 1, day: 1 }, label: t("new_year") },+ { components: { month: 12, day: 31 }, label: t("new_year_eve") },+];++/**+ * A list of file types with their localized names.+ */+const labelledFileTypes = (): LabelledFileType[] => [+ { fileType: FileType.image, label: t("image") },+ { fileType: FileType.video, label: t("video") },+ { fileType: FileType.livePhoto, label: t("live_photo") },+];diff --git a/web/apps/albums/vendor/ente-new/photos/services/search/types.ts b/web/apps/albums/vendor/ente-new/photos/services/search/types.tsnew file mode 100644index 0000000000..9a6eb25036--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/search/types.ts@@ -0,0 +1,187 @@+/**+ * @file types shared between the main thread interface to search (`index.ts`)+ * and the search worker that does the actual searching (`worker.ts`).+ */++import type { Location } from "ente-base/types";+import type { Collection } from "ente-media/collection";+import type { EnteFile } from "ente-media/file";+import { FileType } from "ente-media/file-type";+import type { Person } from "ente-new/photos/services/ml/people";+import type { LocationTag } from "../user-entity";++/**+ * Represents the unique identifiers for various sidebar actions in the application.+ *+ * These IDs are organized into categories:+ * - `shortcuts.*`: Quick access actions like uncategorized items, archive, hidden items, and trash+ * - `utility.*`: General utility actions such as account management, folder watching, deduplication, preferences, help, export, and logout+ * - `account.*`: Account-specific settings including recovery key, two-factor authentication, passkeys, password/email management, and account deletion+ * - `preferences.*`: User preference options like language, theme, custom domains, map settings, advanced options, ML search, and streamable videos+ * - `help.*`: Help-related actions including help center, blog, feature requests, support, log viewing, and test upload+ *+ * @remarks+ * This type is used to ensure type safety when referencing sidebar actions throughout the application.+ */+export type SidebarActionID =+ | "shortcuts.uncategorized"+ | "shortcuts.archive"+ | "shortcuts.hidden"+ | "shortcuts.trash"+ | "utility.account"+ | "utility.watchFolders"+ | "utility.freeUpSpace"+ | "utility.preferences"+ | "utility.help"+ | "utility.export"+ | "utility.logout"+ | "freeUpSpace.deduplicate"+ | "freeUpSpace.largeFiles"+ | "account.subscription"+ | "account.recoveryKey"+ | "account.twoFactor"+ | "account.twoFactor.reconfigure"+ | "account.passkeys"+ | "account.changePassword"+ | "account.changeEmail"+ | "account.deleteAccount"+ | "account.sessions"+ | "preferences.language"+ | "preferences.theme"+ | "preferences.customDomains"+ | "preferences.map"+ | "preferences.advanced"+ | "preferences.fasterUpload"+ | "preferences.openOnStartup"+ | "preferences.mlSearch"+ | "preferences.streamableVideos"+ | "help.helpCenter"+ | "help.blog"+ | "help.requestFeature"+ | "help.support"+ | "help.viewLogs"+ | "help.testUpload";++/**+ * A search suggestion.+ *+ * These (wrapped up in {@link SearchOption}s) are shown in the search results+ * dropdown, and can also be used to filter the list of files that are shown.+ */+export type SearchSuggestion = { label: string } & (+ | { type: "collection"; collectionID: number }+ | { type: "fileType"; fileType: FileType }+ | { type: "fileName"; fileIDs: number[] }+ | { type: "fileCaption"; fileIDs: number[] }+ | { type: "cameraMake"; fileIDs: number[] }+ | { type: "cameraModel"; fileIDs: number[] }+ | { type: "date"; dateComponents: SearchDateComponents }+ | { type: "location"; locationTag: LocationTag }+ | { type: "city"; city: City }+ | { type: "clip"; clipScoreForFileID: Map<number, number> }+ | { type: "person"; person: Person }+ | { type: "sidebarAction"; actionID: SidebarActionID; path: string[] }+);++/**+ * An option shown in the the search bar's select dropdown.+ *+ * The {@link SearchOption} wraps a {@link SearchSuggestion} with some metadata+ * used when showing a corresponding entry in the dropdown.+ *+ * If the user selects the option, then we will re-run the search using the+ * {@link suggestion} to filter the list of files shown to the user.+ */+export interface SearchOption {+ suggestion: SearchSuggestion;+ /**+ * The count of files that matched the search option when it was initially+ * computed.+ */+ fileCount: number;+ previewFiles: EnteFile[];+}++/**+ * The collections and files over which we should search.+ */+export interface SearchCollectionsAndFiles {+ collections: Collection[];+ /**+ * Unique files (by ID).+ *+ * @see {@link uniqueFilesByID}.+ */+ files: EnteFile[];+ /**+ * One entry per collection/file pair.+ *+ * Whenever the same file (ID) is in multiple collections, the+ * {@link collectionFiles} will have multiple entries with the same file ID,+ * one per collection in which that file (ID) occurs.+ */+ collectionFiles: EnteFile[];+}++export interface LabelledSearchDateComponents {+ components: SearchDateComponents;+ label: string;+}++export interface LabelledFileType {+ fileType: FileType;+ label: string;+}++/**+ * Various bits of static but locale specific data that the search worker needs+ * during searching.+ */+export interface LocalizedSearchData {+ locale: string;+ holidays: LabelledSearchDateComponents[];+ labelledFileTypes: LabelledFileType[];+}++/**+ * A parsed version of a potential natural language date time string.+ *+ * All attributes which were parsed will be set. The type doesn't enforce this,+ * but it is guaranteed that at least one attribute will be present.+ */+export interface SearchDateComponents {+ /**+ * The year, if the search string specified one. e.g. `2024`.+ */+ year?: number;+ /**+ * The month (1 to 12, with December being 12), if the search string+ * specified one.+ */+ month?: number;+ /**+ * The day of the month (1 to 31), if the search string specified one.+ */+ day?: number;+ /**+ * The day of the week (0 to 6, with Sunday being 0), if the search string+ * specified one.+ */+ weekday?: number;+ /**+ * The hour of the day (0 to 23, with 0 as midnight), if the search string+ * specified one.+ */+ hour?: number;+}++/**+ * A city as identified by a static dataset.+ *+ * Each city is represented by its latitude and longitude. The dataset does not+ * have information about the city's estimated radius.+ */+export type City = Location & {+ /** Name of the city. */+ name: string;+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/search/worker.ts b/web/apps/albums/vendor/ente-new/photos/services/search/worker.tsnew file mode 100644index 0000000000..831cdc9df3--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/search/worker.ts@@ -0,0 +1,579 @@+import type { Component } from "chrono-node";+import * as chrono from "chrono-node";+import { expose } from "comlink";+import { HTTPError } from "ente-base/http";+import { logUnhandledErrorsAndRejectionsInWorker } from "ente-base/log-web";+import type { Location } from "ente-base/types";+import type { Collection } from "ente-media/collection";+import type { EnteFile } from "ente-media/file";+import {+ fileCameraMake,+ fileCameraModel,+ fileCreationPhotoDate,+ fileFileName,+ fileLocation,+} from "ente-media/file-metadata";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";+import type { NamedPerson } from "../ml/people";+import {+ pullUserEntities,+ savedLocationTags,+ type LocationTag,+} from "../user-entity";+import type {+ City,+ LabelledFileType,+ LabelledSearchDateComponents,+ LocalizedSearchData,+ SearchCollectionsAndFiles,+ SearchDateComponents,+ SearchSuggestion,+} from "./types";++/**+ * A web worker that runs the search asynchronously so that the main thread+ * remains responsive.+ */+export class SearchWorker {+ private locationTags: LocationTag[] = [];+ private cities: City[] = [];+ private collectionsAndFiles: SearchCollectionsAndFiles = {+ collections: [],+ files: [],+ collectionFiles: [],+ };+ private people: NamedPerson[] = [];++ /**+ * Fetch any state we might need when the actual search happens.+ *+ * @param masterKey The user's master key (as a base64 string). Web workers+ * do not have access to session storage so this key needs to be passed to+ * us explicitly.+ */+ async sync(masterKey: string) {+ // Let the cities fetch complete async. And do it only once per app+ // startup (this list is static and doesn't change).+ if (this.cities.length == 0) {+ void fetchCities().then((cs) => (this.cities = cs));+ }++ return pullUserEntities("location", masterKey)+ .then(() => savedLocationTags())+ .then((ts) => (this.locationTags = ts));+ }++ /**+ * Set the collections and files that we should search across.+ */+ setCollectionsAndFiles(cf: SearchCollectionsAndFiles) {+ this.collectionsAndFiles = cf;+ }++ /**+ * Set the (named) people that we should search across.+ */+ setPeople(people: NamedPerson[]) {+ this.people = people;+ }++ /**+ * Convert a search string into a list of {@link SearchSuggestion}s.+ */+ suggestionsForString(+ s: string,+ searchString: string,+ localizedSearchData: LocalizedSearchData,+ ) {+ return suggestionsForString(+ s,+ // Case insensitive word prefix match. Note that \b doesn't work+ // with unicode characters, so we use instead a set of common+ // punctuation (and spaces) to discern the word boundary.+ new RegExp("(^|[\\s.,!?\"'-_])" + s, "i"),+ searchString,+ this.collectionsAndFiles,+ this.people,+ localizedSearchData,+ this.locationTags,+ this.cities,+ );+ }++ /**+ * Return {@link EnteFile}s that satisfy the given {@link suggestion}.+ */+ filterSearchableFiles(suggestion: SearchSuggestion) {+ return filterSearchableFiles(this.collectionsAndFiles, suggestion);+ }++ /**+ * Batched variant of {@link filterSearchableFiles}.+ */+ filterSearchableFilesMulti(suggestions: SearchSuggestion[]) {+ const cf = this.collectionsAndFiles;+ return suggestions+ .map((sg) => [filterSearchableFiles(cf, sg), sg] as const)+ .filter(([files]) => files.length);+ }+}++expose(SearchWorker);++logUnhandledErrorsAndRejectionsInWorker();++/**+ * @param s The normalized form of {@link searchString}.+ * @param searchString The original search string.+ */+const suggestionsForString = (+ s: string,+ re: RegExp,+ searchString: string,+ { collections, files }: SearchCollectionsAndFiles,+ people: NamedPerson[],+ { locale, holidays, labelledFileTypes }: LocalizedSearchData,+ locationTags: LocationTag[],+ cities: City[],+): [SearchSuggestion[], SearchSuggestion[]] => [+ [peopleSuggestions(re, people)].flat(),+ // . <-- clip suggestions will be inserted here by our caller.+ [+ fileTypeSuggestions(re, labelledFileTypes),+ dateSuggestions(s, re, locale, holidays),+ locationSuggestions(re, locationTags, cities),+ collectionSuggestions(re, collections),+ fileNameSuggestion(s, re, searchString, files),+ fileCaptionSuggestion(re, searchString, files),+ cameraMakeSuggestions(re, files),+ cameraModelSuggestions(re, files),+ ].flat(),+];++const collectionSuggestions = (+ re: RegExp,+ collections: Collection[],+): SearchSuggestion[] =>+ collections+ .filter((c) => re.test(c.name))+ .map(({ id, name }) => ({+ type: "collection",+ collectionID: id,+ label: name,+ }));++const fileTypeSuggestions = (+ re: RegExp,+ labelledFileTypes: LabelledFileType[],+): SearchSuggestion[] =>+ labelledFileTypes+ .filter(({ label }) => re.test(label))+ .map(({ fileType, label }) => ({ type: "fileType", fileType, label }));++const fileNameSuggestion = (+ s: string,+ re: RegExp,+ searchString: string,+ files: EnteFile[],+): SearchSuggestion[] => {+ // Convert the search string to a number. This allows searching a file by+ // its exact (integral) ID.+ const sn = Number(s) || undefined;++ const fileIDs = files+ .filter((f) => f.id === sn || re.test(fileFileName(f)))+ .map((f) => f.id);++ return fileIDs.length+ ? [{ type: "fileName", fileIDs, label: searchString }]+ : [];+};++const fileCaptionSuggestion = (+ re: RegExp,+ searchString: string,+ files: EnteFile[],+): SearchSuggestion[] => {+ const fileIDs = files+ .filter((file) => {+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition+ const caption = file.pubMagicMetadata?.data?.caption;+ return caption && re.test(caption);+ })+ .map((f) => f.id);++ return fileIDs.length+ ? [{ type: "fileCaption", fileIDs, label: searchString }]+ : [];+};++const cameraMakeSuggestions = (+ re: RegExp,+ files: EnteFile[],+): SearchSuggestion[] => {+ const matches = new Map<string, { label: string; fileIDs: number[] }>();+ for (const file of files) {+ const label = fileCameraMake(file);+ if (!label || !re.test(label)) continue;+ const key = label.toLowerCase();+ const existing = matches.get(key);+ if (existing) {+ existing.fileIDs.push(file.id);+ } else {+ matches.set(key, { label, fileIDs: [file.id] });+ }+ }++ return Array.from(matches.values()).map(({ label, fileIDs }) => ({+ type: "cameraMake" as const,+ label,+ fileIDs,+ }));+};++const cameraModelSuggestions = (+ re: RegExp,+ files: EnteFile[],+): SearchSuggestion[] => {+ const matches = new Map<string, { label: string; fileIDs: number[] }>();+ for (const file of files) {+ const label = fileCameraModel(file);+ if (!label || !re.test(label)) continue;+ const key = label.toLowerCase();+ const existing = matches.get(key);+ if (existing) {+ existing.fileIDs.push(file.id);+ } else {+ matches.set(key, { label, fileIDs: [file.id] });+ }+ }++ return Array.from(matches.values()).map(({ label, fileIDs }) => ({+ type: "cameraModel" as const,+ label,+ fileIDs,+ }));+};++const peopleSuggestions = (+ re: RegExp,+ people: NamedPerson[],+): SearchSuggestion[] =>+ people+ .filter(({ name }) => re.test(name))+ .map((person) => ({ type: "person", person, label: person.name }));++const dateSuggestions = (+ s: string,+ re: RegExp,+ locale: string,+ holidays: LabelledSearchDateComponents[],+): SearchSuggestion[] =>+ parseDateComponents(s, re, locale, holidays).map(+ ({ components, label }) => ({+ type: "date",+ dateComponents: components,+ label,+ }),+ );++/**+ * Try to parse an arbitrary search string into sets of date components.+ *+ * e.g. "December 2022" will be parsed into a+ *+ * [(year 2022, month 12, day undefined)]+ *+ * while "22 December 2022" will be parsed into+ *+ * [(year 2022, month 12, day 22)]+ *+ * In addition, also return a formatted representation of the "best" guess at+ * the date that was intended by the search string.+ */+const parseDateComponents = (+ s: string,+ re: RegExp,+ locale: string,+ holidays: LabelledSearchDateComponents[],+): LabelledSearchDateComponents[] =>+ [+ parseChrono(s, locale),+ parseYearComponents(s),+ holidays.filter((h) => re.test(h.label)),+ ].flat();++const parseChrono = (+ s: string,+ locale: string,+): LabelledSearchDateComponents[] => {+ // Use the appropriate chrono parser based on locale+ // For US locales, use the default parser (MM/DD/YYYY)+ // For other locales, use the GB parser (DD/MM/YYYY)+ const isUSLocale =+ locale.toLowerCase().includes("en-us") || locale.toLowerCase() === "en";++ // Select the appropriate chrono instance based on locale+ let chronoInstance;+ if (isUSLocale) {+ // For US locale, use the default chrono parser (MM/DD/YYYY)+ chronoInstance = chrono;+ } else {+ // For non-US locales, use GB parser (DD/MM/YYYY) and add DD.MM.YYYY support+ chronoInstance = new chrono.Chrono(chrono.en.GB);++ // Add parser for DD.MM.YYYY format (common in Germany, Switzerland, etc.)+ // This format uses dots as separators instead of slashes+ chronoInstance.parsers.push({+ pattern: () => /\b(\d{1,2})\.(\d{1,2})\.(\d{2,4})\b/,+ extract: (_context, match) => {+ if (!match[1] || !match[2] || !match[3]) return null;++ const day = parseInt(match[1]);+ const month = parseInt(match[2]);+ let year = parseInt(match[3]);++ // Handle 2-digit years+ if (year < 100) {+ year = year > 50 ? 1900 + year : 2000 + year;+ }++ // Validate the date+ if (day < 1 || day > 31 || month < 1 || month > 12) {+ return null;+ }++ return { day, month, year };+ },+ });+ }++ return chronoInstance+ .parse(s)+ .map((result) => {+ const p = result.start;+ const component = (s: Component) =>+ p.isCertain(s) ? nullToUndefined(p.get(s)) : undefined;++ const year = component("year");+ const month = component("month");+ const day = component("day");+ const weekday = component("weekday");+ const hour = component("hour");++ if (!year && !month && !day && !weekday && !hour) return undefined;+ const components = { year, month, day, weekday, hour };++ const format: Intl.DateTimeFormatOptions = {};+ if (year) format.year = "numeric";+ if (month) format.month = "long";+ if (day) format.day = "numeric";+ if (weekday) format.weekday = "long";+ if (hour) {+ format.hour = "numeric";+ format.dayPeriod = "short";+ }++ const formatter = new Intl.DateTimeFormat(locale, format);+ const label = formatter.format(p.date());+ return { components, label };+ })+ .filter((x) => x !== undefined);+};++/** chrono does not parse years like "2024", so do it manually. */+const parseYearComponents = (s: string): LabelledSearchDateComponents[] => {+ // s is already trimmed.+ if (s.length == 4) {+ const year = parseInt(s);+ if (year && year <= 9999) {+ const components = { year };+ return [{ components, label: s }];+ }+ }+ return [];+};++/**+ * Zod schema describing world_cities.json.+ *+ * The entries also have a country field which we don't currently use.+ */+const RemoteWorldCities = z.object({+ data: z.array(+ z.object({ city: z.string(), lat: z.number(), lng: z.number() }),+ ),+});++const fetchCities = async () => {+ const res = await fetch("https://assets.ente.io/world_cities.json");+ if (!res.ok) throw new HTTPError(res);+ return RemoteWorldCities.parse(await res.json()).data.map(+ ({ city, lat, lng }) => ({ name: city, latitude: lat, longitude: lng }),+ );+};++const locationSuggestions = (+ re: RegExp,+ locationTags: LocationTag[],+ cities: City[],+): SearchSuggestion[] => {+ const matchingLocationTags = locationTags.filter((t) => re.test(t.name));++ const matchingLocationTagLNames = new Set(+ matchingLocationTags.map((t) => t.name.toLowerCase()),+ );++ const matchingCities = cities+ .filter((c) => re.test(c.name))+ .filter((c) => !matchingLocationTagLNames.has(c.name.toLowerCase()));++ return [+ matchingLocationTags.map(+ (locationTag): SearchSuggestion => ({+ type: "location",+ locationTag,+ label: locationTag.name,+ }),+ ),+ matchingCities.map(+ (city): SearchSuggestion => ({+ type: "city",+ city,+ label: city.name,+ }),+ ),+ ].flat();+};++const filterSearchableFiles = (+ { files, collectionFiles }: SearchCollectionsAndFiles,+ suggestion: SearchSuggestion,+) => {+ if (suggestion.type == "sidebarAction") return [];++ return sortMatchesIfNeeded(+ (suggestion.type == "collection" ? collectionFiles : files).filter(+ (f) => isMatchingFile(f, suggestion),+ ),+ suggestion,+ );+};++/**+ * Return true if file satisfies the given {@link query}.+ */+const isMatchingFile = (file: EnteFile, suggestion: SearchSuggestion) => {+ switch (suggestion.type) {+ case "collection":+ return suggestion.collectionID === file.collectionID;++ case "fileType":+ return suggestion.fileType == file.metadata.fileType;++ case "fileName":+ return suggestion.fileIDs.includes(file.id);++ case "fileCaption":+ case "cameraMake":+ case "cameraModel":+ return suggestion.fileIDs.includes(file.id);++ case "date":+ return isDateComponentsMatch(+ suggestion.dateComponents,+ fileCreationPhotoDate(file),+ );++ case "location": {+ const location = fileLocation(file);+ if (!location) return false;++ return isInsideLocationTag(location, suggestion.locationTag);+ }++ case "city": {+ const location = fileLocation(file);+ if (!location) return false;++ return isInsideCity(location, suggestion.city);+ }++ case "clip":+ return suggestion.clipScoreForFileID.has(file.id);++ case "person":+ return suggestion.person.fileIDs.includes(file.id);++ case "sidebarAction":+ return false;+ }+};++const isDateComponentsMatch = (+ { year, month, day, weekday, hour }: SearchDateComponents,+ date: Date,+) => {+ // Components are guaranteed to have at least one attribute present, so+ // start by assuming true.+ let match = true;++ if (year) match = date.getFullYear() == year;+ // JS getMonth is 0-indexed.+ if (match && month) match = date.getMonth() + 1 == month;+ if (match && day) match = date.getDate() == day;+ if (match && weekday) match = date.getDay() == weekday;+ if (match && hour) match = date.getHours() == hour;++ return match;+};++const defaultCityRadius = 10;+const kmsPerDegree = 111.16;++const isInsideLocationTag = (location: Location, locationTag: LocationTag) =>+ isWithinRadius(location, locationTag.centerPoint, locationTag.radius);++const isInsideCity = (location: Location, city: City) =>+ isWithinRadius(location, city, defaultCityRadius);++const isWithinRadius = (+ location: Location,+ center: Location,+ radius: number,+) => {+ const a = (radius * radiusScaleFactor(center.latitude)) / kmsPerDegree;+ const b = radius / kmsPerDegree;+ const x = center.latitude - location.latitude;+ const y = center.longitude - location.longitude;+ return (x * x) / (a * a) + (y * y) / (b * b) <= 1;+};++/**+ * A latitude specific scaling factor to apply to the radius of a location+ * search.+ *+ * The area bounded by the location tag becomes more elliptical with increase in+ * the magnitude of the latitude on the cartesian plane. When latitude is 0+ * degrees, the ellipse is a circle with a = b = r. When latitude increases, the+ * major axis (a) has to be scaled by the secant of the latitude.+ */+const radiusScaleFactor = (lat: number) => 1 / Math.cos(lat * (Math.PI / 180));++/**+ * Sort the files if necessary.+ *+ * Currently, only the CLIP results are sorted (by their score), in the other+ * cases the files are displayed chronologically (when displaying them in search+ * results) or arbitrarily (when showing them in the search option preview).+ */+const sortMatchesIfNeeded = (+ files: EnteFile[],+ suggestion: SearchSuggestion,+) => {+ if (suggestion.type != "clip") return files;+ // Sort CLIP matches by their corresponding scores.+ const score = ({ id }: EnteFile) => suggestion.clipScoreForFileID.get(id)!;+ return files.sort((a, b) => score(b) - score(a));+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/settings.ts b/web/apps/albums/vendor/ente-new/photos/services/settings.tsnew file mode 100644index 0000000000..1601cac11d--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/settings.ts@@ -0,0 +1,313 @@+/**+ * @file Storage (in-memory, local, remote) and update of various settings.+ */++import { savedPartialLocalUser } from "ente-accounts/services/accounts-db";+import { isDevBuild } from "ente-base/env";+import log from "ente-base/log";+import {+ updateChecksumProtectedUploadsEnabled,+ updateShouldDisableCFUploadProxy,+} from "ente-gallery/services/upload";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";+import {+ fetchFeatureFlags,+ updateRemoteFlag,+ updateRemoteValue,+} from "./remote-store";++/**+ * In-memory flags that tracks various settings.+ *+ * Some of these are local only, some of these are synced with remote.+ *+ * [Note: Remote flag lifecycle]+ *+ * At a high level, this is how the app manages remote flags:+ *+ * 1. On app start, the initial are read from local storage in+ * {@link initSettings}.+ *+ * 2. During the remote pull, remote flags are fetched and saved in local+ * storage, and the in-memory state updated to reflect the latest values+ * ({@link pullSettings}).+ *+ * 3. Updating a value also cause an unconditional fetch and update+ * ({@link pullSettings}).+ *+ * 4. The individual getter functions for the flags (e.g.+ * {@link isInternalUser}) return the in-memory values, and so are suitable+ * for frequent use during UI rendering.+ *+ * 5. Everything gets reset to the default state on {@link logoutSettings}.+ */+export interface Settings {+ /**+ * `true` if the current user is an internal user.+ */+ isInternalUser: boolean;++ /**+ * `true` if maps are enabled.+ */+ mapEnabled: boolean;++ /**+ * `true` if the user has saved a preference to disable workers for uploads.+ *+ * Unlike {@link shouldDisableCFUploadProxy}, whose value reflects other+ * factors that are taken into account to determine the effective value of+ * this setting, this function returns only the saved user preference.+ */+ cfUploadProxyDisabled: boolean;++ /**+ * The URL we should ask the user to open should they wish to pair with the+ * the cast app by manually entering a pairing code.+ *+ * Changing this only ever makes sense for self-hosters, who might want to+ * point to their own self hosted cast app (See `apps.cast` in `local.yaml`+ * in the museum code).+ *+ * Default: "https://cast.ente.io"+ */+ castURL: string;++ /**+ * The URL for the embed app used for embedded sharing.+ *+ * Changing this only ever makes sense for self-hosters, who might want to+ * point to their own self hosted embed app (See `apps.embed-albums` in+ * `local.yaml` in the museum code).+ *+ * Default: "https://embed.ente.io"+ */+ embedURL: string;++ /**+ * Set to the domain (host, e.g. "photos.example.org") that the user wishes+ * to use for sharing their public albums.+ *+ * An empty string is treated as `undefined`.+ */+ customDomain?: string;++ /**+ * The URL we should ask the user to CNAME their {@link customDomain} to+ * for wiring up their domain to the public albums app.+ *+ * See also `apps.custom-domain.cname` in `server/local.yaml`.+ *+ * Default: "my.ente.io"+ */+ customDomainCNAME: string;+}++const createDefaultSettings = (): Settings => ({+ isInternalUser: false,+ mapEnabled: false,+ cfUploadProxyDisabled: false,+ castURL: "https://cast.ente.io",+ embedURL: "https://embed.ente.io",+ customDomainCNAME: "my.ente.io",+});++/**+ * Internal in-memory state shared by the functions in this module.+ *+ * This entire object will be reset on logout.+ */+class SettingsState {+ constructor() {+ this.settingsSnapshot = createDefaultSettings();+ }++ /**+ * Subscriptions to {@link Settings} updates attached using+ * {@link settingsSubscribe}.+ */+ settingsListeners: (() => void)[] = [];++ /**+ * Snapshot of the {@link Settings} returned by the {@link settingsSnapshot}+ * function.+ */+ settingsSnapshot: Settings;+}++/** State shared by the functions in this module. See {@link SettingsState}. */+let _state = new SettingsState();++/**+ * Read in the locally persisted settings into memory, but otherwise do not+ * initiate any network requests to fetch the latest values.+ *+ * This assumes that the user is already logged in.+ */+export const initSettings = () => {+ void updateShouldDisableCFUploadProxy(savedCFProxyDisabled());+ syncSettingsSnapshotWithLocalStorage();+};++export const logoutSettings = () => {+ _state = new SettingsState();+ updateChecksumProtectedUploadsEnabled(false);+};++/**+ * Fetch remote flags from remote and save them in local storage for subsequent+ * lookup. Then use the results to update our in memory state if needed.+ */+export const pullSettings = async () => {+ const jsonString = await fetchFeatureFlags().then((res) => res.text());+ // Do a parse as a sanity check before saving the string contents.+ FeatureFlags.parse(JSON.parse(jsonString));+ saveRemoteFeatureFlagsJSONString(jsonString);+ syncSettingsSnapshotWithLocalStorage();+};++const saveRemoteFeatureFlagsJSONString = (s: string) =>+ localStorage.setItem("remoteFeatureFlags", s);++const savedRemoteFeatureFlags = () => {+ const s = localStorage.getItem("remoteFeatureFlags");+ if (!s) return undefined;+ try {+ return FeatureFlags.parse(JSON.parse(s));+ } catch (e) {+ log.warn("Ignoring unparseable saved remoteFeatureFlags", e);+ return undefined;+ }+};++const FeatureFlags = z.object({+ internalUser: z.boolean().nullish().transform(nullToUndefined),+ betaUser: z.boolean().nullish().transform(nullToUndefined),+ mapEnabled: z.boolean().nullish().transform(nullToUndefined),+ serverApiFlag: z.number().nullish().transform(nullToUndefined),+ castUrl: z.string().nullish().transform(nullToUndefined),+ embedUrl: z.string().nullish().transform(nullToUndefined),+ customDomain: z.string().nullish().transform(nullToUndefined),+ customDomainCNAME: z.string().nullish().transform(nullToUndefined),+});++type FeatureFlags = z.infer<typeof FeatureFlags>;++const syncSettingsSnapshotWithLocalStorage = () => {+ const flags = savedRemoteFeatureFlags();+ const settings = createDefaultSettings();+ settings.isInternalUser = flags?.internalUser || false;+ settings.mapEnabled = flags?.mapEnabled || false;+ settings.cfUploadProxyDisabled = savedCFProxyDisabled();+ if (flags?.castUrl) settings.castURL = flags.castUrl;+ if (flags?.embedUrl) settings.embedURL = flags.embedUrl;+ if (flags?.customDomain) settings.customDomain = flags.customDomain;+ if (flags?.customDomainCNAME)+ settings.customDomainCNAME = flags.customDomainCNAME;+ updateChecksumProtectedUploadsEnabled(true);+ setSettingsSnapshot(settings);+};++/**+ * A function that can be used to subscribe to updates to {@link Settings}.+ *+ * See: [Note: Snapshots and useSyncExternalStore].+ */+export const settingsSubscribe = (onChange: () => void): (() => void) => {+ _state.settingsListeners.push(onChange);+ return () => {+ _state.settingsListeners = _state.settingsListeners.filter(+ (l) => l != onChange,+ );+ };+};++/**+ * Return the last known, cached {@link Settings}.+ *+ * See also {@link settingsSubscribe}.+ */+export const settingsSnapshot = () => _state.settingsSnapshot;++const setSettingsSnapshot = (snapshot: Settings) => {+ _state.settingsSnapshot = snapshot;+ _state.settingsListeners.forEach((l) => l());+};++/**+ * Return `true` if this is a development build, and the current user (if any)+ * is marked as an "development" user.+ *+ * Emails that end in "@ente.io" are considered as dev users.+ */+export const isDevBuildAndUser = () => isDevBuild && isDevUserViaEmail();++const isDevUserViaEmail = () =>+ !!savedPartialLocalUser()?.email?.endsWith("@ente.io");++/**+ * Persist the user's custom domain preference both locally and on remote.+ *+ * Setting the value to a blank string is equivalent to deleting the custom+ * domain value altogether.+ */+export const updateCustomDomain = async (customDomain: string) => {+ await updateRemoteValue("customDomain", customDomain);+ return pullSettings();+};++/**+ * Persist the user's map enabled preference both locally and on remote.+ */+export const updateMapEnabled = async (isEnabled: boolean) => {+ const previousSnapshot = _state.settingsSnapshot;++ setSettingsSnapshot({ ...previousSnapshot, mapEnabled: isEnabled });++ try {+ await updateRemoteFlag("mapEnabled", isEnabled);+ await pullSettings();+ } catch (e) {+ log.error("Failed to update map setting", e);+ setSettingsSnapshot(previousSnapshot);+ throw e;+ }+};++const cfProxyDisabledKey = "cfProxyDisabled";++const saveCFProxyDisabled = (v: boolean) =>+ v+ ? localStorage.setItem(cfProxyDisabledKey, "1")+ : localStorage.removeItem(cfProxyDisabledKey);++const savedCFProxyDisabled = () => {+ const v = localStorage.getItem(cfProxyDisabledKey);+ if (!v) return false;+ if (v == "1") return true;++ // Older versions of the app used to store this flag in a different+ // format, so see if this is one of those, and if so, migrate it too.+ try {+ const value = z+ .object({ value: z.boolean() })+ .parse(JSON.parse(v)).value;+ saveCFProxyDisabled(value);+ return value;+ } catch (e) {+ log.warn(`Ignoring ${cfProxyDisabledKey} value: ${v}`, e);+ localStorage.removeItem(cfProxyDisabledKey);+ return false;+ }+};++/**+ * Save the user preference for disabling uploads via Cloudflare Workers, also+ * notifying the upload subsystem of the change.+ */+export const updateCFProxyDisabledPreference = async (value: boolean) => {+ saveCFProxyDisabled(value);+ await updateShouldDisableCFUploadProxy(value);+ syncSettingsSnapshotWithLocalStorage();+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/social.ts b/web/apps/albums/vendor/ente-new/photos/services/social.tsnew file mode 100644index 0000000000..2a61427e07--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/social.ts@@ -0,0 +1,282 @@+import { decryptBox } from "ente-base/crypto";+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { z } from "zod";+import type { Comment } from "./comment";++/**+ * Remove null byte padding from a decrypted reaction type.+ */+const unpadReaction = (paddedReaction: string): string =>+ paddedReaction.replace(/\0+$/, "");++/**+ * A decrypted reaction from the unified diff endpoint.+ */+export interface UnifiedReaction {+ id: string;+ collectionID: number;+ fileID?: number;+ commentID?: string;+ /** True if this reaction is on a reply (only in feed responses). */+ isCommentReply?: boolean;+ reactionType: string;+ userID: number;+ anonUserID?: string;+ isDeleted: boolean;+ createdAt: number;+ updatedAt: number;+}++/**+ * Result from the unified social diff endpoint.+ */+export interface UnifiedSocialDiff {+ comments: Comment[];+ reactions: UnifiedReaction[];+ hasMoreComments: boolean;+ hasMoreReactions: boolean;+}++/**+ * Get comments and reactions for a file in a single request.+ *+ * @param collectionID The ID of the collection containing the file.+ * @param fileID The ID of the file to get social data for.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Comments and reactions for the file.+ */+export const getUnifiedSocialDiff = async (+ collectionID: number,+ fileID: number,+ collectionKey: string,+): Promise<UnifiedSocialDiff> => {+ const res = await fetch(+ await apiURL("/social/diff", {+ collectionID,+ fileID,+ sinceTime: 0,+ limit: 1000,+ }),+ { headers: await authenticatedRequestHeaders() },+ );+ ensureOk(res);+ return decryptSocialDiff(collectionKey, await res.json());+};++/**+ * Get album feed - comments and reactions relevant to the current user.+ *+ * This uses a server-side filtered endpoint that only returns:+ * - Comments on files owned by the user (excluding user's own comments)+ * - Replies to user's comments+ * - Reactions on files owned by the user+ * - Reactions on user's comments+ *+ * @param collectionID The ID of the collection.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Filtered comments and reactions for the user's feed.+ */+export const getAlbumFeed = async (+ collectionID: number,+ collectionKey: string,+): Promise<UnifiedSocialDiff> => {+ const res = await fetch(+ await apiURL("/social/album-feed", {+ collectionID,+ sinceTime: 0,+ limit: 1000,+ }),+ { headers: await authenticatedRequestHeaders() },+ );+ ensureOk(res);+ return decryptSocialDiff(collectionKey, await res.json());+};++/**+ * Decrypt comments and reactions from the unified diff endpoint response.+ */+const decryptSocialDiff = async (+ collectionKey: string,+ responseJson: unknown,+): Promise<UnifiedSocialDiff> => {+ const data = UnifiedDiffResponse.parse(responseJson);++ // Decrypt comments+ const comments: Comment[] = [];+ for (const comment of data.comments) {+ if (comment.isDeleted || !comment.cipher || !comment.nonce) {+ comments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ parentCommentUserID: comment.parentCommentUserID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text: "",+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ });+ continue;+ }+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: comment.cipher, nonce: comment.nonce },+ collectionKey,+ );+ const text = new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ );+ const decryptedComment = {+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ parentCommentUserID: comment.parentCommentUserID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text,+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ };+ comments.push(decryptedComment);+ } catch {+ // Skip comments that fail to decrypt+ }+ }++ // Decrypt reactions+ const reactions: UnifiedReaction[] = [];+ for (const reaction of data.reactions) {+ if (reaction.isDeleted || !reaction.cipher || !reaction.nonce) continue;+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: reaction.cipher, nonce: reaction.nonce },+ collectionKey,+ );+ const reactionType = unpadReaction(+ new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ ),+ );+ reactions.push({+ id: reaction.id,+ collectionID: reaction.collectionID,+ fileID: reaction.fileID ?? undefined,+ commentID: reaction.commentID ?? undefined,+ isCommentReply: reaction.isCommentReply ?? undefined,+ reactionType,+ userID: reaction.userID,+ anonUserID: reaction.anonUserID ?? undefined,+ isDeleted: reaction.isDeleted,+ createdAt: reaction.createdAt,+ updatedAt: reaction.updatedAt,+ });+ } catch {+ // Skip reactions that fail to decrypt+ }+ }++ const result = {+ comments,+ reactions,+ hasMoreComments: data.hasMoreComments,+ hasMoreReactions: data.hasMoreReactions,+ };+ return result;+};++const RemoteComment = z.object({+ id: z.string(),+ collectionID: z.number(),+ fileID: z.number().nullish(),+ parentCommentID: z.string().nullish(),+ parentCommentUserID: z.number().nullish(),+ userID: z.number(),+ anonUserID: z.string().nullish(),+ cipher: z.string().nullish(),+ nonce: z.string().nullish(),+ isDeleted: z.boolean(),+ createdAt: z.number(),+ updatedAt: z.number(),+});++const RemoteReaction = z.object({+ id: z.string(),+ collectionID: z.number(),+ fileID: z.number().nullish(),+ commentID: z.string().nullish(),+ isCommentReply: z.boolean().nullish(),+ userID: z.number(),+ anonUserID: z.string().nullish(),+ cipher: z.string().nullish(),+ nonce: z.string().nullish(),+ isDeleted: z.boolean(),+ createdAt: z.number(),+ updatedAt: z.number(),+});++const UnifiedDiffResponse = z.object({+ comments: z.array(RemoteComment),+ reactions: z.array(RemoteReaction),+ hasMoreComments: z.boolean(),+ hasMoreReactions: z.boolean(),+});++/**+ * Get anonymous user profiles for a collection.+ *+ * @param collectionID The ID of the collection.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Map of anonUserID to decrypted userName.+ */+export const getAnonProfiles = async (+ collectionID: number,+ collectionKey: string,+): Promise<Map<string, string>> => {+ const res = await fetch(+ await apiURL("/social/anon-profiles", { collectionID }),+ { headers: await authenticatedRequestHeaders() },+ );+ ensureOk(res);+ const { profiles } = GetAnonProfilesResponse.parse(await res.json());++ const anonUserNames = new Map<string, string>();+ for (const profile of profiles) {+ if (!profile.cipher || !profile.nonce) continue;+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: profile.cipher, nonce: profile.nonce },+ collectionKey,+ );+ const userName = new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ );+ if (userName) {+ anonUserNames.set(profile.anonUserID, userName);+ }+ } catch {+ // Skip profiles that fail to decrypt+ }+ }+ return anonUserNames;+};++const RemoteAnonProfile = z.object({+ anonUserID: z.string(),+ collectionID: z.number(),+ cipher: z.string().nullish(),+ nonce: z.string().nullish(),+ createdAt: z.number(),+ updatedAt: z.number(),+});++const GetAnonProfilesResponse = z.object({+ profiles: z+ .array(RemoteAnonProfile)+ .nullish()+ .transform((v) => v ?? []),+});diff --git a/web/apps/albums/vendor/ente-new/photos/services/trash.ts b/web/apps/albums/vendor/ente-new/photos/services/trash.tsnew file mode 100644index 0000000000..d42dde4246--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/trash.ts@@ -0,0 +1,277 @@+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";+import { apiURL } from "ente-base/origins";+import type { Collection } from "ente-media/collection";+import {+ decryptRemoteFile,+ RemoteEnteFile,+ type EnteFile,+} from "ente-media/file";+import { fileCreationTime } from "ente-media/file-metadata";+import { z } from "zod";+import { getCollectionByID } from "./collection";+import {+ savedTrashItemCollectionKeys,+ savedTrashItems,+ savedTrashLastUpdatedAt,+ saveTrashItemCollectionKeys,+ saveTrashItems,+ saveTrashLastUpdatedAt,+} from "./photos-fdb";++/**+ * A trash item indicates a file in trash.+ *+ * On being deleted by the user, files move to trash, and gain this associated+ * trash item, which we can fetch with correspoding diff APIs etc. Files will be+ * permanently deleted after 30 days of being moved to trash, but can be+ * restored or permanently deleted before that by explicit user action.+ *+ * See: [Note: File lifecycle]+ */+export interface TrashItem {+ file: EnteFile;+ /**+ * Timestamp (epoch microseconds) when the trash entry was last updated.+ */+ updatedAt: number;+ /**+ * Timestamp (epoch microseconds) when the trash item (along with its+ * associated {@link EnteFile}) will be permanently deleted.+ */+ deleteBy: number;+}++/**+ * Zod schema for a trash item that we receive from remote.+ */+const RemoteTrashItem = z.looseObject({+ file: RemoteEnteFile,+ /**+ * `true` if the file no longer in trash because it was permanently deleted.+ *+ * This field is relevant when we obtain a trash item as part of the trash+ * diff. It indicates that the file which was previously in trash is no+ * longer in the trash because it was permanently deleted.+ */+ isDeleted: z.boolean(),+ /**+ * `true` if the file no longer in trash because it was restored to some+ * collection.+ *+ * This field is relevant when we obtain a trash item as part of the trash+ * diff. It indicates that the file which was previously in trash is no+ * longer in the trash because it was restored to a collection.+ */+ isRestored: z.boolean(),+ updatedAt: z.number(),+ deleteBy: z.number(),+});++export type RemoteTrashItem = z.infer<typeof RemoteTrashItem>;++/**+ * Update our locally saved data about the files and collections in trash by+ * pulling changes from remote.+ *+ * This function uses a delta diff, pulling only changes since the timestamp+ * saved by the last pull.+ *+ * @param collections All the (non-deleted) collections that we know about+ * locally.+ *+ * @param onSetTrashedItems A callback invoked when the locally persisted trash+ * items are updated. This can be used for the UI to also update its state.+ *+ * This callback can be invoked multiple times during the pull (once for each+ * batch that gets pulled and processed). Each time, it gets passed a list of+ * all the items that are present in trash (in an arbitrary order).+ *+ * @param onPruneDeletedFileIDs A callback invoked when files that were+ * previously in trash have now been permanently deleted. This can be used by+ * other subsystems to prune data referring to files that now have been deleted+ * permanently.+ *+ * This callback can be invoked multiple times during the pull (once for each+ * batch that gets processed).+ */+export const pullTrash = async (+ collections: Collection[],+ onSetTrashedItems: ((trashItems: TrashItem[]) => void) | undefined,+ onPruneDeletedFileIDs: (deletedFileIDs: Set<number>) => Promise<void>,+): Promise<void> => {+ // Data structures:+ //+ // `collectionKeyByID` is a map from collection ID => collection key.+ //+ // It is prefilled with all the non-deleted collections available locally+ // (`collections`), and all keys of collections that trash items refererred+ // to the last time we synced (`trashItemCollectionKeys`).+ //+ // > See: [Note: Trash item collection keys]+ //+ // As we iterate over the trash items, if we find a collection whose key is+ // not present in the map, then we fetch that collection from remote, add+ // its entry to the map, and also updated the persisted value corresponding+ // to `trashItemCollectionKeys`.+ //+ // When we're done, we use `collectionKeyByID` to derive a filtered list of+ // keys that are still referred to by the current set of trash items, and+ // set this filtered list as the persisted value of+ // `trashItemCollectionKeys`.++ const collectionKeyByID = new Map(collections.map((c) => [c.id, c.key]));+ const trashItemCollectionKeys = await savedTrashItemCollectionKeys();+ for (const { id, key } of trashItemCollectionKeys) {+ collectionKeyByID.set(id, key);+ }++ // Trash items, indexed by the file ID of the file they correspond to.+ const trashItemsByID = new Map(+ (await savedTrashItems()).map((t) => [t.file.id, t]),+ );+ let sinceTime = (await savedTrashLastUpdatedAt()) ?? 0;++ while (true) {+ const { diff, hasMore } = await getTrashDiff(sinceTime);+ if (!diff.length) break;++ // IDs of files that we encounter in this batch that have been+ // permanently deleted.+ const deletedFileIDs = new Set<number>();+ for (const change of diff) {+ sinceTime = Math.max(sinceTime, change.updatedAt);+ const fileID = change.file.id;+ if (change.isDeleted) deletedFileIDs.add(fileID);+ if (change.isDeleted || change.isRestored) {+ trashItemsByID.delete(fileID);+ } else {+ const collectionID = change.file.collectionID;+ let collectionKey = collectionKeyByID.get(collectionID);+ if (!collectionKey) {+ // See: [Note: Trash item collection keys]+ const collection = await getCollectionByID(collectionID);+ collectionKey = collection.key;+ collectionKeyByID.set(collectionID, collectionKey);+ trashItemCollectionKeys.push({+ id: collectionID,+ key: collectionKey,+ });+ await saveTrashItemCollectionKeys(trashItemCollectionKeys);+ }+ trashItemsByID.set(fileID, {+ ...change,+ file: await decryptRemoteFile(change.file, collectionKey),+ });+ }+ }++ const trashItems = [...trashItemsByID.values()];+ onSetTrashedItems?.(trashItems);+ await saveTrashItems(trashItems);+ await saveTrashLastUpdatedAt(sinceTime);+ if (deletedFileIDs.size) await onPruneDeletedFileIDs(deletedFileIDs);+ if (!hasMore) break;+ }++ const trashCollectionIDs = new Set(+ [...trashItemsByID.values()].map((item) => item.file.collectionID),+ );+ await saveTrashItemCollectionKeys(+ [...collectionKeyByID.entries()]+ .filter(([id]) => trashCollectionIDs.has(id))+ .map(([id, key]) => ({ id, key })),+ );+};++/**+ * See {@link FileDiffResponse} for general semantics of diff responses.+ */+const TrashDiffResponse = z.object({+ diff: RemoteTrashItem.array(),+ hasMore: z.boolean(),+});++/**+ * Fetch all trash items that have been created or updated since+ * {@link sinceTime}.+ *+ * Remote only, does not modify local state.+ *+ * @param sinceTime The {@link updatedAt} of the most recently updated trash+ * item we have previously fetched from remote. This serves both as a pagination+ * mechanish, and a way to fetch a delta diff the next time the client needs to+ * pull changes from remote.+ */+const getTrashDiff = async (sinceTime: number) => {+ const res = await fetch(await apiURL("/trash/v2/diff", { sinceTime }), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return TrashDiffResponse.parse(await res.json());+};++/**+ * Sort trash items such that the items which were recently deleted are first.+ *+ * This is a variant of {@link sortFiles}; it sorts {@link items} in place and+ * also returns a reference to the same mutated arrays.+ *+ * Items are sorted in descending order of their time to deletion (that is, the+ * items which were the most recently deleted will be at the top). For items+ * with the same time to deletion, the ordering is in descending order of the+ * item's file's modification or creation date.+ */+export const sortTrashItems = (trashItems: TrashItem[]) =>+ trashItems.sort((a, b) => {+ if (a.deleteBy == b.deleteBy) {+ const af = a.file;+ const bf = b.file;+ const at = fileCreationTime(af);+ const bt = fileCreationTime(bf);+ return at == bt+ ? bf.metadata.modificationTime - af.metadata.modificationTime+ : bt - at;+ }+ return b.deleteBy - a.deleteBy;+ });++/**+ * Return the IDs of all the files that are part of the trash in our local+ * database.+ */+export const savedTrashItemFileIDs = () =>+ savedTrashItems().then((items) => new Set(items.map((f) => f.file.id)));++/**+ * Delete all the items in trash, permanently deleting the files corresponding+ * to them.+ *+ * This updates both remote and our local database.+ */+export const emptyTrash = async () => {+ await postTrashEmpty((await savedTrashLastUpdatedAt()) ?? 0);+ await saveTrashItems([]);+};++/**+ * Delete all the items in trash on remote.+ *+ * Remote only, does not modify local state.+ *+ * @param lastUpdatedAt The {@link updatedAt} value of the most recent item in+ * trash for the user that we know about locally. Remote will only delete trash+ * entries with updatedAt timestamp <= this provided lastUpdatedAt.+ *+ * The user's trash is cleaned up in an async manner. This timestamp is used to+ * ensure that newly trashed files are not deleted due to delay in the async+ * operation, and that out of sync clients (who have a stale lastUpdatedAt)+ * do not cause deletion of newer files that they don't know about locally.+ */+const postTrashEmpty = async (lastUpdatedAt: number) =>+ ensureOk(+ await fetch(await apiURL("/trash/empty"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ lastUpdatedAt }),+ }),+ );diff --git a/web/apps/albums/vendor/ente-new/photos/services/user-details.ts b/web/apps/albums/vendor/ente-new/photos/services/user-details.tsnew file mode 100644index 0000000000..7202441633--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/user-details.ts@@ -0,0 +1,622 @@+import { updateSavedLocalUser } from "ente-accounts/services/accounts-db";+import { ensureLocalUser } from "ente-accounts/services/user";+import { isDesktop } from "ente-base/app";+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";+import { getKV, setKV } from "ente-base/kv";+import log from "ente-base/log";+import { apiURL } from "ente-base/origins";+import {+ nullishToEmpty,+ nullishToZero,+ nullToUndefined,+} from "ente-utils/transform";+import { z } from "zod";++/**+ * Validity of the plan.+ */+export type PlanPeriod = "month" | "year";++const Subscription = z.object({+ /**+ * Store-specific ID of the product ("plan") that the user has subscribed+ * to. e.g. if the user has subscribed to a plan using Stripe, then this+ * will be the stripeID of the corresponding {@link Plan}.+ *+ * For free plans, the productID will be the constant "free".+ */+ productID: z.string(),+ /**+ * Storage (in bytes) that the user can use.+ */+ storage: z.number(),+ /**+ * Epoch microseconds indicating the time until which the user's+ * subscription is valid.+ */+ expiryTime: z.number(),+ paymentProvider: z.string(),+ price: z.string(),+ period: z+ .string()+ .transform((p) => (p == "month" || p == "year" ? p : undefined)),+ attributes: z+ .object({+ isCancelled: z.boolean().nullish().transform(nullToUndefined),+ })+ .nullish()+ .transform(nullToUndefined),+});++/**+ * Details about the user's subscription.+ */+export type Subscription = z.infer<typeof Subscription>;++const FamilyMember = z.object({+ /**+ * Email address of the family member.+ */+ email: z.string(),+ /**+ * `true` if this is the admin.+ *+ * This field will not be sent for invited members until they accept.+ */+ isAdmin: z.boolean().nullish().transform(nullToUndefined),+ /**+ * Storage used by the family member.+ *+ * This field will not be present for invited members until they accept.+ */+ usage: z.number().nullish().transform(nullToUndefined),+ /**+ * Storage limit allocated to the family member.+ *+ * This field will not be present unless the admin for the family plan has+ * configured a member specific limit, in which case this will be the limit+ * (in bytes) specifying the storage which this member can use.+ */+ storageLimit: z.number().nullish().transform(nullToUndefined),+});++type FamilyMember = z.infer<typeof FamilyMember>;++/**+ * Zod schema for details about the family plan (if any) that the user is a part+ * of.+ */+const FamilyData = z.object({+ members: z.array(FamilyMember),+ /**+ * Family admin subscription storage capacity.+ *+ * This excludes add-on and any other bonus storage.+ */+ storage: z.number(),+});++/**+ * Details about the family plan (if any) that the user is a part of.+ */+export type FamilyData = z.infer<typeof FamilyData>;++const Bonus = z.object({+ /**+ * The type of the bonus.+ */+ type: z.string(),+ /**+ * Amount of storage bonus (in bytes) added to the account.+ */+ storage: z.number(),+ /**+ * Validity of the storage bonus. If it is 0, it is valid forever.+ */+ validTill: z.number(),+});++/**+ * Details about an individual bonus applied for the user.+ */+export type Bonus = z.infer<typeof Bonus>;++const BonusData = z.object({+ /**+ * List of bonuses applied for the user.+ */+ storageBonuses: Bonus.array().nullish().transform(nullishToEmpty),+});++/**+ * Information about bonuses applied for the user.+ */+export type BonusData = z.infer<typeof BonusData>;++/**+ * Zod schema for {@link UserDetails}+ */+const UserDetails = z.object({+ email: z.string(),+ usage: z.number(),+ fileCount: z.number().nullish().transform(nullishToZero),+ subscription: Subscription,+ familyData: FamilyData.nullish().transform(nullToUndefined),+ storageBonus: z.number().nullish().transform(nullishToZero),+ bonusData: BonusData.nullish().transform(nullToUndefined),+});++export type UserDetails = z.infer<typeof UserDetails>;++/**+ * Internal in-memory state shared by the functions in this module.+ *+ * This entire object will be reset on logout.+ */+class UserDetailsState {+ /**+ * Subscriptions to {@link UserDetails} updates attached using+ * {@link userDetailsSubscribe}.+ */+ userDetailsListeners: (() => void)[] = [];++ /**+ * Snapshot of the {@link UserDetails} returned by the+ * {@link userDetailsSnapshot} function.+ */+ userDetailsSnapshot: UserDetails | undefined;+}++/**+ * State shared by the functions in this module. See {@link UserDetailsState}.+ */+let _state = new UserDetailsState();++export const logoutUserDetails = () => {+ _state = new UserDetailsState();+};++/**+ * Read in the locally persisted user details into memory and return them.+ *+ * If there are no locally persisted values, initiate a network requests to+ * fetch the latest values (but don't wait for it to complete).+ *+ * This assumes that the user is already logged in.+ */+export const savedUserDetailsOrTriggerPull = async () => {+ const saved = await getKV("userDetails");+ if (saved) {+ const userDetails = UserDetails.parse(saved);+ setUserDetailsSnapshot(userDetails);+ return userDetails;+ } else {+ void pullUserDetails();+ return undefined;+ }+};++/**+ * A function that can be used to subscribe to updates to {@link UserDetails}.+ *+ * [Note: Snapshots and useSyncExternalStore]+ *+ * This subscribe function, along with {@link userDetailsSnapshot}, is meant to+ * be used as arguments to React's {@link useSyncExternalStore}.+ *+ * @param callback A function that will be invoked whenever the result of+ * {@link userDetailsSnapshot} changes.+ *+ * @returns A function that can be used to clear the subscription.+ */+export const userDetailsSubscribe = (onChange: () => void): (() => void) => {+ _state.userDetailsListeners.push(onChange);+ return () => {+ _state.userDetailsListeners = _state.userDetailsListeners.filter(+ (l) => l != onChange,+ );+ };+};++/**+ * Return the last known, cached {@link UserDetails}.+ *+ * This, along with {@link userDetailsSubscribe}, is meant to be used as+ * arguments to React's {@link useSyncExternalStore}.+ */+export const userDetailsSnapshot = () => _state.userDetailsSnapshot;++const setUserDetailsSnapshot = (snapshot: UserDetails) => {+ _state.userDetailsSnapshot = snapshot;+ _state.userDetailsListeners.forEach((l) => l());+};++/**+ * Fetch the user's details from remote and save them in local storage for+ * subsequent lookup, and also update our in-memory snapshots.+ */+export const pullUserDetails = async () => {+ const userDetails = await getUserDetails();+ await setKV("userDetails", userDetails);++ // Update the email for the local storage user if needed (the user might've+ // changed their email on a different client).+ const { email } = userDetails;+ if (ensureLocalUser().email != email) {+ log.info("Updating user email to match fetched user details");+ updateSavedLocalUser({ email });+ }++ // The gallery listens for updates to userDetails, so a special case, do a+ // deep equality check so as to not rerender it on redundant updates.+ //+ // [Note: Deep equal check]+ //+ // React uses `Object.is` to detect changes, which changes for arrays,+ // objects and combinations thereof even if the underlying data is the same.+ //+ // In many cases, the code can be restructured to avoid this being a+ // problem, or the rerender might be infrequent enough that it is not a+ // problem.+ //+ // However, when used with useSyncExternalStore, there is an easy way to+ // prevent this, by doing a preflight deep equality comparison.+ //+ // There are arguably faster libraries out there that'll do the deep+ // equality check for us, but since it is an infrequent pattern in our code+ // base currently, we just use the JSON serialization.+ //+ // Mark all cases that do this using this note's title so we can audit them+ // if we move to a deep equality comparison library in the future.++ if (JSON.stringify(userDetails) != JSON.stringify(userDetailsSnapshot())) {+ setUserDetailsSnapshot(userDetails);+ }+};++/**+ * Fetch the user details for the currently logged in user from remote.+ */+const getUserDetails = async () => {+ const res = await fetch(await apiURL("/users/details/v2"), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return UserDetails.parse(await res.json());+};++/**+ * Zod schema for an individual plan received in the list of plans.+ */+const Plan = z.object({+ id: z.string(),+ androidID: z.string().nullish().transform(nullToUndefined),+ iosID: z.string().nullish().transform(nullToUndefined),+ stripeID: z.string().nullish().transform(nullToUndefined),+ storage: z.number(),+ price: z.string(),+ period: z+ .string()+ .transform((p) => (p == "month" || p == "year" ? p : undefined)),+});++/**+ * An individual plan received in the list of plans from remote.+ */+export type Plan = z.infer<typeof Plan>;++const PlansData = z.object({+ freePlan: z.object({+ /* Number of bytes available in the free plan. */+ storage: z.number(),+ }),+ plans: z.array(Plan),+});++export type PlansData = z.infer<typeof PlansData>;++/**+ * Fetch the list of plans from remote.+ */+export const getPlansData = async (): Promise<PlansData> => {+ const res = await fetch(await apiURL("/billing/user-plans"), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return PlansData.parse(await res.json());+};++/**+ * Derive the total usage for the user both when they are on an individual plan,+ * or on a family plan.+ */+export const planUsage = (userDetails: UserDetails) =>+ isPartOfFamily(userDetails) ? familyUsage(userDetails) : userDetails.usage;++/**+ * Ask remote to acknowledge a subscription that was completed via Stripe,+ * updating our local state to reflect the new subscription on successful+ * verification.+ *+ * @param sessionID Arbitrary and optional string passed on completion of the+ * flow. It is forwarded as the verification data to remote.+ */+export const verifyStripeSubscription = async (+ sessionID: unknown,+): Promise<Subscription> => {+ ensureOk(+ await fetch(await apiURL("/billing/verify-subscription"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({+ paymentProvider: "stripe",+ productID: null,+ verificationData: sessionID,+ }),+ }),+ );+ await pullUserDetails();+ return userDetailsSnapshot()!.subscription;+};++/**+ * Ask remote to reactivate the user's current Stripe subscription (that user+ * had previously cancelled), updating our local state to reflect the changes on+ * success.+ */+export const activateStripeSubscription = async () => {+ ensureOk(+ await fetch(await apiURL("/billing/stripe/activate-subscription"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ }),+ );+ return pullUserDetails();+};++/**+ * Ask remote to cancel the user's current Stripe subscription, updating our+ * local state to reflect the changes on success.+ */+export const cancelStripeSubscription = async () => {+ ensureOk(+ await fetch(await apiURL("/billing/stripe/cancel-subscription"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ }),+ );+ return pullUserDetails();+};++const paymentsAppOrigin = "https://payments.ente.io";++/**+ * Start the flow to purchase or update a subscription by redirecting the user+ * to the payments app.+ *+ * @param productID The Stripe product ID of the plan to purchase.+ *+ * @param action buy or update.+ */+export const redirectToPaymentsApp = async (+ productID: string,+ action: "buy" | "update",+) => {+ const paymentToken = await getPaymentToken();+ const redirectURL = paymentCompletionRedirectURL();+ window.location.href = `${paymentsAppOrigin}?productID=${productID}&paymentToken=${paymentToken}&action=${action}&redirectURL=${redirectURL}`;+};++/**+ * Return the URL to which the payments app should redirect back on completion+ * of the flow.+ */+const paymentCompletionRedirectURL = () =>+ isDesktop+ ? `${paymentsAppOrigin}/desktop-redirect`+ : `${window.location.origin}/gallery`;++/**+ * Fetch and return a one-time token that can be used to authenticate user's+ * requests to the payments app.+ */+const getPaymentToken = async () => {+ const res = await fetch(await apiURL("/users/payment-token"), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return z.object({ paymentToken: z.string() }).parse(await res.json())+ .paymentToken;+};++/**+ * Redirect to the Stripe customer portal / dashboard where the user can view+ * details about their subscription and modify their payment method.+ */+export const redirectToCustomerPortal = async () => {+ const redirectURL = paymentCompletionRedirectURL();+ const res = await fetch(+ await apiURL("/billing/stripe/customer-portal", { redirectURL }),+ { headers: await authenticatedRequestHeaders() },+ );+ ensureOk(res);+ const portal = z.object({ url: z.string() }).parse(await res.json());+ window.location.href = portal.url;+};++/**+ * Return true if the given {@link Subscription} has not expired.+ */+export const isSubscriptionActive = (subscription: Subscription) =>+ subscription.expiryTime > Date.now() * 1000;++/**+ * Return true if the given {@link Subscription} is active and for a paid plan.+ */+export const isSubscriptionActivePaid = (subscription: Subscription) =>+ isSubscriptionActive(subscription) && subscription.productID != "free";++/**+ * Return true if the given {@link Subscription} is for a free plan.+ */+export const isSubscriptionFree = (subscription: Subscription) =>+ subscription.productID == "free";++/**+ * Return true if the given {@link Subscription} is active and for the given+ * {@link Plan}.+ */+export const isSubscriptionForPlan = (subscription: Subscription, plan: Plan) =>+ plan.stripeID === subscription.productID ||+ plan.iosID === subscription.productID ||+ plan.androidID === subscription.productID;++/**+ * Return true if the given {@link Subscription} is using Stripe.+ */+export const isSubscriptionStripe = (subscription: Subscription) =>+ subscription.paymentProvider == "stripe";++/**+ * Return true if the given {@link Subscription} has the cancelled attribute.+ */+export const isSubscriptionCancelled = (subscription: Subscription) =>+ subscription.attributes?.isCancelled;++/**+ * Return true if the user (represented by the given {@link userDetails}) is+ * part of a family plan.+ */+export const isPartOfFamily = (userDetails: UserDetails) =>+ (userDetails.familyData?.members.length ?? 0) > 0;++/**+ * Return true if the user (represented by the given {@link userDetails}) is+ * part of a family plan which has members in the family.+ */+export const isPartOfFamilyWithOtherMembers = (userDetails: UserDetails) =>+ (userDetails.familyData?.members.length ?? 0) > 1;++/**+ * Return true if the user (represented by the given {@link userDetails}) is the+ * admin for the family plan.+ */+export const isFamilyAdmin = (userDetails: UserDetails) =>+ userDetails.email == familyAdminEmail(userDetails);++/**+ * Return the member specific storage limit for the user (represented by the+ * given {@link userDetails}).+ */+export const familyMemberStorageLimit = (userDetails: UserDetails) =>+ userDetails.familyData?.members.find((m) => m.email == userDetails.email)+ ?.storageLimit;++/**+ * Return the email of the admin for the family plan, if any, that the user+ * (represented by the given {@link userDetails}) is a part of.+ */+export const familyAdminEmail = (userDetails: UserDetails) =>+ userDetails.familyData?.members.find((x) => x.isAdmin)?.email;++/**+ * Return the combined usage of all the family members.+ */+export const familyUsage = (userDetails: UserDetails) =>+ (userDetails.familyData?.members ?? []).reduce(+ (sum, { usage }) => sum + (usage ?? 0),+ 0,+ );++/**+ * Return a pre-authenticated URL for the families app, where the user can+ * manage their family plan.+ */+export const getFamilyPortalRedirectURL = async () => {+ const userDetails = userDetailsSnapshot();++ const { familiesToken: token, familyUrl: familiesURL } =+ await getFamiliesTokenAndURL();+ const isFamilyCreated =+ userDetails && isPartOfFamily(userDetails) ? "true" : "false";+ const redirectURL = `${window.location.origin}/gallery`;+ const params = new URLSearchParams({ token, isFamilyCreated, redirectURL });+ return `${familiesURL}?${params.toString()}`;+};++/**+ * Fetch and return a one-time token that can be used to authenticate user's+ * requests to the families app, alongwith the URL of the families app.+ */+const getFamiliesTokenAndURL = async () => {+ const res = await fetch(await apiURL("/users/families-token"), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return z+ .object({+ // The origin that serves the family dashboard which can be used to+ // create or manage family plans.+ familyUrl: z.string(),+ // A token that can be used to authenticate with the family+ // dashboard.+ familiesToken: z.string(),+ })+ .parse(await res.json());+};++/**+ * Update remote to indicate that the user wants to leave the family plan that+ * they are part of, then update our local user details by pulling the latest+ * ones from remote.+ */+export const leaveFamily = async () => {+ ensureOk(+ await fetch(await apiURL("/family/leave"), {+ method: "DELETE",+ headers: await authenticatedRequestHeaders(),+ }),+ );+ return pullUserDetails();+};++/**+ * Return true if the given {@link Subscription} has expired, and is also beyond+ * the grace period.+ */+export const isSubscriptionPastDue = (subscription: Subscription) => {+ const thirtyDaysMicroseconds = 30 * 24 * 60 * 60 * 1000 * 1000;+ const currentTime = Date.now() * 1000;+ return (+ !isSubscriptionCancelled(subscription) &&+ subscription.expiryTime < currentTime &&+ subscription.expiryTime >= currentTime - thirtyDaysMicroseconds+ );+};++/**+ * Return the bonuses whose type starts with "ADD_ON" applicable for the user+ * (represented by the given {@link userDetails}).+ */+export const userDetailsAddOnBonuses = (userDetails: UserDetails) =>+ userDetails.bonusData?.storageBonuses.filter((bonus) =>+ bonus.type.startsWith("ADD_ON"),+ ) ?? [];++/**+ * Return true if the user (represented by the given {@link userDetails}) has a+ * exceeded their storage quota (individual or of the family plan they are a+ * part of).+ */+export const hasExceededStorageQuota = (userDetails: UserDetails) => {+ let usage: number;+ let storage: number;+ if (isPartOfFamily(userDetails)) {+ usage = familyUsage(userDetails);+ storage = userDetails.familyData?.storage ?? 0;+ } else {+ usage = userDetails.usage;+ storage = userDetails.subscription.storage;+ }+ return usage > storage + userDetails.storageBonus;+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/user-entity/db.ts b/web/apps/albums/vendor/ente-new/photos/services/user-entity/db.tsnew file mode 100644index 0000000000..7558acee55--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/user-entity/db.ts@@ -0,0 +1,93 @@+import { getKV, getKVN, setKV } from "ente-base/kv";+import { z } from "zod";+import { type EntityType } from ".";+import { RemoteUserEntityKey } from "./remote";++// Our DB footprint---+//+// All these are stored in the kv db.++const entitiesKey = (type: EntityType) => `entity/${type}`;+const entityKeyKey = (type: EntityType) => `entity/${type}/key`;+const latestUpdatedAtKey = (type: EntityType) => `entity/${type}/time`;++// ^---++/**+ * A locally persisted user entity.+ */+export interface LocalUserEntity {+ /**+ * The UUID or nanoid of the entity.+ */+ id: string;+ /**+ * Arbitrary (decrypted) data associated with the entity. The format of this+ * data is specific to each entity type, but it is guaranteed to be JSON+ * serializable.+ */+ data: unknown;+ /**+ * Epoch microseconds denoting when this entity was last changed (created or+ * updated).+ */+ updatedAt: number;+}++const LocalUserEntity = z.object({+ id: z.string(),+ // Retain the data verbatim.+ data: z.looseObject({}),+ updatedAt: z.number(),+});++/**+ * Update the list of locally persisted user entities of the given {@link type}.+ */+export const saveEntities = (type: EntityType, items: LocalUserEntity[]) =>+ setKV(entitiesKey(type), items);++/**+ * Return the list of locally persisted user entities of the given {@link type}.+ */+export const savedEntities = async (+ type: EntityType,+): Promise<LocalUserEntity[]> =>+ LocalUserEntity.array().parse((await getKV(entitiesKey(type))) ?? []);++/**+ * Save the {@link entityKey} for the given user entity {@link type} to our+ * local database.+ */+export const saveRemoteUserEntityKey = (+ type: EntityType,+ entityKey: RemoteUserEntityKey,+) => setKV(entityKeyKey(type), entityKey);++/**+ * Return the locally persisted {@link RemoteUserEntityKey}, if any,+ * corresponding the given user entity {@link type}.+ */+export const savedRemoteUserEntityKey = (+ type: EntityType,+): Promise<RemoteUserEntityKey | undefined> =>+ getKV(entityKeyKey(type)).then((s) =>+ s ? RemoteUserEntityKey.parse(s) : undefined,+ );++/**+ * Save the latest `updatedAt` {@link value} for the given user entity+ * {@link type} to our local database.+ */+export const saveLatestUpdatedAt = (type: EntityType, value: number) =>+ setKV(latestUpdatedAtKey(type), value);++/**+ * Return the locally persisted value for the latest `updatedAt` time for the+ * given user entity {@link type}.+ *+ * This is used to checkpoint diffs, so that we can resume fetching from the+ * last time we did a fetch.+ */+export const savedLatestUpdatedAt = (type: EntityType) =>+ getKVN(latestUpdatedAtKey(type));diff --git a/web/apps/albums/vendor/ente-new/photos/services/user-entity/index.ts b/web/apps/albums/vendor/ente-new/photos/services/user-entity/index.tsnew file mode 100644index 0000000000..6a4dea2ce0--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/user-entity/index.ts@@ -0,0 +1,292 @@+import {+ decryptBox,+ encryptBlob,+ encryptBox,+ generateBlobOrStreamKey,+} from "ente-base/crypto";+import { nullishToEmpty, nullToUndefined } from "ente-utils/transform";+import { z } from "zod";+import { gunzip, gzip } from "../../utils/gzip";+import type { CGroupUserEntityData } from "../ml/people";+import {+ savedEntities,+ savedLatestUpdatedAt,+ savedRemoteUserEntityKey,+ saveEntities,+ saveLatestUpdatedAt,+ saveRemoteUserEntityKey,+ type LocalUserEntity,+} from "./db";+import {+ getUserEntityKey,+ postUserEntity,+ postUserEntityKey,+ putUserEntity,+ RemoteUserEntityKey,+ userEntityDiff,+} from "./remote";++/**+ * User entities are predefined lists of otherwise arbitrary data that the user+ * can store for their account.+ *+ * e.g. location tags, cluster groups.+ */+export type EntityType =+ /**+ * A location tag.+ *+ * The entity data is base64(encrypt(json))+ */+ | "location"+ /**+ * A cluster group.+ *+ * The entity data is base64(encrypt(gzip(json)))+ */+ | "cgroup";++/**+ * Zod schema for the fields of interest in the location tag that we get from+ * remote.+ */+const RemoteLocationTagData = z.looseObject({+ name: z.string(),+ radius: z.number(),+ centerPoint: z.object({ latitude: z.number(), longitude: z.number() }),+});++/**+ * A view of the location tag data suitable for use by the rest of the app.+ */+export type LocationTag = z.infer<typeof RemoteLocationTagData>;++/**+ * Return the list of locally available location tags.+ */+export const savedLocationTags = (): Promise<LocationTag[]> =>+ savedEntities("location").then((es) =>+ es.map((e) => RemoteLocationTagData.parse(e.data)),+ );++const RemoteFaceCluster = z.looseObject({+ id: z.string(),+ faces: z.string().array(),+});++/**+ * Zod schema for the fields of interest in the cgroup that we get from remote.+ *+ * See also: {@link CGroupUserEntityData}.+ *+ * See: [Note: Use looseObject for metadata Zod schemas].+ */+const RemoteCGroupData = z.looseObject({+ name: z.string().nullish().transform(nullToUndefined),+ // Accept nullish entries within the array and filter them out.+ assigned: z+ .array(RemoteFaceCluster.nullish())+ .nullish()+ .transform((arr) =>+ (arr ?? []).filter(+ (x): x is z.infer<typeof RemoteFaceCluster> => x != null,+ ),+ ),+ rejectedFaceIDs: z.array(z.string()).nullish().transform(nullishToEmpty),+ manuallyAssigned: z.array(z.number()).nullish().transform(nullishToEmpty),+ isHidden: z.boolean(),+ avatarFaceID: z.string().nullish().transform(nullToUndefined),+ isPinned: z.boolean().nullish().transform(Boolean),+ hideFromMemories: z.boolean().nullish().transform(Boolean),+});++/**+ * A "cgroup" user entity.+ */+export type CGroup = Omit<LocalUserEntity, "data"> & {+ // CGroupUserEntityData is meant to be a (documented) equivalent of+ // `z.infer<typeof RemoteCGroup>`.+ data: CGroupUserEntityData;+};++/**+ * Return the list of locally available cgroup user entities.+ */+export const savedCGroups = (): Promise<CGroup[]> =>+ savedEntities("cgroup").then((es) =>+ es.map((e) => ({ ...e, data: RemoteCGroupData.parse(e.data) })),+ );++/**+ * Update our local entities of the given {@link type} by pulling the latest+ * changes from remote.+ *+ * This fetches all the user entities corresponding to the given user entity+ * type from remote that have been created, updated or deleted since the last+ * time we checked.+ *+ * This diff is then applied to the data we have persisted locally.+ *+ * It uses local state to remember the latest entry the last time it did a pull,+ * so each subsequent pull is a lightweight diff.+ *+ * @param masterKey The user's masterKey (as a base64 string), which is is used+ * to encrypt and decrypt the entity key.+ */+export const pullUserEntities = async (type: EntityType, masterKey: string) => {+ const entityKey = await getOrCreateEntityKey(type, masterKey);++ let sinceTime = (await savedLatestUpdatedAt(type)) ?? 0;+ while (true) {+ const diff = await userEntityDiff(type, sinceTime, entityKey);+ if (diff.length == 0) break;++ const entityByID = new Map(+ (await savedEntities(type)).map((e) => [e.id, e]),+ );++ for (const { id, data, updatedAt } of diff) {+ if (data) {+ const s = isGzipped(type)+ ? await gunzip(data)+ : new TextDecoder().decode(data);+ entityByID.set(id, { id, data: JSON.parse(s), updatedAt });+ } else {+ entityByID.delete(id);+ }+ sinceTime = Math.max(sinceTime, updatedAt);+ }++ await saveEntities(type, [...entityByID.values()]);+ await saveLatestUpdatedAt(type, sinceTime);+ }+};++const isGzipped = (type: EntityType) => type == "cgroup";++/**+ * Create a new user entity of the given {@link type}.+ *+ * @param data Arbitrary data associated with the entity. The format of the data+ * is specific to each entity type, but the provided data should be JSON+ * serializable (Typescript does not have a native JSON type, so we need to+ * specify this as an `unknown`).+ *+ * @param masterKey The user's masterKey, which is is used to encrypt and+ * decrypt the entity key.+ *+ * @returns The ID of the newly created entity.+ */+export const addUserEntity = async (+ type: EntityType,+ data: unknown,+ masterKey: string,+) =>+ await postUserEntity(+ type,+ await encryptedUserEntityData(type, data, masterKey),+ );++const encryptedUserEntityData = async (+ type: EntityType,+ data: unknown,+ masterKey: string,+) => {+ const entityKey = await getOrCreateEntityKey(type, masterKey);++ const json = JSON.stringify(data);+ const bytes = isGzipped(type)+ ? await gzip(json)+ : new TextEncoder().encode(json);+ return encryptBlob(bytes, entityKey);+};++/**+ * Update the given user entities (both on remote and locally), creating them if+ * they don't exist.+ *+ * @param masterKey The user's masterKey (as a base64 string), which is is used+ * to encrypt and decrypt the entity key.+ */+export const updateOrCreateUserEntities = async (+ type: EntityType,+ entities: LocalUserEntity[],+ masterKey: string,+) =>+ await Promise.all(+ entities.map(({ id, data }) =>+ encryptedUserEntityData(type, data, masterKey).then(+ (encryptedBlob) => putUserEntity(id, type, encryptedBlob),+ ),+ ),+ );++/**+ * Return the entity key (base64 string) that can be used to decrypt the+ * encrypted contents of user entities of the given {@link type}.+ *+ * 1. See if we have the encrypted entity key present locally. If so, return the+ * entity key by decrypting it using with the user's master key.+ *+ * 2. Otherwise fetch the encrypted entity key for that type from remote. If we+ * get one, obtain the entity key by decrypt the encrypted one using the+ * user's master key, save it locally for future use, and return it.+ *+ * 3. Otherwise generate a new entity key, encrypt it using the user's master+ * key, putting the encrypted one to remote and also saving it locally, and+ * return it.+ *+ * See also, [Note: User entity keys].+ */+const getOrCreateEntityKey = async (type: EntityType, masterKey: string) => {+ // See if we already have it locally.+ const saved = await savedRemoteUserEntityKey(type);+ if (saved) return decryptEntityKey(saved, masterKey);++ // See if remote already has it.+ const existing = await getUserEntityKey(type);+ if (existing) {+ // Only save it if we can decrypt it to avoid corrupting our local state+ // in unforeseen circumstances.+ const result = await decryptEntityKey(existing, masterKey);+ await saveRemoteUserEntityKey(type, existing);+ return result;+ }++ // Nada. Create a new one, put it to remote, save it locally, and return.++ // As a sanity check, generate the key but immediately encrypt it as if it+ // were fetched from remote and then try to decrypt it before doing anything+ // with it.+ const generated = await generateEncryptedEntityKey(masterKey);+ const result = decryptEntityKey(generated, masterKey);+ await postUserEntityKey(type, generated);+ await saveRemoteUserEntityKey(type, generated);+ return result;+};++const generateEncryptedEntityKey = async (masterKey: string) => {+ const { encryptedData, nonce } = await encryptBox(+ await generateBlobOrStreamKey(),+ masterKey,+ );+ // Remote calls it the header, but it really is the nonce.+ return { encryptedKey: encryptedData, header: nonce };+};++/**+ * Decrypt an encrypted entity key (as a base64 string) using the provided+ * user's {@link masterKey}.+ */+const decryptEntityKey = async (+ remote: RemoteUserEntityKey,+ masterKey: string,+) =>+ decryptBox(+ {+ encryptedData: remote.encryptedKey,+ // Remote calls it the header, but it really is the nonce.+ nonce: remote.header,+ },+ masterKey,+ );diff --git a/web/apps/albums/vendor/ente-new/photos/services/user-entity/remote.ts b/web/apps/albums/vendor/ente-new/photos/services/user-entity/remote.tsnew file mode 100644index 0000000000..dd685e1bff--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/user-entity/remote.ts@@ -0,0 +1,267 @@+import { decryptBlobBytes } from "ente-base/crypto";+import type { EncryptedBlobB64 } from "ente-base/crypto/types";+import {+ authenticatedRequestHeaders,+ ensureOk,+ HTTPError,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { z } from "zod";+import type { EntityType } from ".";++/**+ * The maximum number of items to fetch in a single diff+ *+ * [Note: Limit of returned items in /diff requests]+ *+ * The various GET /diff API methods, which tell the client what all has changed+ * since a timestamp (provided by the client) take a limit parameter.+ *+ * These diff API calls return all items whose updated at is greater+ * (non-inclusive) than the timestamp we provide. So there is no mechanism for+ * pagination of items which have the exact same updated at.+ *+ * Conceptually, it may happen that there are more items than the limit we've+ * provided, but there are practical safeguards.+ *+ * For file diff, the limit is advisory, and remote may return less, equal or+ * more items than the provided limit. The scenario where it returns more is+ * when more files than the limit have the same updated at. Theoretically it+ * would make the diff response unbounded, however in practice file+ * modifications themselves are all batched. Even if the user were to select all+ * the files in their library and updates them all in one go in the UI, their+ * client app is required (with server side enforcement) to use batched API+ * calls to make those updates. Thus, each of those batches would get distinct+ * updated at values.+ *+ * For entity diff, there are no bulk operations yet that can result in the+ * assignment of the same microsecond to hundreds of items.+ */+const defaultDiffLimit = 500;++/**+ * An entry in the user entity diff.+ *+ * Each change either contains the latest data associated with a particular user+ * entity that has been created or updated, or has a flag set to indicate that+ * the corresponding entity has been deleted.+ */+export interface UserEntityChange {+ /**+ * The UUID or nanoid of the entity.+ */+ id: string;+ /**+ * Arbitrary (decrypted) data associated with the entity. The format of this+ * data is specific to each entity type.+ *+ * This will not be present for entities that have been deleted on remote.+ */+ data: Uint8Array | undefined;+ /**+ * Epoch microseconds denoting when this entity was last changed (created or+ * updated or deleted).+ */+ updatedAt: number;+}++/**+ * Zod schema for a item in the user entity diff.+ */+const RemoteUserEntityChange = z.object({+ id: z.string(),+ /**+ * Base64 string containing the encrypted contents of the entity.+ *+ * Will be `null` when isDeleted is true.+ */+ encryptedData: z.string().nullable(),+ /**+ * Base64 string containing the decryption header.+ *+ * Will be `null` when isDeleted is true.+ */+ header: z.string().nullable(),+ /**+ * `true` if the corresponding entity was deleted.+ */+ isDeleted: z.boolean(),+ /**+ * Epoch microseconds when this entity was last updated.+ *+ * This value is suitable for being passed as the `sinceTime` in the diff+ * requests to implement pagination.+ */+ updatedAt: z.number(),+});++/**+ * Fetch the next set of changes (upserts or deletions) to user entities of the+ * given type since the given time.+ *+ * @param type The type of the entities to fetch.+ *+ * @param sinceTime Epoch microseconds. This is used to ask remote to provide us+ * only entities whose {@link updatedAt} is more than the given value. Set this+ * to zero to start from the beginning.+ *+ * @param entityKey The base64 encoded key to use for decrypting the encrypted+ * contents of the user entity.+ *+ * [Note: Diff response will have at most one entry for an id]+ *+ * Unlike git diffs which track all changes, the diffs we get from remote are+ * guaranteed to contain only one entry (upsert or delete) for a particular Ente+ * object. This holds true irrespective of the diff limit.+ *+ * For example, in a user entity diff, it is guaranteed that there will only be+ * at max one entry for a particular entity id. The entry will have no data to+ * indicate that the corresponding entity was deleted. Otherwise, when the data+ * is present, it is taken as the creation of a new entity or the updation of an+ * existing one.+ *+ * This behaviour comes from how remote stores the underlying, say, entities. A+ * diff returns just entities whose updation times greater than the provided+ * since time (limited to the given diff limit). So there will be at most one+ * row for a particular entity id. And if that entity has been deleted, then the+ * row will be a tombstone, so data be absent.+ */+export const userEntityDiff = async (+ type: EntityType,+ sinceTime: number,+ entityKey: string,+): Promise<UserEntityChange[]> => {+ const decrypt = (encryptedData: string, decryptionHeader: string) =>+ decryptBlobBytes({ encryptedData, decryptionHeader }, entityKey);++ const res = await fetch(+ await apiURL("/user-entity/entity/diff", {+ type,+ sinceTime,+ limit: defaultDiffLimit,+ }),+ { headers: await authenticatedRequestHeaders() },+ );+ ensureOk(res);+ const diff = z+ .object({ diff: z.array(RemoteUserEntityChange) })+ .parse(await res.json()).diff;+ return Promise.all(+ diff.map(+ async ({ id, encryptedData, header, isDeleted, updatedAt }) => ({+ id,+ data: !isDeleted+ ? await decrypt(encryptedData!, header!)+ : undefined,+ updatedAt,+ }),+ ),+ );+};++/**+ * Create a new user entity with the given {@link type} on remote.+ *+ * @returns The ID of the newly created entity.+ */+export const postUserEntity = async (+ type: EntityType,+ { encryptedData, decryptionHeader }: EncryptedBlobB64,+) => {+ const res = await fetch(await apiURL("/user-entity/entity"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({+ type,+ encryptedData: encryptedData,+ header: decryptionHeader,+ }),+ });+ ensureOk(res);+ return z.object({ id: z.string() }).parse(await res.json()).id;+};++/**+ * Update an existing remote user entity with the given {@link id} and+ * {@link type}.+ */+export const putUserEntity = async (+ id: string,+ type: EntityType,+ { encryptedData, decryptionHeader }: EncryptedBlobB64,+) =>+ ensureOk(+ await fetch(await apiURL("/user-entity/entity"), {+ method: "PUT",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({+ id,+ type,+ encryptedData: encryptedData,+ header: decryptionHeader,+ }),+ }),+ );++/**+ * Delete an existing remote user entity with the given {@link id}.+ */+export const deleteUserEntity = async (id: string) =>+ ensureOk(+ await fetch(await apiURL("/user-entity/entity", { id }), {+ method: "DELETE",+ headers: await authenticatedRequestHeaders(),+ }),+ );++export const RemoteUserEntityKey = z.object({+ /** Base64 encoded entity key, encrypted with the user's master key. */+ encryptedKey: z.string(),+ /** Base64 encoded nonce used during encryption of this entity key. */+ header: z.string(),+});++export type RemoteUserEntityKey = z.infer<typeof RemoteUserEntityKey>;++/**+ * Fetch the encryption key for the given user entity {@link type} from remote.+ *+ * [Note: User entity keys]+ *+ * There is one encryption key (itself encrypted with the user's master key) for+ * each user entity type. If the key doesn't exist on remote, then the client is+ * expected to create one on the user's behalf. Remote will disallow attempts to+ * multiple keys for the same user entity type.+ */+export const getUserEntityKey = async (+ type: EntityType,+): Promise<RemoteUserEntityKey | undefined> => {+ const res = await fetch(await apiURL("/user-entity/key", { type }), {+ headers: await authenticatedRequestHeaders(),+ });+ if (!res.ok) {+ // Remote says HTTP 404 Not Found if there is no key yet for the user.+ if (res.status == 404) return undefined;+ throw new HTTPError(res);+ } else {+ return RemoteUserEntityKey.parse(await res.json());+ }+};++/**+ * Create a new encryption key for the given user entity {@link type} on remote.+ *+ * See: [Note: User entity keys]+ */+export const postUserEntityKey = async (+ type: EntityType,+ entityKey: RemoteUserEntityKey,+) => {+ const url = await apiURL("/user-entity/key");+ const res = await fetch(url, {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ type, ...entityKey }),+ });+ ensureOk(res);+};diff --git a/web/apps/albums/vendor/ente-new/photos/services/user.ts b/web/apps/albums/vendor/ente-new/photos/services/user.tsnew file mode 100644index 0000000000..48be703d0b--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/services/user.ts@@ -0,0 +1,122 @@+import { ensureSavedKeyAttributes } from "ente-accounts/services/user";+import { boxSealOpenBytes, decryptBox } from "ente-base/crypto";+import type { KeyPair } from "ente-base/crypto/types";+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { ensureMasterKeyFromSession } from "ente-base/session";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";++/**+ * Return the public/private keypair of the currently logged in user.+ */+export const ensureUserKeyPair = async (): Promise<KeyPair> => {+ const { encryptedSecretKey, secretKeyDecryptionNonce, publicKey } =+ ensureSavedKeyAttributes();+ const privateKey = await decryptBox(+ { encryptedData: encryptedSecretKey, nonce: secretKeyDecryptionNonce },+ await ensureMasterKeyFromSession(),+ );+ return { publicKey, privateKey };+};++/**+ * Fetch the public key from remote for the user (if any) who has registered+ * with remote with the given {@link email}.+ *+ * @returns the base64 encoded public key of the user with {@link email}.+ */+export const getPublicKey = async (email: string) => {+ const res = await fetch(await apiURL("/users/public-key", { email }), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return z.object({ publicKey: z.string() }).parse(await res.json())+ .publicKey;+};++/**+ * Fetch the two-factor status (whether or not it is enabled) from remote.+ */+export const get2FAStatus = async () => {+ const res = await fetch(await apiURL("/users/two-factor/status"), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return z.object({ status: z.boolean() }).parse(await res.json()).status;+};++/**+ * Disable two-factor authentication for the current user on remote.+ */+export const disable2FA = async () =>+ ensureOk(+ await fetch(await apiURL("/users/two-factor/disable"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ }),+ );++const DeleteChallengeResponse = z.object({+ // allowDelete indicates whether the user is allowed to delete their account+ // via app (some special-cased accounts might need to contact support).+ allowDelete: z.boolean(),+ // An encrypted challenge that the client needs to decrypt and provide in+ // the actual account deletion request.+ encryptedChallenge: z.string().nullish().transform(nullToUndefined),+});++/**+ * Initiate an account deletion by obtaining a delete challenge from remote.+ *+ * Account deletion is a three step process:+ *+ * 1. Client obtains a encrypted challenge from remote by using+ * {@link getAccountDeleteChallenge}.+ *+ * 2. Client asks the user to reverify their password to solve the challenge and+ * obtain the decrypted challenge ({@link decryptDeleteAccountChallenge}).+ *+ * 3. Client performs the account deletion using the solved challenge+ * ({@link deleteAccount}).+ */+export const getAccountDeleteChallenge = async () => {+ const res = await fetch(await apiURL("/users/delete-challenge"), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return DeleteChallengeResponse.parse(await res.json());+};++/**+ * Decrypt the {@link encryptedChallenge} sent by remote during the delete+ * account flow ({@link getAccountDeleteChallenge}), returning a value that can+ * then directly be passed to the actual delete account request+ * ({@link deleteAccount}).+ */+export const decryptDeleteAccountChallenge = async (+ encryptedChallenge: string,+) =>+ new TextDecoder().decode(+ await boxSealOpenBytes(encryptedChallenge, await ensureUserKeyPair()),+ );++/**+ * Delete the logged in user's account on remote.+ *+ * @param challenge Decrypted value of the challenge previously obtained via+ * {@link getAccountDeleteChallenge}. The decryption algorithm is implemented in+ * {@link decryptDeleteAccountChallenge}.+ */+export const deleteAccount = async (+ challenge: string,+ reason: string,+ feedback: string,+) =>+ ensureOk(+ await fetch(await apiURL("/users/delete"), {+ method: "DELETE",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ challenge, reason, feedback }),+ }),+ );diff --git a/web/apps/albums/vendor/ente-new/photos/types/context.ts b/web/apps/albums/vendor/ente-new/photos/types/context.tsnew file mode 100644index 0000000000..15ced6b718--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/types/context.ts@@ -0,0 +1,41 @@+import { type NotificationAttributes } from "ente-new/photos/components/Notification";+import { createContext, useContext } from "react";++/**+ * The type of the React context available to all pages in the photos app.+ */+export interface PhotosAppContextT {+ /**+ * Show the global activity indicator (a loading bar at the top of the+ * page).+ */+ showLoadingBar: () => void;+ /**+ * Hide the global activity indicator bar.+ */+ hideLoadingBar: () => void;+ /**+ * Show a {@link Notification}, customizing its contents and click behaviour+ * using the provided {@link NotificationAttributes}.+ */+ showNotification: (attributes: NotificationAttributes) => void;+ watchFolderView: boolean;+ setWatchFolderView: (isOpen: boolean) => void;+}++/**+ * The React {@link Context} available to all nodes in the React tree of photos+ * app pages.+ */+export const PhotosAppContext = createContext<PhotosAppContextT | undefined>(+ undefined,+);++/**+ * Utility hook to get the photos {@link PhotosAppContextT}.+ *+ * This context is provided at the top level _app component for the photos app,+ * and thus is available to all React components in the Photos app's React tree.+ */+export const usePhotosAppContext = (): PhotosAppContextT =>+ useContext(PhotosAppContext)!;diff --git a/web/apps/albums/vendor/ente-new/photos/utils/file-actions.ts b/web/apps/albums/vendor/ente-new/photos/utils/file-actions.tsnew file mode 100644index 0000000000..b070360c9d--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/utils/file-actions.ts@@ -0,0 +1,228 @@+import type { GalleryBarMode } from "ente-new/photos/components/gallery/reducer";+import {+ PseudoCollectionID,+ type CollectionSummary,+} from "ente-new/photos/services/collection-summary";++/**+ * Actions that can be performed on files via the context menu.+ *+ * These correspond to the same operations available in SelectedFileOptions.+ */+export type FileContextAction =+ | "sendLink"+ | "download"+ | "fixTime"+ | "editLocation"+ | "favorite"+ | "unfavorite"+ | "archive"+ | "unarchive"+ | "hide"+ | "unhide"+ | "trash"+ | "deletePermanently"+ | "restore"+ | "addToAlbum"+ | "moveToAlbum"+ | "removeFromAlbum"+ | "addPerson";++/**+ * Context needed to determine which file actions should be available.+ */+export interface FileActionContext {+ /** The current bar mode (albums, hidden-albums, people). */+ barMode?: GalleryBarMode;+ /** Whether we're in search mode. */+ isInSearchMode: boolean;+ /**+ * The collection summary for the current view.+ *+ * Will be undefined if we're in people section or showing search results.+ */+ collectionSummary: CollectionSummary | undefined;+ /**+ * Whether to show the "Add Person" action.+ *+ * This depends on ML being enabled and having named people.+ */+ showAddPerson: boolean;+ /**+ * Whether to show the "Edit Location" action.+ *+ * This depends on the selection containing owned files.+ */+ showEditLocation: boolean;+ /**+ * Whether to show the "Send link" action.+ *+ * This depends on the selection containing owned files.+ */+ showSendLink: boolean;+}++/**+ * Returns the list of available file actions based on the current context.+ *+ * This function encapsulates the conditional logic from SelectedFileOptions+ * to enable reuse in both the selection bar and the context menu.+ */+export function getAvailableFileActions(+ context: FileActionContext,+): FileContextAction[] {+ const {+ barMode,+ isInSearchMode,+ collectionSummary,+ showAddPerson,+ showEditLocation,+ showSendLink,+ } = context;++ const actions = getBaseActions(+ barMode,+ isInSearchMode,+ collectionSummary,+ showEditLocation,+ );++ if (showSendLink && collectionSummary?.id !== PseudoCollectionID.trash) {+ insertSendLinkBeforeDownload(actions);+ }++ // Insert "addPerson" before modification actions if enabled+ // (not applicable for trash since you can't add people to trashed files)+ if (showAddPerson && collectionSummary?.id !== PseudoCollectionID.trash) {+ insertAddPersonBeforeModifications(actions);+ }++ return actions;+}++/**+ * Returns base actions without the "addPerson" action.+ */+function getBaseActions(+ barMode: GalleryBarMode | undefined,+ isInSearchMode: boolean,+ collectionSummary: CollectionSummary | undefined,+ showEditLocation: boolean,+): FileContextAction[] {+ // Search mode actions+ if (isInSearchMode) {+ const actions: FileContextAction[] = ["favorite", "fixTime"];+ if (showEditLocation) {+ actions.push("editLocation");+ }+ actions.push("download", "addToAlbum", "archive", "hide", "trash");+ return actions;+ }++ // People mode actions+ if (barMode === "people") {+ return [+ "favorite",+ "download",+ "addToAlbum",+ "archive",+ "hide",+ "trash",+ ];+ }++ // Trash actions+ if (collectionSummary?.id === PseudoCollectionID.trash) {+ return ["restore", "deletePermanently"];+ }++ // Uncategorized actions+ if (collectionSummary?.attributes.has("uncategorized")) {+ return ["download", "moveToAlbum", "trash"];+ }++ // Shared incoming actions+ if (collectionSummary?.attributes.has("sharedIncoming")) {+ return ["download", "removeFromAlbum"];+ }++ // Hidden albums mode actions+ if (barMode === "hidden-albums") {+ return ["download", "unhide", "trash"];+ }++ // Default (normal albums) actions+ const isUserFavorites =+ !!collectionSummary?.attributes.has("userFavorites");+ const isArchiveItems =+ collectionSummary?.id === PseudoCollectionID.archiveItems;++ const actions: FileContextAction[] = [];++ // Favorite/unfavorite action shown when not in archive.+ if (isUserFavorites) {+ actions.push("unfavorite");+ } else if (!isArchiveItems) {+ actions.push("favorite");+ }++ actions.push("fixTime");+ if (showEditLocation) {+ actions.push("editLocation");+ }+ actions.push("download", "addToAlbum");++ if (collectionSummary?.id === PseudoCollectionID.all) {+ actions.push("archive");+ } else if (isArchiveItems) {+ actions.push("unarchive");+ } else if (!isUserFavorites) {+ actions.push("moveToAlbum", "removeFromAlbum");+ }++ actions.push("hide", "trash");++ return actions;+}++/**+ * Inserts "sendLink" before "download" if present, else prepends it.+ */+function insertSendLinkBeforeDownload(actions: FileContextAction[]): void {+ const downloadIndex = actions.indexOf("download");+ if (downloadIndex !== -1) {+ actions.splice(downloadIndex, 0, "sendLink");+ } else {+ actions.unshift("sendLink");+ }+}++/**+ * Actions that modify file visibility or collection membership.+ * "addPerson" is inserted before the first of these actions.+ */+const modificationActions: FileContextAction[] = [+ "archive",+ "unarchive",+ "hide",+ "unhide",+ "trash",+ "moveToAlbum",+ "removeFromAlbum",+];++/**+ * Inserts "addPerson" before the first modification action in the array.+ */+function insertAddPersonBeforeModifications(+ actions: FileContextAction[],+): void {+ const insertIndex = actions.findIndex((a) =>+ modificationActions.includes(a),+ );+ if (insertIndex !== -1) {+ actions.splice(insertIndex, 0, "addPerson");+ } else {+ actions.push("addPerson");+ }+}diff --git a/web/apps/albums/vendor/ente-new/photos/utils/gzip.ts b/web/apps/albums/vendor/ente-new/photos/utils/gzip.tsnew file mode 100644index 0000000000..a5731bfcc2--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/utils/gzip.ts@@ -0,0 +1,30 @@+/**+ * Compress the given {@link string} using "gzip" and return the resultant+ * bytes. See {@link gunzip} for the reverse operation.+ *+ * This is syntactic sugar to deal with the string/blob/stream/bytes+ * conversions, but it should not be taken as an abstraction layer. If your code+ * can directly use a ReadableStream, then then data -> stream -> data round+ * trip is unnecessary.+ */+export const gzip = async (string: string) => {+ const compressedStream = new Blob([string])+ .stream()+ // This code only runs on the desktop app currently, so we can rely on+ // the existence of new web features the CompressionStream APIs.+ .pipeThrough(new CompressionStream("gzip"));+ return new Uint8Array(await new Response(compressedStream).arrayBuffer());+};++/**+ * Decompress the given "gzip" compressed {@link data} and return the resultant+ * string. See {@link gzip} for the reverse operation.+ */+export const gunzip = async (data: Uint8Array) => {+ const decompressedStream = new Blob([data])+ .stream()+ // This code only runs on the desktop app currently, so we can rely on+ // the existence of new web features the CompressionStream APIs.+ .pipeThrough(new DecompressionStream("gzip"));+ return new Response(decompressedStream).text();+};diff --git a/web/apps/albums/vendor/ente-new/photos/utils/native-fs.ts b/web/apps/albums/vendor/ente-new/photos/utils/native-fs.tsnew file mode 100644index 0000000000..94e935a525--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/utils/native-fs.ts@@ -0,0 +1,78 @@+/**+ * @file Utilities for native file system access.+ *+ * While they don't have any direct dependencies to our desktop app, they were+ * written for use by the code that runs in our desktop app.+ */++import { joinPath, nameAndExtension } from "ente-base/file-name";+import {+ exportMetadataDirectoryName,+ exportTrashDirectoryName,+} from "ente-gallery/export-dirs";+import sanitize from "sanitize-filename";++/**+ * Sanitize string for use as file or directory name.+ *+ * Return a string suitable for use as a file or directory name by replacing+ * directory separators and invalid characters in the input string {@link s}+ * with "_".+ */+const sanitizeFilename = (s: string) => sanitize(s, { replacement: "_" });++/**+ * Return a new sanitized and unique directory name based on {@link name} that+ * is not the same as any existing item in the given {@link directoryPath}.+ *+ * We also ensure we don't return names which might collide with our own special+ * directories.+ *+ * @param exists A function to check if an item already exists at the given+ * path. Usually, you'd pass `fs.exists` from {@link Electron}.+ *+ * See also: {@link safeFileame}+ */+export const safeDirectoryName = async (+ directoryPath: string,+ name: string,+ exists: (path: string) => Promise<boolean>,+): Promise<string> => {+ const specialDirectoryNames = [+ exportTrashDirectoryName,+ exportMetadataDirectoryName,+ ];++ let result = sanitizeFilename(name);+ let count = 1;+ while (+ (await exists(joinPath(directoryPath, result))) ||+ specialDirectoryNames.includes(result)+ ) {+ result = `${sanitizeFilename(name)}(${count})`;+ count++;+ }+ return result;+};++/**+ * Return a new sanitized and unique file name based on {@link name} that is not+ * the same as any existing item in the given {@link directoryPath}.+ *+ * This is a sibling of {@link safeDirectoryName} for use with file names.+ */+export const safeFileName = async (+ directoryPath: string,+ name: string,+ exists: (path: string) => Promise<boolean>,+) => {+ let result = sanitizeFilename(name);+ let count = 1;+ while (await exists(joinPath(directoryPath, result))) {+ const [fn, ext] = nameAndExtension(sanitizeFilename(name));+ if (ext) result = `${fn}(${count}).${ext}`;+ else result = `${fn}(${count})`;+ count++;+ }+ return result;+};diff --git a/web/apps/albums/vendor/ente-new/photos/utils/web.ts b/web/apps/albums/vendor/ente-new/photos/utils/web.tsnew file mode 100644index 0000000000..7236cab798--- /dev/null+++ b/web/apps/albums/vendor/ente-new/photos/utils/web.ts@@ -0,0 +1,23 @@+/**+ * Open the given {@link url} in a new browser tab.+ *+ * @param url The URL to open.+ */+export const openURL = (url: string) => {+ const a = document.createElement("a");+ a.href = url;+ a.target = "_blank";+ a.rel = "noopener";+ a.click();+};++/**+ * Open the system configured email client, initiating a new email to the given+ * {@link email} address.+ */+export const initiateEmail = (email: string) => {+ const a = document.createElement("a");+ a.href = "mailto:" + email;+ a.rel = "noopener";+ a.click();+};diff --git a/web/apps/albums/vendor/ente-utils/array.ts b/web/apps/albums/vendor/ente-utils/array.tsnew file mode 100644index 0000000000..dbdc214bb7--- /dev/null+++ b/web/apps/albums/vendor/ente-utils/array.ts@@ -0,0 +1,117 @@+/**+ * Shuffle.+ *+ * Return a new array containing the shuffled elements of the given array.+ *+ * The algorithm used is not the most efficient, but is effectively a one-liner+ * whilst being reasonably efficient. To each element we assign a random key,+ * then we sort by this key. Since the key is random, the sorted array will have+ * the original elements in a random order.+ */+export const shuffled = <T>(xs: T[]): T[] =>+ xs+ .map((x) => [Math.random(), x])+ .sort()+ .map(([, x]) => x) as T[];++/**+ * Return a random sample of {@link n} elements from the given {@link items}.+ *+ * Functionally this is equivalent to `shuffled(items).slice(0, n)`, except it+ * tries to be a bit faster for long arrays when we need only a small sample+ * from it. In a few tests, this indeed makes a substantial difference.+ *+ * If {@link n} is less than the number of {@link items} then a random shuffle+ * of the {@link items} is returned.+ */+export const randomSample = <T>(items: T[], n: number) => {+ if (items.length <= n) return shuffled(items);+ if (n == 0) return [];++ if (n > items.length / 3) {+ // Avoid using the random sampling without replacement method if a+ // significant proportion of the original items are needed, otherwise we+ // might run into long retry loop at the tail end (hitting the same+ // indexes again an again).+ return shuffled(items).slice(0, n);+ }++ const ix = new Set<number>();+ while (ix.size < n) {+ ix.add(Math.floor(Math.random() * items.length));+ }+ return [...ix].map((i) => items[i]!);+};++/**+ * Return the first non-empty string from the given list of strings.+ *+ * This function is needed because the `a ?? b` idiom doesn't do what you'd+ * expect when a is "". Perhaps the behaviour is wrong, perhaps the expectation+ * is wrong; this function papers over the differences.+ *+ * If none of the strings are non-empty, or if there are no strings in the given+ * array, return undefined.+ */+export const firstNonEmpty = (+ ss: (string | undefined)[],+): string | undefined => {+ for (const s of ss) if (s && s.length > 0) return s;+ return undefined;+};++/**+ * Merge the given array of {@link Uint8Array}s in order into a single+ * {@link Uint8Array}.+ *+ * @param as An array of {@link Uint8Array}.+ */+export const mergeUint8Arrays = (as: Uint8Array[]): Uint8Array => {+ // A longer but better performing replacement of+ //+ // new Uint8Array(as.reduce((acc, x) => acc.concat(...x), []))+ //++ const len = as.reduce((len, xs) => len + xs.length, 0);+ const result = new Uint8Array(len);+ as.reduce((n, xs) => (result.set(xs, n), n + xs.length), 0);+ return result;+};++/**+ * Break an array into batches of size {@link chunkSize}.+ *+ * @returns An array of the resultant batches.+ */+export const batch = <T>(xs: T[], batchSize: number): T[][] => {+ const batches: T[][] = [];+ for (let i = 0; i < xs.length; i += batchSize) {+ batches.push(xs.slice(i, i + batchSize));+ }+ return batches;+};++/**+ * Split an array into two arrays - those that satisfy the given+ * {@link predicate}, and those that don't.+ *+ * @param xs The array to split.+ *+ * @param predicate A function invoked for each element, to decide which part of+ * the split it will belong to.+ *+ * @returns A tuple with two arrays. The first of these arrays contains all+ * elements for which the predicate returned `true`, and the second array+ * contains the rest of the elements.+ */+export const splitByPredicate = <T>(+ xs: T[],+ predicate: (t: T) => boolean,+): [T[], T[]] =>+ xs.reduce<[T[], T[]]>(+ (result, x) => {+ (predicate(x) ? result[0] : result[1]).push(x);+ return result;+ },+ [[], []],+ );diff --git a/web/apps/albums/vendor/ente-utils/ensure.ts b/web/apps/albums/vendor/ente-utils/ensure.tsnew file mode 100644index 0000000000..9be5215bf5--- /dev/null+++ b/web/apps/albums/vendor/ente-utils/ensure.ts@@ -0,0 +1,60 @@+/**+ * Throw an exception if the given value {@link v} is false-y.+ *+ * This is a variant of {@link assertionFailed}, except it always throws, not+ * just in dev builds, if the given value is falsey.+ */+export const ensurePrecondition = (v: unknown): void => {+ if (!v) throw new Error("Precondition failed");+};++/**+ * Throw an exception if the given value is `null` or `undefined`.+ *+ * This is different from TypeScript's built in null assertion operator `!` in+ * that `ensure` involves a runtime check, and will throw if the given value is+ * null-ish. On the other hand the TypeScript null assertion is only an+ * indication to the type system and does not involve any runtime checks.+ *+ * However, still it is preferable to use the TypeScript build in null assertion+ * since the stack traces are more informative. The stack trace is not at the+ * point of the assertion, but later at the point of the use, so it is not+ * _directly_ pointing at the issue, but usually it is not hard to backtrace.+ *+ * Still, in rare cases we might want to, well, ensure that a undefined value+ * doesn't sneak into the machinery. So this.+ */+export const ensure = <T>(v: T | null | undefined): T => {+ if (v === null) throw new Error("Required value was null");+ if (v === undefined) throw new Error("Required value was undefined");+ return v;+};++/**+ * Throw an exception if the given value is not a string.+ */+export const ensureString = (v: unknown): string => {+ if (typeof v != "string")+ throw new Error(`Expected a string, instead found ${String(v)}`);+ return v;+};++/**+ * Throw an exception if the given value is not a number or if it is NaN.+ */+export const ensureNumber = (v: unknown): number => {+ if (typeof v != "number" || Number.isNaN(v))+ throw new Error(`Expected a number, instead found ${String(v)}`);+ return v;+};++/**+ * Throw an exception if the given value is not an integral number.+ */+export const ensureInteger = (v: unknown): number => {+ if (typeof v != "number")+ throw new Error(`Expected a number, instead found ${String(v)}`);+ if (!Number.isInteger(v))+ throw new Error(`Expected an integer, instead found ${v}`);+ return v;+};diff --git a/web/apps/albums/vendor/ente-utils/promise.ts b/web/apps/albums/vendor/ente-utils/promise.tsnew file mode 100644index 0000000000..19a0311a7e--- /dev/null+++ b/web/apps/albums/vendor/ente-utils/promise.ts@@ -0,0 +1,157 @@+/**+ * Wait for {@link ms} milliseconds+ *+ * This function is a promisified `setTimeout`. It returns a promise that+ * resolves after {@link ms} milliseconds.+ */+export const wait = (ms: number): Promise<void> =>+ new Promise((resolve) => setTimeout(resolve, ms));++/**+ * Throttle invocations of an underlying function, coalescing pending calls.+ *+ * Take a function that returns a promise, and return a new function that can be+ * called an any number of times while still ensuring that the underlying+ * function is only called a maximum of once per the specified period.+ *+ * The underlying function is immediately called if there were no calls to the+ * throttled function in the last period.+ *+ * Otherwise we start waiting. Multiple calls to the throttled function while+ * we're waiting (either for the original promise to resolve, or after that, for+ * the specified cooldown period to elapse) will all be coalesced into a single+ * call to the underlying function when we're done waiting.+ *+ * ---+ *+ * [Note: Throttle and debounce]+ *+ * There are many throttle/debounce libraries, and ideally I'd have liked to+ * just use one of them instead of reinventing such a basic and finicky wheel.+ * Then why write a bespoke one?+ *+ * - "debounce" means that the underlying function will only be called when a+ * particular wait time has elapsed since the last call to the _debounced_+ * function.+ *+ * - This behaviour, while useful sometimes, is not what we want always. If the+ * debounced function is continuously being called, then the underlying+ * function might never get called (since the wait time does not elapse).+ *+ * - To avoid this starvation, some debounce implementations like lodash provide+ * a "maxWait" option, which tells the debounced function to always call the+ * underlying function if maxWait has elapsed.+ *+ * - The debounced functions can trigger the underlying in two ways: leading+ * (aka immediate) and trailing which control if the underlying should be+ * called at the leading or the trailing edge of the time period.+ *+ * - "throttle" can be conceptually thought of as just maxWait + leading. In+ * fact, this is how lodash actually implements it too. So we could've used+ * lodash, except that is a big dependency to pull for a small function.+ *+ * - Alternatively, pThrottle is a micro-library that provide such a "throttle"+ * primitive. However, its implementation enqueues all incoming requests to+ * the throttled function: it still calls the underlying once per period, but+ * eventually underlying will get called once for each call to the throttled+ * function.+ *+ * - There are circumstances where that would be the appropriate behaviour, but+ * that's not what we want. We wish to trigger an async action, coalescing+ * multiple triggers into a single one, one per period.+ *+ * - Perhaps there are other focused and standard library that'd have what we+ * want, but instead of spending more time searching I just wrote it from+ * scratch for now. Indeed, I've spent more time writing about the function+ * than the function itself.+ */+export const throttled = (+ underlying: () => Promise<void>,+ period: number,+): (() => void) => {+ let pending = 0;++ const f = () => {+ pending += 1;+ if (pending > 1) return;+ void underlying()+ .then(() => wait(period))+ .then(() => {+ const retrigger = pending > 1;+ pending = 0;+ if (retrigger) f();+ });+ };++ return f;+};++/**+ * Await the given {@link promise} for {@link timeoutMS} milliseconds. If it+ * does not resolve within {@link timeoutMS}, then reject with a timeout error.+ *+ * Note that this does not abort {@link promise} itself - it will still get+ * settled, just its eventual state will be ignored if it gets fulfilled or+ * rejected after we've already timed out.+ */+export const withTimeout = async <T>(+ promise: Promise<T>,+ ms: number,+): Promise<T> => {+ let timeoutId: ReturnType<typeof setTimeout>;+ const rejectOnTimeout = new Promise<T>((_, reject) => {+ timeoutId = setTimeout(+ () => reject(new Error("Operation timed out")),+ ms,+ );+ });+ const promiseAndCancelTimeout = async () => {+ const result = await promise;+ clearTimeout(timeoutId);+ return result;+ };+ return Promise.race([promiseAndCancelTimeout(), rejectOnTimeout]);+};++/**+ * A promise queue to serialize execution of bunch of promises.+ *+ * Promises can be added to the queue with the {@link add} function, which+ * returns a new promise that'll settle when the original promise settles.+ *+ * The queue will ensure that promises run sequentially one after the other, in+ * the order which they are added.+ */+export class PromiseQueue<T> {+ private q: { task: () => Promise<T>; handlers: unknown }[] = [];++ /**+ * Add a promise to the queue, and return a new promise that will resolve to+ * the provided promise when it gets a chance to run (after all previous+ * promises in the queue have settled).+ *+ * @param task To avoid starting the promise resolution when adding them,+ * instead of the promise itself, {@link add} takes a function that should+ * return the promise that we wish to await.+ */+ async add(task: () => Promise<T>): Promise<T> {+ let handlers;+ const p = new Promise<T>((...args) => (handlers = args));+ this.q.push({ task, handlers });+ if (this.q.length == 1) this.next();+ return p;+ }++ private next() {+ const item = this.q[0];+ if (!item) return;+ const { task, handlers } = item;+ void task()+ // @ts-expect-error Can't think of an easy way to satisfy tsc.+ .then(...handlers)+ .finally(() => {+ this.q.shift();+ this.next();+ });+ }+}diff --git a/web/apps/albums/vendor/ente-utils/transform.ts b/web/apps/albums/vendor/ente-utils/transform.tsnew file mode 100644index 0000000000..6934f78b25--- /dev/null+++ b/web/apps/albums/vendor/ente-utils/transform.ts@@ -0,0 +1,26 @@+/**+ * Convert `null` to `undefined`, passthrough everything else unchanged.+ */+export const nullToUndefined = <T>(v: T | null | undefined): T | undefined =>+ v === null ? undefined : v;++/**+ * Convert `null` and `undefined` to `false`, passthrough everything else unchanged.+ */+export const nullishToFalse = (v: boolean | null | undefined): boolean =>+ v ?? false;++/**+ * Convert `null` and `undefined` to `0`, passthrough everything else unchanged.+ */+export const nullishToZero = (v: number | null | undefined): number => v ?? 0;++/**+ * Convert `null` and `undefined` to "" (blank string), passthrough everything else unchanged.+ */+export const nullishToBlank = (v: string | null | undefined): string => v ?? "";++/**+ * Convert `null` and `undefined` to `[]`, passthrough everything else unchanged.+ */+export const nullishToEmpty = <T>(v: T[] | null | undefined): T[] => v ?? [];diff --git a/web/apps/albums/vendor/ente-utils/type-guards.ts b/web/apps/albums/vendor/ente-utils/type-guards.tsnew file mode 100644index 0000000000..1309a5bea4--- /dev/null+++ b/web/apps/albums/vendor/ente-utils/type-guards.ts@@ -0,0 +1,15 @@+/**+ * A variant of Array.includes that allows us to use it as a type guard.+ *+ * It allows us to narrow the type of an arbitrary T to U if it is one of U[].+ *+ * TypeScript currently doesn't allow us to use the standard Array.includes as a+ * type guard for checking if an arbitrary string is one of the known set of+ * values. This issue and this workaround is mentioned here:+ * - https://github.com/microsoft/TypeScript/issues/48247+ * - https://github.com/microsoft/TypeScript/issues/26255#issuecomment-502899689+ */+export function includes<T, U extends T>(us: readonly U[], t: T): t is U {+ // @ts-expect-error @typescript-eslint/no-unsafe-argument+ return us.includes(t);+}diff --git a/web/apps/albums/vendor/photos/components/ActiveDownloadStatusNotifications.tsx b/web/apps/albums/vendor/photos/components/ActiveDownloadStatusNotifications.tsxnew file mode 100644index 0000000000..78daab7ee0--- /dev/null+++ b/web/apps/albums/vendor/photos/components/ActiveDownloadStatusNotifications.tsx@@ -0,0 +1,22 @@+import { useSaveGroups } from "ente-gallery/components/utils/save-groups";+import { type ComponentProps } from "react";+import { DownloadStatusNotifications } from "./DownloadStatusNotifications";++type ActiveDownloadStatusNotificationsProps = Omit<+ ComponentProps<typeof DownloadStatusNotifications>,+ "saveGroups" | "onRemoveSaveGroup"+>;++export const ActiveDownloadStatusNotifications: React.FC<+ ActiveDownloadStatusNotificationsProps+> = (props) => {+ const { saveGroups, onRemoveSaveGroup } = useSaveGroups();++ return (+ <DownloadStatusNotifications+ saveGroups={saveGroups}+ onRemoveSaveGroup={onRemoveSaveGroup}+ {...props}+ />+ );+};diff --git a/web/apps/albums/vendor/photos/components/Avatar.tsx b/web/apps/albums/vendor/photos/components/Avatar.tsxnew file mode 100644index 0000000000..05feac15bf--- /dev/null+++ b/web/apps/albums/vendor/photos/components/Avatar.tsx@@ -0,0 +1,117 @@+// TODO: Audit this file+/* eslint-disable react-hooks/exhaustive-deps */+import { styled } from "@mui/material";+import type { LocalUser } from "ente-accounts/services/user";+import log from "ente-base/log";+import { type EnteFile } from "ente-media/file";+import {+ avatarBackgroundColor,+ avatarBackgroundColorPublicCollectedFile,+ avatarTextColor,+} from "ente-new/photos/services/avatar";+import React, { useLayoutEffect, useState } from "react";++interface AvatarProps {+ user?: LocalUser;+ file?: EnteFile;+ email?: string;+ opacity?: number;+ emailByUserID?: Map<number, string>;+}++const AvatarBase = styled("div")<{+ colorCode: string;+ size: number;+ opacity: number | undefined;+}>`+ width: ${({ size }) => `${size}px`};+ height: ${({ size }) => `${size}px`};+ background-color: ${({ colorCode, opacity }) =>+ `${colorCode}${opacity === 100 ? "" : (opacity ?? 95)}`};+ border-radius: 50%;+ display: flex;+ justify-content: center;+ align-items: center;+ color: ${avatarTextColor};+ font-weight: bold;+ font-size: ${({ size }) => `${Math.floor(size / 2)}px`};+`;++const Avatar: React.FC<AvatarProps> = ({+ user,+ file,+ email,+ opacity,+ emailByUserID,+}) => {+ const [colorCode, setColorCode] = useState("");+ const [userLetter, setUserLetter] = useState<string | undefined>("");++ useLayoutEffect(() => {+ try {+ if (!file) {+ return;+ }+ if (file.ownerID !== user?.id) {+ // getting email from in-memory id-email map+ const email = emailByUserID?.get(file.ownerID);+ if (!email) {+ log.error("email not found in userIDToEmailMap");+ return;+ }+ setUserLetter(email[0]?.toUpperCase());+ setColorCode(avatarBackgroundColor(file.ownerID));+ } else if (file.ownerID === user.id) {+ const uploaderName = file.pubMagicMetadata?.data.uploaderName;+ if (!uploaderName) {+ log.error(+ "uploaderName not found in file.pubMagicMetadata.data",+ );+ return;+ }+ setUserLetter(uploaderName[0]?.toUpperCase());+ setColorCode(avatarBackgroundColorPublicCollectedFile);+ }+ } catch (e) {+ log.error("AvatarIcon.tsx - useLayoutEffect file failed", e);+ }+ }, [file]);++ useLayoutEffect(() => {+ try {+ if (!email) {+ return;+ }++ if (user?.email === email) {+ setUserLetter(email[0]?.toUpperCase());+ setColorCode(avatarBackgroundColorPublicCollectedFile);+ return;+ }++ const id = Array.from(emailByUserID?.keys() ?? []).find(+ (key) => emailByUserID?.get(key) === email,+ );+ if (!id) {+ log.error(`ID not found for email: ${email}`);+ return;+ }+ setUserLetter(email[0]?.toUpperCase());+ setColorCode(avatarBackgroundColor(id));+ } catch (e) {+ log.error("AvatarIcon.tsx - useLayoutEffect email failed", e);+ }+ }, [user, email, emailByUserID]);++ if (!colorCode || !userLetter) {+ return <></>;+ }++ return (+ <AvatarBase size={18} colorCode={colorCode} opacity={opacity}>+ {userLetter}+ </AvatarBase>+ );+};++export default Avatar;diff --git a/web/apps/albums/vendor/photos/components/CanvasReadbackBlockedDialog.tsx b/web/apps/albums/vendor/photos/components/CanvasReadbackBlockedDialog.tsxnew file mode 100644index 0000000000..6a99a5e97d--- /dev/null+++ b/web/apps/albums/vendor/photos/components/CanvasReadbackBlockedDialog.tsx@@ -0,0 +1,161 @@+import CloseIcon from "@mui/icons-material/Close";+import ErrorOutlineRoundedIcon from "@mui/icons-material/ErrorOutlineRounded";+import {+ Box,+ Dialog,+ IconButton,+ Link,+ styled,+ Typography,+ type DialogProps,+} from "@mui/material";+import { type ModalVisibilityProps } from "ente-base/components/utils/modal";+import { t } from "i18next";+import React from "react";++export type CanvasReadbackBlockedDialogProps = ModalVisibilityProps;++export const CanvasReadbackBlockedDialog: React.FC<+ CanvasReadbackBlockedDialogProps+> = ({ open, onClose }) => (+ <StyledDialog open={open} onClose={onClose}>+ <DialogWrapper>+ <CloseButton onClick={onClose}>+ <CloseIcon sx={{ fontSize: 20 }} />+ </CloseButton>+ <ContentContainer>+ <IllustrationWrapper>+ <ErrorIconContainer>+ <ErrorOutlineRoundedIcon sx={{ fontSize: 48 }} />+ </ErrorIconContainer>+ </IllustrationWrapper>++ <TitleSection>+ <Title>{t("thumbnail_generation_failed")}</Title>+ <Subtitle>+ {t("canvas_blocked_upload_description")}{" "}+ <HelpLink+ href="https://ente.io/help/photos/faq/troubleshooting#thumbnails"+ target="_blank"+ rel="noopener noreferrer"+ >+ {t("learn_how")}+ </HelpLink>+ .+ </Subtitle>+ </TitleSection>+ </ContentContainer>+ </DialogWrapper>+ </StyledDialog>+);++const StyledDialog = styled(Dialog)<DialogProps>(({ theme }) => ({+ "& .MuiDialog-paper": {+ width: 381,+ maxWidth: "calc(100% - 32px)",+ borderRadius: 28,+ backgroundColor: "#fff",+ padding: 0,+ margin: 16,+ overflow: "visible",+ boxShadow: "none",+ border: "1px solid #E0E0E0",+ ...theme.applyStyles("dark", {+ backgroundColor: "#1b1b1b",+ border: "1px solid rgba(255, 255, 255, 0.18)",+ }),+ },+ "& .MuiBackdrop-root": { backgroundColor: "rgba(0, 0, 0, 0.5)" },+}));++const DialogWrapper = styled(Box)(() => ({+ position: "relative",+ padding: "48px 16px 16px 16px",+}));++const CloseButton = styled(IconButton)(({ theme }) => ({+ position: "absolute",+ top: 11,+ right: 12,+ backgroundColor: "#FAFAFA",+ color: "#000",+ padding: 10,+ "&:hover": { backgroundColor: "#F0F0F0" },+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.12)",+ color: "#fff",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.16)" },+ }),+}));++const ContentContainer = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 16,+}));++const IllustrationWrapper = styled(Box)(() => ({+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ marginBottom: 8,+}));++const ErrorIconContainer = styled(Box)(({ theme }) => ({+ width: 92,+ height: 92,+ borderRadius: 56,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ backgroundColor: "rgba(229, 57, 53, 0.12)",+ color: "#E53935",+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 138, 128, 0.15)",+ color: "#FF8A80",+ }),+}));++const TitleSection = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 9,+ width: "100%",+ textAlign: "center",+ marginBottom: 16,+}));++const Title = styled(Typography)(({ theme }) => ({+ fontWeight: 600,+ fontSize: 24,+ lineHeight: "28px",+ letterSpacing: "-0.48px",+ color: "#000",+ ...theme.applyStyles("dark", { color: "#fff" }),+}));++const Subtitle = styled(Typography)(({ theme }) => ({+ fontWeight: 500,+ fontSize: 14,+ lineHeight: "20px",+ color: "#666666",+ width: "100%",+ padding: "0 8px",+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.7)" }),+}));++const HelpLink = styled(Link)(({ theme }) => ({+ fontWeight: "inherit",+ fontSize: 14,+ lineHeight: "20px",+ color: "#08C225",+ textDecorationColor: "#08C225",+ "&:hover": { color: "#07A820", textDecorationColor: "#07A820" },+ ...theme.applyStyles("dark", {+ color: "#22D840",+ textDecorationColor: "#22D840",+ "&:hover": { color: "#4BE066", textDecorationColor: "#4BE066" },+ }),+}));diff --git a/web/apps/albums/vendor/photos/components/Collections/CollectionHeader.tsx b/web/apps/albums/vendor/photos/components/Collections/CollectionHeader.tsxnew file mode 100644index 0000000000..70a8c7e7f1--- /dev/null+++ b/web/apps/albums/vendor/photos/components/Collections/CollectionHeader.tsx@@ -0,0 +1,1211 @@+import {+ CleanIcon,+ Delete02Icon,+ ModernTvIcon,+ RemoveCircleIcon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import ArchiveOutlinedIcon from "@mui/icons-material/ArchiveOutlined";+import CheckIcon from "@mui/icons-material/Check";+import DeleteOutlinedIcon from "@mui/icons-material/DeleteOutlined";+import EditIcon from "@mui/icons-material/Edit";+import ImageOutlinedIcon from "@mui/icons-material/ImageOutlined";+import LinkIcon from "@mui/icons-material/Link";+import LogoutIcon from "@mui/icons-material/Logout";+import MapOutlinedIcon from "@mui/icons-material/MapOutlined";+import MoreHorizIcon from "@mui/icons-material/MoreHoriz";+import PublicIcon from "@mui/icons-material/Public";+import PushPinIcon from "@mui/icons-material/PushPin";+import PushPinOutlinedIcon from "@mui/icons-material/PushPinOutlined";+import SortIcon from "@mui/icons-material/Sort";+import TvIcon from "@mui/icons-material/Tv";+import UnarchiveIcon from "@mui/icons-material/Unarchive";+import VisibilityOffOutlinedIcon from "@mui/icons-material/VisibilityOffOutlined";+import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";+import { Box, IconButton, Menu, Stack, Tooltip } from "@mui/material";+import { SpacedRow } from "ente-base/components/containers";+import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";+import {+ OverflowMenu,+ OverflowMenuOption,+} from "ente-base/components/OverflowMenu";+import { SingleInputDialog } from "ente-base/components/SingleInputDialog";+import { useModalVisibility } from "ente-base/components/utils/modal";+import { useBaseContext } from "ente-base/context";+import type { AddSaveGroup } from "ente-gallery/components/utils/save-groups";+import { downloadAndSaveCollectionFiles } from "ente-gallery/services/save";+import { uniqueFilesByID } from "ente-gallery/utils/file";+import {+ CollectionOrder,+ CollectionSubType,+ type Collection,+} from "ente-media/collection";+import { ItemVisibility } from "ente-media/file-metadata";+import type { RemotePullOpts } from "ente-new/photos/components/gallery";+import {+ GalleryItemsHeaderAdapter,+ GalleryItemsSummary,+} from "ente-new/photos/components/gallery/ListHeader";+import { StarIcon } from "ente-new/photos/components/icons/StarIcon";+import { useSettingsSnapshot } from "ente-new/photos/components/utils/use-snapshot";+import {+ cleanUncategorized,+ defaultHiddenCollectionUserFacingName,+ deleteCollection,+ deleteShareURL,+ findDefaultHiddenCollectionIDs,+ isHiddenCollection,+ leaveSharedCollection,+ renameCollection,+ updateCollectionOrder,+ updateCollectionSortOrder,+ updateCollectionVisibility,+ updateShareeCollectionOrder,+} from "ente-new/photos/services/collection";+import {+ PseudoCollectionID,+ type CollectionSummary,+ type CollectionSummaryType,+} from "ente-new/photos/services/collection-summary";+import {+ savedCollectionFiles,+ savedCollections,+} from "ente-new/photos/services/photos-fdb";+import { updateMapEnabled } from "ente-new/photos/services/settings";+import { emptyTrash } from "ente-new/photos/services/trash";+import { usePhotosAppContext } from "ente-new/photos/types/context";+import { t } from "i18next";+import React, { useCallback, useRef } from "react";+import { Trans } from "react-i18next";+import type { FileListWithViewerProps } from "../FileListWithViewer";+import { CollectionMapDialog } from "./CollectionMapDialog";++export interface CollectionHeaderProps+ extends Pick<+ FileListWithViewerProps,+ | "onMarkTempDeleted"+ | "onAddFileToCollection"+ | "onRemoteFilesPull"+ | "onVisualFeedback"+ | "fileNormalCollectionIDs"+ | "collectionNameByID"+ | "onSelectCollection"+ | "onSelectPerson"+ > {+ collectionSummary: CollectionSummary;+ activeCollection: Collection | undefined;+ setActiveCollectionID: (collectionID: number) => void;+ isActiveCollectionDownloadInProgress: () => boolean;+ /**+ * Called when an operation (e.g. renaming a collection) completes and wants+ * to perform a full remote pull.+ */+ onRemotePull: (opts?: RemotePullOpts) => Promise<void>;+ onCollectionShare: () => void;+ onCollectionManageLink: () => void;+ onCollectionCast: () => void;+ canSetAlbumCover: boolean;+ onSetAlbumCover: () => 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;+}++/**+ * A header shown at the top of the list of photos in the gallery, when the+ * gallery is showing a collection.+ */+export const CollectionHeader: React.FC<CollectionHeaderProps> = (props) => {+ const { collectionSummary } = props;++ const { name, type, attributes, fileCount } = collectionSummary;++ const EndIcon = () => {+ if (attributes.has("archived")) return <ArchiveOutlinedIcon />;+ if (attributes.has("sharedOnlyViaLink")) return <LinkIcon />;+ if (attributes.has("shared"))+ return (+ <Box sx={{ mt: "-1px" }}>+ <SmallShareIcon />+ </Box>+ );+ if (attributes.has("userFavorites"))+ return <StarIcon fontSize="small" />;+ return <></>;+ };++ return (+ <GalleryItemsHeaderAdapter>+ <SpacedRow>+ <GalleryItemsSummary+ name={name}+ fileCount={fileCount}+ endIcon={<EndIcon />}+ />+ {shouldShowOptions(type) && (+ <CollectionHeaderOptions {...props} />+ )}+ </SpacedRow>+ </GalleryItemsHeaderAdapter>+ );+};++const shouldShowOptions = (type: CollectionSummaryType) =>+ type != "all" && type != "archiveItems";++const CollectionHeaderOptions: React.FC<CollectionHeaderProps> = ({+ activeCollection,+ collectionSummary,+ setActiveCollectionID,+ onRemotePull,+ onCollectionShare,+ onCollectionManageLink,+ onCollectionCast,+ canSetAlbumCover,+ onSetAlbumCover,+ onAddSaveGroup,+ isActiveCollectionDownloadInProgress,+ onMarkTempDeleted,+ onAddFileToCollection,+ onRemoteFilesPull,+ onVisualFeedback,+ fileNormalCollectionIDs,+ collectionNameByID,+ onSelectCollection,+ onSelectPerson,+}) => {+ const { showMiniDialog, onGenericError } = useBaseContext();+ const { showLoadingBar, hideLoadingBar, showNotification } =+ usePhotosAppContext();+ const { mapEnabled } = useSettingsSnapshot();+ const overflowMenuIconRef = useRef<SVGSVGElement | null>(null);++ const { show: showSortOrderMenu, props: sortOrderMenuVisibilityProps } =+ useModalVisibility();+ const { show: showAlbumNameInput, props: albumNameInputVisibilityProps } =+ useModalVisibility();+ const { show: showMapDialog, props: mapDialogVisibilityProps } =+ useModalVisibility();++ const { type: collectionSummaryType, fileCount } = collectionSummary;+ const isQuickLinkAlbum =+ activeCollection?.magicMetadata?.data.subType ==+ CollectionSubType.quicklink;++ /**+ * Return a new function by wrapping an async function in an error handler,+ * showing the global loading bar when the function runs, and syncing with+ * remote on completion.+ */+ const wrap = useCallback(+ (f: () => Promise<void>) => {+ const wrapped = async () => {+ showLoadingBar();+ try {+ await f();+ } catch (e) {+ onGenericError(e);+ } finally {+ void onRemotePull({ silent: true });+ hideLoadingBar();+ }+ };+ return (): void => void wrapped();+ },+ [showLoadingBar, hideLoadingBar, onGenericError, onRemotePull],+ );++ const handleRenameCollection = useCallback(+ async (newName: string) => {+ if (!activeCollection) return;+ if (activeCollection.name !== newName) {+ await renameCollection(activeCollection, newName);+ void onRemotePull({ silent: true });+ }+ },+ [activeCollection, onRemotePull],+ );++ const hasAlbumFiles = fileCount > 0;++ const confirmDeleteCollection = () => {+ if (hasAlbumFiles) {+ showMiniDialog({+ title: t("delete_album_title"),+ message: (+ <Trans+ i18nKey={"delete_album_message"}+ components={{+ a: (+ <Box+ component={"span"}+ sx={{ color: "text.base" }}+ />+ ),+ }}+ />+ ),+ continue: {+ text: t("keep_photos"),+ color: "primary",+ action: deleteCollectionButKeepFiles,+ },+ secondary: {+ text: t("delete_photos"),+ color: "critical",+ action: deleteCollectionAlongWithFiles,+ },+ });+ return;+ }++ showMiniDialog({+ title: t("delete_album_title"),+ message: (+ <Trans+ i18nKey={"delete_album_message_no_photos"}+ components={{+ a: (+ <Box+ component={"span"}+ sx={{ color: "text.base" }}+ />+ ),+ }}+ />+ ),+ continue: {+ text: t("delete_album"),+ color: "critical",+ action: deleteCollectionAlongWithFiles,+ },+ });+ };++ const deleteCollectionAlongWithFiles = wrap(async () => {+ if (!activeCollection) return;+ await deleteCollection(activeCollection.id);+ setActiveCollectionID(PseudoCollectionID.all);+ });++ const deleteCollectionButKeepFiles = wrap(async () => {+ if (!activeCollection) return;+ await deleteCollection(activeCollection.id, { keepFiles: true });+ setActiveCollectionID(PseudoCollectionID.all);+ });++ const confirmEmptyTrash = () =>+ showMiniDialog({+ title: t("empty_trash_title"),+ message: t("empty_trash_message"),+ continue: {+ text: t("empty_trash"),+ color: "critical",+ action: doEmptyTrash,+ },+ });++ const doEmptyTrash = wrap(async () => {+ await emptyTrash();+ setActiveCollectionID(PseudoCollectionID.all);+ });++ const confirmCleanUncategorized = () =>+ showMiniDialog({+ title: t("clean_uncategorized"),+ message: t("clean_uncategorized_message"),+ continue: {+ text: t("clean_uncategorized"),+ color: "primary",+ action: doCleanUncategorized,+ },+ });++ const doCleanUncategorized = wrap(async () => {+ if (!activeCollection) return;+ const count = await cleanUncategorized(activeCollection);+ showNotification({+ color: "secondary",+ title: t("clean_uncategorized_success", { count }),+ });+ });++ const _downloadCollection = async () => {+ if (isActiveCollectionDownloadInProgress()) return;++ if (collectionSummaryType == "hiddenItems") {+ const defaultHiddenCollectionsIDs = findDefaultHiddenCollectionIDs(+ await savedCollections(),+ );+ const collectionFiles = await savedCollectionFiles();+ const defaultHiddenCollectionFiles = uniqueFilesByID(+ collectionFiles.filter((file) =>+ defaultHiddenCollectionsIDs.has(file.collectionID),+ ),+ );+ await downloadAndSaveCollectionFiles(+ defaultHiddenCollectionUserFacingName,+ PseudoCollectionID.hiddenItems,+ defaultHiddenCollectionFiles,+ true,+ onAddSaveGroup,+ );+ } else if (activeCollection) {+ await downloadAndSaveCollectionFiles(+ activeCollection.name,+ activeCollection.id,+ (await savedCollectionFiles()).filter(+ (file) => file.collectionID == activeCollection.id,+ ),+ isHiddenCollection(activeCollection),+ onAddSaveGroup,+ );+ }+ };++ const downloadCollection = () =>+ void _downloadCollection().catch(onGenericError);++ const archiveAlbum = wrap(async () => {+ if (!activeCollection) return;+ await updateCollectionVisibility(+ activeCollection,+ ItemVisibility.archived,+ );+ });++ const unarchiveAlbum = wrap(async () => {+ if (!activeCollection) return;+ await updateCollectionVisibility(+ activeCollection,+ ItemVisibility.visible,+ );+ });++ const confirmLeaveSharedAlbum = () =>+ showMiniDialog({+ title: t("leave_shared_album_title"),+ message: t("leave_shared_album_message"),+ continue: {+ text: t("leave_shared_album"),+ color: "critical",+ action: leaveSharedAlbum,+ },+ });++ const leaveSharedAlbum = wrap(async () => {+ if (!activeCollection) return;+ await leaveSharedCollection(activeCollection.id);+ setActiveCollectionID(PseudoCollectionID.all);+ });++ const pinAlbum = wrap(async () => {+ if (!activeCollection) return;+ await updateCollectionOrder(activeCollection, CollectionOrder.pinned);+ });++ const unpinAlbum = wrap(async () => {+ if (!activeCollection) return;+ await updateCollectionOrder(activeCollection, CollectionOrder.default);+ });++ const pinSharedAlbum = wrap(async () => {+ if (!activeCollection) return;+ await updateShareeCollectionOrder(+ activeCollection,+ CollectionOrder.pinned,+ );+ });++ const unpinSharedAlbum = wrap(async () => {+ if (!activeCollection) return;+ await updateShareeCollectionOrder(+ activeCollection,+ CollectionOrder.default,+ );+ });++ const hideAlbum = wrap(async () => {+ if (!activeCollection) return;+ await updateCollectionVisibility(+ activeCollection,+ ItemVisibility.hidden,+ );+ setActiveCollectionID(PseudoCollectionID.all);+ });++ const unhideAlbum = wrap(async () => {+ if (!activeCollection) return;+ await updateCollectionVisibility(+ activeCollection,+ ItemVisibility.visible,+ );+ setActiveCollectionID(PseudoCollectionID.hiddenItems);+ });++ const removeQuickLink = wrap(async () => {+ if (!activeCollection) return;++ if (isQuickLinkAlbum && activeCollection.sharees.length === 0) {+ await deleteCollection(activeCollection.id, { keepFiles: true });+ setActiveCollectionID(PseudoCollectionID.all);+ return;+ }++ await deleteShareURL(activeCollection.id);+ });++ const changeSortOrderAsc = wrap(async () => {+ if (!activeCollection) return;+ await updateCollectionSortOrder(activeCollection, true);+ });++ const changeSortOrderDesc = wrap(async () => {+ if (!activeCollection) return;+ await updateCollectionSortOrder(activeCollection, false);+ });++ const handleShowMap = useCallback(async () => {+ if (!mapEnabled) {+ try {+ await updateMapEnabled(true);+ } catch (e) {+ onGenericError(e);+ return;+ }+ }+ showMapDialog();+ }, [mapEnabled, onGenericError, showMapDialog]);++ let menuOptions: React.ReactNode[] = [];+ // MUI doesn't let us use fragments to pass multiple menu items, so we need+ // to instead put them in an array. This also necessitates giving each a+ // unique key.+ switch (collectionSummaryType) {+ case "trash":+ menuOptions = fileCount+ ? [<EmptyTrashOption key="trash" onClick={confirmEmptyTrash} />]+ : [];+ break;++ case "userFavorites":+ menuOptions = [];+ break;++ case "uncategorized":+ // Quick options (download + clean) are shown instead of a menu+ break;++ case "hiddenItems":+ menuOptions = [+ fileCount && (+ <DownloadOption+ key="download-hidden"+ onClick={downloadCollection}+ >+ {t("download_hidden_items")}+ </DownloadOption>+ ),+ ];+ break;++ case "sharedIncoming":+ menuOptions = [+ shouldShowMapOption(collectionSummary) && (+ <OverflowMenuOption+ key="map"+ onClick={handleShowMap}+ startIcon={<MapOutlinedIcon />}+ >+ {t("map")}+ </OverflowMenuOption>+ ),+ // Pin/Unpin for shared incoming collections+ collectionSummary.attributes.has("shareePinned") ? (+ <OverflowMenuOption+ key="unpin"+ onClick={unpinSharedAlbum}+ startIcon={<PushPinOutlinedIcon />}+ >+ {t("unpin_album")}+ </OverflowMenuOption>+ ) : (+ <OverflowMenuOption+ key="pin"+ onClick={pinSharedAlbum}+ startIcon={<PushPinIcon />}+ >+ {t("pin_album")}+ </OverflowMenuOption>+ ),+ collectionSummary.attributes.has("archived") ? (+ <OverflowMenuOption+ key="unarchive"+ onClick={unarchiveAlbum}+ startIcon={<UnarchiveIcon />}+ >+ {t("unarchive_album")}+ </OverflowMenuOption>+ ) : (+ <OverflowMenuOption+ key="archive"+ onClick={archiveAlbum}+ startIcon={<ArchiveOutlinedIcon />}+ >+ {t("archive_album")}+ </OverflowMenuOption>+ ),++ activeCollection ? (+ isHiddenCollection(activeCollection) ? (+ <OverflowMenuOption+ key="unhide"+ onClick={unhideAlbum}+ startIcon={<VisibilityOutlinedIcon />}+ >+ {t("unhide_collection")}+ </OverflowMenuOption>+ ) : (+ <OverflowMenuOption+ key="hide"+ onClick={hideAlbum}+ startIcon={<VisibilityOffOutlinedIcon />}+ >+ {t("hide_collection")}+ </OverflowMenuOption>+ )+ ) : undefined,+ <OverflowMenuOption+ key="leave"+ startIcon={<LogoutIcon />}+ onClick={confirmLeaveSharedAlbum}+ >+ {t("leave_album")}+ </OverflowMenuOption>,+ <OverflowMenuOption+ key="cast"+ startIcon={<TvIcon />}+ onClick={onCollectionCast}+ >+ {t("cast_album_to_tv")}+ </OverflowMenuOption>,+ ];+ break;++ default:+ if (isQuickLinkAlbum) {+ menuOptions = [+ shouldShowMapOption(collectionSummary) && (+ <OverflowMenuOption+ key="map"+ onClick={handleShowMap}+ startIcon={<MapOutlinedIcon />}+ >+ {t("map")}+ </OverflowMenuOption>+ ),+ <OverflowMenuOption+ key="sort"+ onClick={showSortOrderMenu}+ startIcon={<SortIcon />}+ >+ {t("sort_by")}+ </OverflowMenuOption>,+ <OverflowMenuOption+ key="cast"+ startIcon={<TvIcon />}+ onClick={onCollectionCast}+ >+ {t("cast_album_to_tv")}+ </OverflowMenuOption>,+ <OverflowMenuOption+ key="remove-link"+ onClick={removeQuickLink}+ startIcon={+ <HugeiconsIcon+ icon={RemoveCircleIcon}+ size={20}+ strokeWidth={1.5}+ />+ }+ >+ {t("remove_link")}+ </OverflowMenuOption>,+ ];+ break;+ }+ menuOptions = [+ <OverflowMenuOption+ key="rename"+ onClick={showAlbumNameInput}+ startIcon={<EditIcon />}+ >+ {t("rename_album")}+ </OverflowMenuOption>,+ canSetAlbumCover && (+ <OverflowMenuOption+ key="set-cover"+ onClick={onSetAlbumCover}+ startIcon={<ImageOutlinedIcon />}+ >+ {t("set_cover")}+ </OverflowMenuOption>+ ),+ <OverflowMenuOption+ key="sort"+ onClick={showSortOrderMenu}+ startIcon={<SortIcon />}+ >+ {t("sort_by")}+ </OverflowMenuOption>,+ shouldShowMapOption(collectionSummary) && (+ <OverflowMenuOption+ key="map"+ onClick={handleShowMap}+ startIcon={<MapOutlinedIcon />}+ >+ {t("map")}+ </OverflowMenuOption>+ ),+ collectionSummary.attributes.has("pinned") ? (+ <OverflowMenuOption+ key="unpin"+ onClick={unpinAlbum}+ startIcon={<PushPinOutlinedIcon />}+ >+ {t("unpin_album")}+ </OverflowMenuOption>+ ) : (+ <OverflowMenuOption+ key="pin"+ onClick={pinAlbum}+ startIcon={<PushPinIcon />}+ >+ {t("pin_album")}+ </OverflowMenuOption>+ ),+ ...(!activeCollection || !isHiddenCollection(activeCollection)+ ? [+ collectionSummary.attributes.has("archived") ? (+ <OverflowMenuOption+ key="unarchive"+ onClick={unarchiveAlbum}+ startIcon={<UnarchiveIcon />}+ >+ {t("unarchive_album")}+ </OverflowMenuOption>+ ) : (+ <OverflowMenuOption+ key="archive"+ onClick={archiveAlbum}+ startIcon={<ArchiveOutlinedIcon />}+ >+ {t("archive_album")}+ </OverflowMenuOption>+ ),+ ]+ : []),+ activeCollection && isHiddenCollection(activeCollection) ? (+ <OverflowMenuOption+ key="unhide"+ onClick={unhideAlbum}+ startIcon={<VisibilityOutlinedIcon />}+ >+ {t("unhide_collection")}+ </OverflowMenuOption>+ ) : (+ <OverflowMenuOption+ key="hide"+ onClick={hideAlbum}+ startIcon={<VisibilityOffOutlinedIcon />}+ >+ {t("hide_collection")}+ </OverflowMenuOption>+ ),+ <OverflowMenuOption+ key="delete"+ startIcon={<DeleteOutlinedIcon />}+ onClick={confirmDeleteCollection}+ >+ {t("delete_album")}+ </OverflowMenuOption>,+ <OverflowMenuOption+ key="share"+ onClick={onCollectionShare}+ startIcon={<ShareIcon />}+ >+ {t("share_album")}+ </OverflowMenuOption>,+ <OverflowMenuOption+ key="cast"+ startIcon={<TvIcon />}+ onClick={onCollectionCast}+ >+ {t("cast_album_to_tv")}+ </OverflowMenuOption>,+ ];+ break;+ }++ const validMenuOptions = menuOptions.filter((o) => !!o);++ return (+ <Box sx={{ display: "inline-flex", gap: "16px" }}>+ <QuickOptions+ collectionSummary={collectionSummary}+ isQuickLinkAlbum={!!isQuickLinkAlbum}+ isDownloadInProgress={isActiveCollectionDownloadInProgress}+ onMapClick={handleShowMap}+ onEmptyTrashClick={confirmEmptyTrash}+ onDownloadClick={downloadCollection}+ onShareClick={+ isQuickLinkAlbum+ ? onCollectionManageLink+ : onCollectionShare+ }+ onCastClick={onCollectionCast}+ onCleanUncategorizedClick={confirmCleanUncategorized}+ />+ {validMenuOptions.length > 0 && (+ <OverflowMenu+ ariaID="collection-options"+ triggerButtonIcon={+ <MoreHorizIcon ref={overflowMenuIconRef} />+ }+ >+ {validMenuOptions}+ </OverflowMenu>+ )}+ <CollectionSortOrderMenu+ {...sortOrderMenuVisibilityProps}+ overflowMenuIconRef={overflowMenuIconRef}+ sortAsc={activeCollection?.pubMagicMetadata?.data.asc ?? false}+ onAscClick={changeSortOrderAsc}+ onDescClick={changeSortOrderDesc}+ />+ <CollectionMapDialog+ {...mapDialogVisibilityProps}+ collectionSummary={collectionSummary}+ activeCollection={activeCollection}+ onRemotePull={onRemotePull}+ onAddSaveGroup={onAddSaveGroup}+ onMarkTempDeleted={onMarkTempDeleted}+ onAddFileToCollection={onAddFileToCollection}+ onRemoteFilesPull={onRemoteFilesPull}+ onVisualFeedback={onVisualFeedback}+ fileNormalCollectionIDs={fileNormalCollectionIDs}+ collectionNameByID={collectionNameByID}+ onSelectCollection={onSelectCollection}+ onSelectPerson={onSelectPerson}+ />+ <SingleInputDialog+ {...albumNameInputVisibilityProps}+ title={t("rename_album")}+ label={t("album_name")}+ initialValue={activeCollection?.name}+ submitButtonColor="primary"+ submitButtonTitle={t("rename")}+ onSubmit={handleRenameCollection}+ />+ </Box>+ );+};++/** Props for a generic option. */+interface OptionProps {+ onClick: () => void;+}++interface QuickOptionsProps {+ collectionSummary: CollectionSummary;+ isQuickLinkAlbum: boolean;+ isDownloadInProgress: () => boolean;+ onMapClick: () => void;+ onEmptyTrashClick: () => void;+ onDownloadClick: () => void;+ onShareClick: () => void;+ onCastClick: () => void;+ onCleanUncategorizedClick: () => void;+}++const QuickOptions: React.FC<QuickOptionsProps> = ({+ onMapClick,+ onEmptyTrashClick,+ onDownloadClick,+ onShareClick,+ onCastClick,+ onCleanUncategorizedClick,+ collectionSummary,+ isQuickLinkAlbum,+ isDownloadInProgress,+}) => (+ <Stack direction="row" sx={{ alignItems: "center", gap: "16px" }}>+ {showEmptyTrashQuickOption(collectionSummary) && (+ <EmptyTrashQuickOption onClick={onEmptyTrashClick} />+ )}+ {showDownloadQuickOption(collectionSummary) &&+ collectionSummary.fileCount > 0 &&+ (isDownloadInProgress() ? (+ <ActivityIndicator size="20px" sx={{ m: "12px" }} />+ ) : (+ <DownloadQuickOption+ collectionSummary={collectionSummary}+ onClick={onDownloadClick}+ />+ ))}+ {showCleanUncategorizedQuickOption(collectionSummary) && (+ <CleanUncategorizedQuickOption+ onClick={onCleanUncategorizedClick}+ />+ )}+ {showMapQuickOption(collectionSummary) && (+ <MapQuickOption onClick={onMapClick} />+ )}+ {showShareQuickOption(collectionSummary) && (+ <ShareQuickOption+ collectionSummary={collectionSummary}+ isQuickLinkAlbum={isQuickLinkAlbum}+ onClick={onShareClick}+ />+ )}+ {showCastQuickOption(collectionSummary) && (+ <CastQuickOption onClick={onCastClick} />+ )}+ </Stack>+);++const showEmptyTrashQuickOption = ({ type, fileCount }: CollectionSummary) =>+ type == "trash" && fileCount > 0;++const EmptyTrashQuickOption: React.FC<OptionProps> = ({ onClick }) => (+ <Tooltip title={t("empty_trash")}>+ <IconButton onClick={onClick}>+ <HugeiconsIcon icon={Delete02Icon} size={22} strokeWidth={1.5} />+ </IconButton>+ </Tooltip>+);++const showCleanUncategorizedQuickOption = ({+ type,+ fileCount,+}: CollectionSummary) => type == "uncategorized" && fileCount > 0;++const CleanUncategorizedQuickOption: React.FC<OptionProps> = ({ onClick }) => (+ <Tooltip title={t("clean_uncategorized")}>+ <IconButton onClick={onClick}>+ <HugeiconsIcon icon={CleanIcon} size={22} strokeWidth={1.5} />+ </IconButton>+ </Tooltip>+);++const MapQuickOption: React.FC<OptionProps> = ({ onClick }) => (+ <Tooltip title={t("map")}>+ <IconButton onClick={onClick}>+ <Box+ sx={{+ width: 24,+ height: 24,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ <PublicIcon />+ </Box>+ </IconButton>+ </Tooltip>+);++const showDownloadQuickOption = ({ type, attributes }: CollectionSummary) =>+ type == "album" ||+ type == "folder" ||+ type == "uncategorized" ||+ type == "hiddenItems" ||+ attributes.has("favorites") ||+ attributes.has("shared");++const showMapQuickOption = (collectionSummary: CollectionSummary) =>+ collectionSummary.type == "userFavorites" &&+ shouldShowMapOption(collectionSummary);++const shouldShowMapOption = ({ type, fileCount }: CollectionSummary) =>+ fileCount > 0 &&+ type !== "all" &&+ type !== "archiveItems" &&+ type !== "trash" &&+ type !== "hiddenItems";++type DownloadQuickOptionProps = OptionProps & {+ collectionSummary: CollectionSummary;+};++const DownloadIcon: React.FC = () => (+ <svg+ width="22"+ height="22"+ viewBox="0 0 24 24"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M2.99969 17.0002C2.99969 17.9302 2.99969 18.3952 3.10192 18.7767C3.37932 19.8119 4.18796 20.6206 5.22324 20.898C5.60474 21.0002 6.06972 21.0002 6.99969 21.0002L16.9997 21.0002C17.9297 21.0002 18.3947 21.0002 18.7762 20.898C19.8114 20.6206 20.6201 19.8119 20.8975 18.7767C20.9997 18.3952 20.9997 17.9302 20.9997 17.0002" />+ <path d="M16.4998 11.5002C16.4998 11.5002 13.1856 16.0002 11.9997 16.0002C10.8139 16.0002 7.49976 11.5002 7.49976 11.5002M11.9997 15.0002V3.00016" />+ </svg>+);++const DownloadQuickOption: React.FC<DownloadQuickOptionProps> = ({+ collectionSummary: { type },+ onClick,+}) => (+ <Tooltip+ title={+ type == "userFavorites"+ ? t("download_favorites")+ : type == "uncategorized"+ ? t("download_uncategorized")+ : type == "hiddenItems"+ ? t("download_hidden_items")+ : t("download_album")+ }+ >+ <IconButton onClick={onClick}>+ <Box+ sx={{+ width: 24,+ height: 24,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ <DownloadIcon />+ </Box>+ </IconButton>+ </Tooltip>+);++export const FeedIcon: React.FC = () => (+ <svg+ width="23"+ height="20"+ viewBox="0 0 23 20"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M9.7998 0.5C10.2416 0.5 10.5996 0.857977 10.5996 1.2998C10.5996 1.74163 10.2416 2.09961 9.7998 2.09961H4.7998C3.03249 2.09961 1.59961 3.53249 1.59961 5.2998V14.2998C1.59961 16.0671 3.0325 17.5 4.7998 17.5H13.7998C15.5671 17.5 17 16.0671 17 14.2998V11.7998C17 11.358 17.358 11 17.7998 11C18.2416 11 18.5996 11.358 18.5996 11.7998V14.2998C18.5996 16.9507 16.4507 19.0996 13.7998 19.0996H4.7998C2.14883 19.0996 0 16.9507 0 14.2998V5.2998C0 2.64884 2.14884 0.5 4.7998 0.5H9.7998Z"+ fill="currentColor"+ />+ <path+ d="M13.2998 13.5C13.7416 13.5 14.0996 13.858 14.0996 14.2998C14.0996 14.7416 13.7416 15.0996 13.2998 15.0996H4.2998C3.85798 15.0996 3.5 14.7416 3.5 14.2998C3.5 13.858 3.85798 13.5 4.2998 13.5H13.2998Z"+ fill="currentColor"+ />+ <path+ d="M10.2998 10.5C10.7416 10.5 11.0996 10.858 11.0996 11.2998C11.0996 11.7416 10.7416 12.0996 10.2998 12.0996H4.2998C3.85798 12.0996 3.5 11.7416 3.5 11.2998C3.5 10.858 3.85798 10.5 4.2998 10.5H10.2998Z"+ fill="currentColor"+ />+ <path+ d="M20.6523 6.12012C21.3761 5.2635 22.0996 4.13144 22.0996 2.93848C22.0995 1.38141 20.9626 0 19.2998 0C18.621 0 17.9847 0.205224 17.2998 0.749023C16.6149 0.205224 15.9787 0 15.2998 0C13.637 0 12.5001 1.38141 12.5 2.93848C12.5 4.13144 13.2236 5.2635 13.9473 6.12012C14.698 7.00866 15.5878 7.76218 16.1758 8.21484C16.8431 8.72865 17.7565 8.72865 18.4238 8.21484C19.0119 7.76218 19.9016 7.00866 20.6523 6.12012Z"+ fill="currentColor"+ />+ </svg>+);++const showShareQuickOption = ({ type, attributes }: CollectionSummary) =>+ type == "album" ||+ type == "folder" ||+ attributes.has("favorites") ||+ attributes.has("shared");++const showCastQuickOption = ({ type }: CollectionSummary) =>+ type == "userFavorites";++interface ShareQuickOptionProps {+ collectionSummary: CollectionSummary;+ isQuickLinkAlbum: boolean;+ onClick: () => void;+}++const ShareIcon: React.FC = () => (+ <svg+ width="21"+ height="19"+ viewBox="0 0 22 20"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M13.875 8C13.3918 8 13 8.39175 13 8.875C13 9.35825 13.3918 9.75 13.875 9.75V8.875V8ZM13.875 0C13.3918 0 13 0.391751 13 0.875C13 1.35825 13.3918 1.75 13.875 1.75V0.875V0ZM15.875 11C15.3918 11 15 11.3918 15 11.875C15 12.3582 15.3918 12.75 15.875 12.75V11.875V11ZM17.375 18C16.8918 18 16.5 18.3918 16.5 18.875C16.5 19.3582 16.8918 19.75 17.375 19.75V18.875V18ZM11.875 4.875H11C11 6.60089 9.60086 8 7.875 8V8.875V9.75C10.5673 9.75 12.75 7.56739 12.75 4.875H11.875ZM7.875 8.875V8C6.14911 8 4.75 6.60089 4.75 4.875H3.875H3C3 7.56739 5.18261 9.75 7.875 9.75V8.875ZM3.875 4.875H4.75C4.75 3.14911 6.14911 1.75 7.875 1.75V0.875V0C5.18261 0 3 2.18261 3 4.875H3.875ZM7.875 0.875V1.75C9.60086 1.75 11 3.14911 11 4.875H11.875H12.75C12.75 2.18261 10.5673 0 7.875 0V0.875ZM13.875 8.875V9.75C16.5673 9.75 18.75 7.56739 18.75 4.875H17.875H17C17 6.60089 15.6009 8 13.875 8V8.875ZM17.875 4.875H18.75C18.75 2.18261 16.5673 0 13.875 0V0.875V1.75C15.6009 1.75 17 3.14911 17 4.875H17.875ZM9.875 11.875V11H5.875V11.875V12.75H9.875V11.875ZM5.875 11.875V11C2.63033 11 0 13.6304 0 16.875H0.875H1.75C1.75 14.5968 3.59683 12.75 5.875 12.75V11.875ZM0.875 16.875H0C0 18.4629 1.28719 19.75 2.875 19.75V18.875V18C2.25367 18 1.75 17.4963 1.75 16.875H0.875ZM2.875 18.875V19.75H12.875V18.875V18H2.875V18.875ZM12.875 18.875V19.75C14.4628 19.75 15.75 18.4628 15.75 16.875H14.875H14C14 17.4964 13.4964 18 12.875 18V18.875ZM14.875 16.875H15.75C15.75 13.6304 13.1196 11 9.875 11V11.875V12.75C12.1532 12.75 14 14.5968 14 16.875H14.875ZM15.875 11.875V12.75C18.1532 12.75 20 14.5968 20 16.875H20.875H21.75C21.75 13.6304 19.1196 11 15.875 11V11.875ZM20.875 16.875H20C20 17.4964 19.4964 18 18.875 18V18.875V19.75C20.4628 19.75 21.75 18.4628 21.75 16.875H20.875ZM18.875 18.875V18H17.375V18.875V19.75H18.875V18.875Z"+ fill="currentColor"+ />+ </svg>+);++/** A smaller version of ShareIcon for use in the collection header summary. */+const SmallShareIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (+ <svg+ width="15"+ height="14"+ viewBox="0 0 22 20"+ {...props}+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M13.875 8C13.3918 8 13 8.39175 13 8.875C13 9.35825 13.3918 9.75 13.875 9.75V8.875V8ZM13.875 0C13.3918 0 13 0.391751 13 0.875C13 1.35825 13.3918 1.75 13.875 1.75V0.875V0ZM15.875 11C15.3918 11 15 11.3918 15 11.875C15 12.3582 15.3918 12.75 15.875 12.75V11.875V11ZM17.375 18C16.8918 18 16.5 18.3918 16.5 18.875C16.5 19.3582 16.8918 19.75 17.375 19.75V18.875V18ZM11.875 4.875H11C11 6.60089 9.60086 8 7.875 8V8.875V9.75C10.5673 9.75 12.75 7.56739 12.75 4.875H11.875ZM7.875 8.875V8C6.14911 8 4.75 6.60089 4.75 4.875H3.875H3C3 7.56739 5.18261 9.75 7.875 9.75V8.875ZM3.875 4.875H4.75C4.75 3.14911 6.14911 1.75 7.875 1.75V0.875V0C5.18261 0 3 2.18261 3 4.875H3.875ZM7.875 0.875V1.75C9.60086 1.75 11 3.14911 11 4.875H11.875H12.75C12.75 2.18261 10.5673 0 7.875 0V0.875ZM13.875 8.875V9.75C16.5673 9.75 18.75 7.56739 18.75 4.875H17.875H17C17 6.60089 15.6009 8 13.875 8V8.875ZM17.875 4.875H18.75C18.75 2.18261 16.5673 0 13.875 0V0.875V1.75C15.6009 1.75 17 3.14911 17 4.875H17.875ZM9.875 11.875V11H5.875V11.875V12.75H9.875V11.875ZM5.875 11.875V11C2.63033 11 0 13.6304 0 16.875H0.875H1.75C1.75 14.5968 3.59683 12.75 5.875 12.75V11.875ZM0.875 16.875H0C0 18.4629 1.28719 19.75 2.875 19.75V18.875V18C2.25367 18 1.75 17.4963 1.75 16.875H0.875ZM2.875 18.875V19.75H12.875V18.875V18H2.875V18.875ZM12.875 18.875V19.75C14.4628 19.75 15.75 18.4628 15.75 16.875H14.875H14C14 17.4964 13.4964 18 12.875 18V18.875ZM14.875 16.875H15.75C15.75 13.6304 13.1196 11 9.875 11V11.875V12.75C12.1532 12.75 14 14.5968 14 16.875H14.875ZM15.875 11.875V12.75C18.1532 12.75 20 14.5968 20 16.875H20.875H21.75C21.75 13.6304 19.1196 11 15.875 11V11.875ZM20.875 16.875H20C20 17.4964 19.4964 18 18.875 18V18.875V19.75C20.4628 19.75 21.75 18.4628 21.75 16.875H20.875ZM18.875 18.875V18H17.375V18.875V19.75H18.875V18.875Z"+ fill="currentColor"+ />+ </svg>+);++const ShareQuickOption: React.FC<ShareQuickOptionProps> = ({+ collectionSummary: { attributes },+ isQuickLinkAlbum,+ onClick,+}) => (+ <Tooltip+ title={+ isQuickLinkAlbum+ ? t("manage_link")+ : attributes.has("userFavorites")+ ? t("share_favorites")+ : attributes.has("sharedIncoming")+ ? t("sharing_details")+ : attributes.has("shared")+ ? t("modify_sharing")+ : t("share_album")+ }+ >+ <IconButton onClick={onClick}>+ <Box+ sx={{+ width: 24,+ height: 24,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ {isQuickLinkAlbum ? <LinkIcon /> : <ShareIcon />}+ </Box>+ </IconButton>+ </Tooltip>+);++const CastQuickOption: React.FC<OptionProps> = ({ onClick }) => (+ <Tooltip title={t("cast_to_tv")}>+ <IconButton onClick={onClick}>+ <Box+ sx={{+ width: 24,+ height: 24,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ <HugeiconsIcon+ icon={ModernTvIcon}+ size={22}+ strokeWidth={1.8}+ />+ </Box>+ </IconButton>+ </Tooltip>+);++const EmptyTrashOption: React.FC<OptionProps> = ({ onClick }) => (+ <OverflowMenuOption+ color="critical"+ startIcon={+ <HugeiconsIcon icon={Delete02Icon} size={20} strokeWidth={1.5} />+ }+ onClick={onClick}+ >+ {t("empty_trash")}+ </OverflowMenuOption>+);++type DownloadOptionProps = OptionProps & {+ isDownloadInProgress?: () => boolean;+};++const DownloadOption: React.FC<+ React.PropsWithChildren<DownloadOptionProps>+> = ({ isDownloadInProgress, onClick, children }) => (+ <OverflowMenuOption+ startIcon={+ isDownloadInProgress?.() ? (+ <ActivityIndicator size="20px" sx={{ cursor: "not-allowed" }} />+ ) : (+ <DownloadIcon />+ )+ }+ onClick={onClick}+ >+ {children}+ </OverflowMenuOption>+);++interface CollectionSortOrderMenuProps {+ open: boolean;+ onClose: () => void;+ overflowMenuIconRef: React.RefObject<SVGSVGElement | null>;+ sortAsc: boolean;+ onAscClick: () => void;+ onDescClick: () => void;+}++const CollectionSortOrderMenu: React.FC<CollectionSortOrderMenuProps> = ({+ open,+ onClose,+ overflowMenuIconRef,+ sortAsc,+ onAscClick,+ onDescClick,+}) => {+ const handleAscClick = () => {+ onAscClick();+ onClose();+ };++ const handleDescClick = () => {+ onDescClick();+ onClose();+ };++ return (+ <Menu+ id="collection-files-sort"+ anchorEl={overflowMenuIconRef.current}+ open={open}+ onClose={onClose}+ slotProps={{+ list: {+ disablePadding: true,+ "aria-labelledby": "collection-files-sort",+ },+ }}+ anchorOrigin={{ vertical: "bottom", horizontal: "right" }}+ transformOrigin={{ vertical: "top", horizontal: "right" }}+ >+ <OverflowMenuOption+ onClick={handleDescClick}+ endIcon={!sortAsc ? <CheckIcon /> : undefined}+ >+ {t("newest_first")}+ </OverflowMenuOption>+ <OverflowMenuOption+ onClick={handleAscClick}+ endIcon={sortAsc ? <CheckIcon /> : undefined}+ >+ {t("oldest_first")}+ </OverflowMenuOption>+ </Menu>+ );+};diff --git a/web/apps/albums/vendor/photos/components/Collections/CollectionMapDialog.tsx b/web/apps/albums/vendor/photos/components/Collections/CollectionMapDialog.tsxnew file mode 100644index 0000000000..94f083205f--- /dev/null+++ b/web/apps/albums/vendor/photos/components/Collections/CollectionMapDialog.tsx@@ -0,0 +1,2634 @@+import AddIcon from "@mui/icons-material/Add";+import CloseIcon from "@mui/icons-material/Close";+import LocationOnIcon from "@mui/icons-material/LocationOn";+import RemoveIcon from "@mui/icons-material/Remove";+import {+ Box,+ Dialog,+ DialogContent,+ IconButton,+ Stack,+ styled,+ Typography,+ useMediaQuery,+ type IconButtonProps,+} from "@mui/material";+import { useTheme } from "@mui/material/styles";+import { ensureLocalUser } from "ente-accounts/services/user";+import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import { useBaseContext } from "ente-base/context";+import { downloadManager } from "ente-gallery/services/download";+import { uniqueFilesByID } from "ente-gallery/utils/file";+import { type Collection } from "ente-media/collection";+import { type EnteFile } from "ente-media/file";+import {+ fileCreationTime,+ fileLocation,+ ItemVisibility,+} from "ente-media/file-metadata";+import type { RemotePullOpts } from "ente-new/photos/components/gallery";+import {+ addToFavoritesCollection,+ isArchivedCollection,+ isHiddenCollection,+ removeFromFavoritesCollection,+} from "ente-new/photos/services/collection";+import { type CollectionSummary } from "ente-new/photos/services/collection-summary";+import { updateFilesVisibility } from "ente-new/photos/services/file";+import {+ savedCollectionFiles,+ savedCollections,+} from "ente-new/photos/services/photos-fdb";+import { t } from "i18next";+import "leaflet/dist/leaflet.css";+import type { Dispatch, SetStateAction } from "react";+import React, {+ startTransition,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import Supercluster from "supercluster";+import type { SelectedState } from "utils/file";+import type { FileListWithViewerProps } from "../FileListWithViewer";+import { FileListWithViewer } from "../FileListWithViewer";+import { calculateOptimalZoom } from "../TripLayout/mapHelpers";+import type { JourneyPoint } from "../TripLayout/types";++interface CollectionMapDialogProps+ extends ModalVisibilityProps,+ Pick<+ FileListWithViewerProps,+ | "onAddSaveGroup"+ | "onMarkTempDeleted"+ | "onAddFileToCollection"+ | "onRemoteFilesPull"+ | "onVisualFeedback"+ | "fileNormalCollectionIDs"+ | "collectionNameByID"+ | "onSelectCollection"+ | "onSelectPerson"+ > {+ collectionSummary: CollectionSummary;+ activeCollection: Collection | undefined;+ onRemotePull?: (opts?: RemotePullOpts) => Promise<void>;+}++// Describes all map-related state used in the dialog:+// - mapCenter: current map center, typically derived from the latest file with location+// - mapIndex/mapPoints/latestFileId: spatial index and its source points, plus the newest file id+// - filesByID/thumbByFileID: cached file metadata and lazily-fetched thumbnails+// - isLoading/error: loading/error flags for map data fetches++interface MapDataState {+ mapCenter: [number, number] | null;+ mapIndex: MapIndex | null;+ mapPoints: MapIndexPoint[];+ latestFileId: number | undefined;+ filesByID: Map<number, EnteFile>;+ thumbByFileID: Map<number, string>;+ isLoading: boolean;+ error: string | null;+}++/**+ * When files are being opened from the the Sidebar, there is ablity to add them as favoriate,+ * archive them or unarchieve them and this interface is for facilitating that. Where the favoruteFileIds+ * hols the existing favorites, pending holds the ones which are in progress for respective ones+ */++interface FavoritesState {+ favoriteFileIDs: Set<number>;+ pendingFavoriteUpdates: Set<number>;+ pendingVisibilityUpdates: Set<number>;+}++/**+ * Extension of MapDataState that adds mutation functions for map data management.+ * - removeFiles: Removes files from the map index when deleted from FileListWithViewer+ * - updateFileVisibility: Updates file visibility state and removes hidden files from the map+ * - queueThumbnailFetch: Batches and fetches thumbnails on demand for visible files+ */++interface MapDataResult extends MapDataState {+ removeFiles: (fileIDs: number[]) => void;+ updateFileVisibility: (file: EnteFile, visibility: ItemVisibility) => void;+ queueThumbnailFetch: (fileIDs: number[]) => void;+}++/**+ * Dynamically loaded map components to avoid SSR issues with Leaflet. Normal imports actually caused+ * the app to break in some instances, thus dynamically loading them instead.+ * Loaded lazily in useMapComponents() hook when the dialog opens to ensure window exists.+ */+interface MapComponents {+ MapContainer: typeof import("react-leaflet").MapContainer;+ TileLayer: typeof import("react-leaflet").TileLayer;+ Marker: typeof import("react-leaflet").Marker;+ useMap: typeof import("react-leaflet").useMap;+}++/**+ * Represents a geotagged photo point stored in the map spatial index.+ * Each point corresponds to a photo with location metadata.+ * - fileId: Unique identifier for the photo file+ * - lat: Latitude coordinate of the photo location+ * - lng: Longitude coordinate of the photo location+ * - timestamp: Unix timestamp (milliseconds) of when the photo was created+ */++interface MapIndexPoint {+ fileId: number;+ lat: number;+ lng: number;+ timestamp: number;+}++/**+ * Along with the GeoTagged photos we are also storing a metadata, which changes+ * only when there is change in the stored values, to prevent this from updating+ * each time when there is change. Currently fileCount and updationTime are the+ * two metrics kept to analyse this change.+ */++/**+ * The small payload we attach to a point: fileId points to the photo, and timestamp keeps+ * enough context for sorting or choosing the freshest item in a cluster.+ */+interface MapPointProperties {+ fileId: number;+ timestamp: number;+}++/**+ * A GeoJSON feature for a single photo point. GeoJSON is the small, common shape most map+ * libraries expect for geographic data, so we stick with it even when we only need a+ * couple of fields. type stays "Feature" because that is the GeoJSON spec's envelope for+ * real-world points; it does not change our logic, but it keeps the data recognizable to+ * tooling like Supercluster. properties carry the fileId and timestamp (and keep cluster+ * as false), and geometry stores the point in [lng, lat] order for map libs.+ */+interface MapPointFeature {+ type: "Feature";+ properties: MapPointProperties & { cluster?: false };+ geometry: { type: "Point"; coordinates: [number, number] };+}++/**+ * Summary info for a cluster: latestTimestamp and latestFileId keep track of the freshest+ * photo inside the cluster so we can choose a representative cover.+ */+interface MapClusterProperties {+ latestTimestamp: number;+ latestFileId: number;+}++/**+ * A GeoJSON feature that represents a cluster instead of a single point. properties mark+ * it as a cluster, carry cluster_id for expansion, point_count for the raw size, and+ * point_count_abbreviated for a compact label, while geometry still gives the centroid.+ */+interface MapClusterFeature {+ type: "Feature";+ properties: MapClusterProperties & {+ cluster: true;+ cluster_id: number;+ point_count: number;+ point_count_abbreviated?: number | string;+ };+ geometry: { type: "Point"; coordinates: [number, number] };+}++/**+ * Convenience union so callers can handle clusters and single points together.+ */+type MapFeature = MapClusterFeature | MapPointFeature;++/**+ * The small contract we rely on from Supercluster: load ingests points, getClusters+ * returns mixed clusters/points for bounds and zoom, getLeaves expands a cluster into+ * its points, and getClusterExpansionZoom tells us how far to zoom to break it apart.+ */+interface MapIndex {+ load(points: MapPointFeature[]): MapIndex;+ getClusters(+ bbox: [number, number, number, number],+ zoom: number,+ ): MapFeature[];+ getLeaves(+ clusterId: number,+ limit: number,+ offset: number,+ ): MapPointFeature[];+ getClusterExpansionZoom(clusterId: number): number;+}++/**+ * Tuning knobs for building the index: radius controls cluster size in pixels, maxZoom+ * caps clustering depth, map shapes point data into the cluster properties we track,+ * and reduce merges those properties as clusters grow.+ */+interface MapClusterOptions {+ radius?: number;+ maxZoom?: number;+ map?: (props: MapPointProperties) => MapClusterProperties;+ reduce?: (+ accumulated: MapClusterProperties,+ props: MapClusterProperties,+ ) => void;+}++type SuperclusterConstructor = new (options?: MapClusterOptions) => MapIndex;++//OpenStreetMap only supports clustering till this zoom level and this tell the supercluster what the max limit is for the zoom.+const MAX_MAP_ZOOM = 19;+//Instead of loading just the tiles which are in view, we're actually loading the 15% of the surrounding zone as well for smoother experience.+//Leaflet LatLngBounds.pad expects a ratio (0.15 = 15%).+const PREFETCH_BOUNDS_PADDING = 0.15;+//This count controls how many thumbnails are fetched in each batch when loading images for the markers+const THUMBNAIL_BATCH_SIZE = 40;++/**+ * This is the first hook which is being loaded when the CollectionMapDialog is mounted+ * Dynamically loads map-related React components (Leaflet) to avoid SSR issues+ * Responsibility: Lazy load map dependencies only when needed (window must exist)+ */+function useMapComponents() {+ const [mapComponents, setMapComponents] = useState<MapComponents | null>(+ null,+ );++ useEffect(() => {+ // Only load on client-side where window exists, and updates the state with the components.+ if (typeof window === "undefined") return;++ void import("react-leaflet")+ .then((leaflet) =>+ setMapComponents({+ MapContainer: leaflet.MapContainer,+ TileLayer: leaflet.TileLayer,+ Marker: leaflet.Marker,+ useMap: leaflet.useMap,+ }),+ )+ .catch((e: unknown) => {+ console.error("Failed to load map components", e);+ });+ }, []);++ return mapComponents;+}++/**+ * Retrieves the current authenticated user data and throws error if the user is not loggedIn.+ * Responsibility: Provide user context for favorite/visibility operations+ */+function useCurrentUser() {+ return useMemo(() => {+ try {+ return ensureLocalUser();+ } catch {+ return undefined;+ }+ }, []);+}++/**+ *+ * @param files+ * @returns points, latestFileId+ *+ * This function create the inital mapIndexPoint any collection.+ * It's later this points+ * that is being given to the supercluster for the mapping and indexing.+ *+ * This function loops over the entire files which is suspect is not EFFICENT+ * but currently it loads about 1,00,000 images seamlessly which is far better+ * than the earlier implementation we had.+ */+const buildMapIndexPoints = async (files: EnteFile[]) => {+ const points: MapIndexPoint[] = [];+ let latestTimestamp = -1;+ let latestFileId: number | undefined;++ //looping over each file to extract their time and location to create the point+ for (let index = 0; index < files.length; index += 1) {+ const file = files[index];+ if (!file) continue;+ const loc = fileLocation(file);+ if (!loc) continue;++ const timestamp = fileCreationTime(file);+ points.push({+ fileId: file.id,+ lat: loc.latitude,+ lng: loc.longitude,+ timestamp,+ });++ if (timestamp > latestTimestamp) {+ latestTimestamp = timestamp;+ latestFileId = file.id;+ }++ /**+ * This pauses the event loop briefly, so the main thead is not blocked if there are mutliple so many files.+ * This doesn't change the complexisty of this loop, just keep the thread responsive for UI updates, input and rendering.+ */++ if (index > 0 && index % 5000 === 0) {+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+ }++ return { points, latestFileId };+};++/**+ *+ * @param points+ * @returns a SuperCluster Spatial Index, using which we can retrive (1)the clusters/points for a particular bbox + zoom level+ * (2) all leaves under a cluster. (3) the maximum zoom for a particular cluster+ *+ * This function converts every MapIndexPoint to a GeoJSON Feature(required for rendering+ * using supercluster)[type MapPointFeature]. NOTE this index is not persisted.+ */+const buildClusterIndex = (points: MapIndexPoint[]): MapIndex => {+ /**+ * - For every point we load, Supercluster calls map(props) once to decide what+ * cluster metadata that point contributes.+ *+ * - When multiple points are to begrouped into a cluster, Supercluster repeatedly calls+ * reduce(accumulated, props) to merge those per‑point metadata objects into a single cluster summary.+ */++ const options: MapClusterOptions = {+ radius: 80,+ maxZoom: MAX_MAP_ZOOM,+ map: (props) => ({+ latestTimestamp: props.timestamp,+ latestFileId: props.fileId,+ }),+ reduce: (accumulated, props) => {+ if (props.latestTimestamp > accumulated.latestTimestamp) {+ accumulated.latestTimestamp = props.latestTimestamp;+ accumulated.latestFileId = props.latestFileId;+ }+ },+ };++ const SuperclusterCtor = Supercluster as unknown as SuperclusterConstructor;+ const index = new SuperclusterCtor(options);++ // converting MapIndexPoint -> MapPointFeature+ const features: MapPointFeature[] = points.map((point) => ({+ type: "Feature" as const,+ properties: { fileId: point.fileId, timestamp: point.timestamp },+ geometry: {+ type: "Point" as const,+ coordinates: [point.lng, point.lat] as [number, number],+ },+ }));++ //builds the spaital cluster hierachy across various zoom level+ index.load(features);+ return index;+};++const buildMapIndex = (points: MapIndexPoint[]) =>+ points.length > 0 ? buildClusterIndex(points) : null;++const getPointByFileId = (+ points: MapIndexPoint[],+ fileId: number | undefined,+) => {+ if (fileId === undefined) return undefined;+ return points.find((point) => point.fileId === fileId);+};++/**+ *+ * @param points+ * @returns MapIndexPoint+ *+ * Though we are computing the latestFile while loadMapData(), sometimes+ * if this latestFile is deleted or archieved by the user then we need+ * to compute a new latestFile, this is the purpose this fn serves.+ */+const getLatestPointByTimestamp = (+ points: MapIndexPoint[],+): MapIndexPoint | undefined => {+ let latest: MapIndexPoint | undefined;+ for (const point of points) {+ if (!latest || point.timestamp > latest.timestamp) {+ latest = point;+ }+ }+ return latest;+};++const getLatestFileIdFromPoints = (points: MapIndexPoint[]) =>+ getLatestPointByTimestamp(points)?.fileId;++/**+ * Loads and manages map data including index, files, and thumbnails.+ * Responsibility: Fetch collection files, build/persist spatial index, prefetch thumbnails on demand.+ */+function useMapData(+ open: boolean,+ collectionSummary: CollectionSummary,+ activeCollection: Collection | undefined,+ onGenericError: (e: unknown) => void,+): MapDataResult {+ const [state, setState] = useState<MapDataState>({+ mapCenter: null,+ mapIndex: null,+ mapPoints: [],+ latestFileId: undefined,+ filesByID: new Map(),+ thumbByFileID: new Map(),+ isLoading: false,+ error: null,+ });++ //Ref mirroring the filesByID(state) to prevent the stale closure issue with the queueThumbnailFetch useCallback fn().+ const filesByIDRef = useRef<Map<number, EnteFile>>(new Map());+ //Ref mirroring the thumbByFileID state to prevent the same issue as above+ const thumbsByFileIDRef = useRef<Map<number, string>>(new Map());+ //A work queue with the list of fileIDs waiting to have their thumbs fetched.+ const pendingThumbsRef = useRef<Set<number>>(new Set());+ const isThumbnailWorkerRunningRef = useRef(false);++ // Track which collection we've loaded to avoid unnecessary reloads+ // Include fileCount to detect when collection content changes+ const loadedCollectionRef = useRef<{+ summaryId: number;+ collectionId: number | undefined;+ fileCount: number;+ updationTime: number | null;+ } | null>(null);++ //Syncing the refs with the state for the stale closure prevention.+ useEffect(() => {+ filesByIDRef.current = state.filesByID;+ }, [state.filesByID]);++ useEffect(() => {+ thumbsByFileIDRef.current = state.thumbByFileID;+ }, [state.thumbByFileID]);++ const queueThumbnailFetch = useCallback((fileIDs: number[]) => {+ if (!fileIDs.length) return;++ const pending = pendingThumbsRef.current;+ const existingThumbs = thumbsByFileIDRef.current;+ const filesByID = filesByIDRef.current;++ /**+ * Loops through the fileIds for which thumbnails are to fetched,+ * and if thumbs are already generated or that fileId doesn't exist+ * then skipping it.+ *+ * Otherwise adding it to the ref for the fetching process+ */+ for (const fileId of fileIDs) {+ if (existingThumbs.has(fileId)) continue;+ if (!filesByID.has(fileId)) continue;+ pending.add(fileId);+ }++ if (isThumbnailWorkerRunningRef.current) return;+ isThumbnailWorkerRunningRef.current = true;++ void (async () => {+ while (pendingThumbsRef.current.size > 0) {+ /**+ * Since we're fetching in a batched manner, slicing the THUMBNAIL_BATCH_SIZE for fetching and+ * removing these from the pending list.+ */++ const batchIds = Array.from(pendingThumbsRef.current).slice(+ 0,+ THUMBNAIL_BATCH_SIZE,+ );+ batchIds.forEach((id) => pendingThumbsRef.current.delete(id));++ const entries = await Promise.all(+ batchIds.map(async (fileId) => {+ const file = filesByIDRef.current.get(fileId);+ if (!file) return [fileId, undefined] as const;+ try {+ const thumb =+ await downloadManager.renderableThumbnailURL(+ file,+ );+ return [fileId, thumb] as const;+ } catch {+ return [fileId, undefined] as const;+ }+ }),+ );++ /**+ * Updating the existing state with the newly fetched thumbnails.+ */+ setState((prev) => {+ const updatedThumbMap = new Map(prev.thumbByFileID);+ entries.forEach(([fileId, thumbnailUrl]) => {+ if (!thumbnailUrl || updatedThumbMap.has(fileId))+ return;+ updatedThumbMap.set(fileId, thumbnailUrl);+ });+ return updatedThumbMap.size > prev.thumbByFileID.size+ ? { ...prev, thumbByFileID: updatedThumbMap }+ : prev;+ });++ //To yield control between batches os the UI stays responsive+ await new Promise((resolve) => setTimeout(resolve, 0));+ }++ isThumbnailWorkerRunningRef.current = false;+ })();+ }, []);++ // Clear loaded ref when dialog closes so we reload fresh data next time.+ useEffect(() => {+ if (!open) {+ loadedCollectionRef.current = null;+ pendingThumbsRef.current.clear();+ isThumbnailWorkerRunningRef.current = false;+ }+ }, [open]);++ useEffect(() => {+ if (!open) return;++ // Skip reload if we already have data for this collection with same file count+ const currentSummaryId = collectionSummary.id;+ const currentCollectionId = activeCollection?.id;+ const currentFileCount = collectionSummary.fileCount;+ const currentUpdationTime = collectionSummary.updationTime ?? null;+ const loaded = loadedCollectionRef.current;++ //preventing reloading of the data if it's already loaded.+ if (+ loaded &&+ loaded.summaryId === currentSummaryId &&+ loaded.collectionId === currentCollectionId &&+ loaded.fileCount === currentFileCount &&+ loaded.updationTime === currentUpdationTime+ ) {+ return;+ }++ const loadMapData = async () => {+ //In this ref we are actually setting a new Set() so clearing that before any compute happens.+ pendingThumbsRef.current.clear();+ setState((prev) => ({ ...prev, isLoading: true, error: null }));++ try {+ const files = await getFilesForCollection(+ collectionSummary,+ activeCollection,+ );++ //Creating a id <- file mapping to drive renders and update the UI, changes to this will result in UI re-renders+ const filesByID = new Map(files.map((file) => [file.id, file]));+ //ref mirrow for using in the useCallbacks+ filesByIDRef.current = filesByID;++ const { points, latestFileId } =+ await buildMapIndexPoints(files);++ //mapIndex has the SuperCluster Spatial Index+ const mapIndex = buildMapIndex(points);++ const latestPoint =+ getPointByFileId(points, latestFileId) ?? points[0];++ const mapCenter: [number, number] | null = latestPoint+ ? [latestPoint.lat, latestPoint.lng]+ : null;++ setState({+ filesByID,+ mapCenter,+ mapIndex,+ mapPoints: points,+ latestFileId,+ thumbByFileID: new Map(),+ isLoading: false,+ error: null,+ });++ // Mark this collection as loaded+ loadedCollectionRef.current = {+ summaryId: currentSummaryId,+ collectionId: currentCollectionId,+ fileCount: currentFileCount,+ updationTime: currentUpdationTime,+ };++ const coverId = collectionSummary.coverFile?.id ?? latestFileId;+ if (coverId !== undefined) {+ queueThumbnailFetch([coverId]);+ }++ return;+ } catch (e) {+ setState((prev) => ({+ ...prev,+ isLoading: false,+ error: t("something_went_wrong"),+ }));+ onGenericError(e);+ } finally {+ // Ensure we never leave the dialog stuck in a loading state+ setState((prev) =>+ prev.isLoading ? { ...prev, isLoading: false } : prev,+ );+ }+ };++ void loadMapData();+ }, [+ open,+ collectionSummary,+ activeCollection,+ onGenericError,+ queueThumbnailFetch,+ ]);++ /**+ * This function is used to update the map view, after a file has been+ * deleted by the user. The deleted file is removed from the mapPoints+ * and then a new mapIndex is built+ */+ const removeFiles = useCallback((fileIDs: number[]) => {+ if (!fileIDs.length) return;+ setState((prev) => {+ const ids = new Set(fileIDs);+ const filesByID = new Map(prev.filesByID);+ const thumbByFileID = new Map(prev.thumbByFileID);+ ids.forEach((id) => {+ filesByID.delete(id);+ thumbByFileID.delete(id);+ });+ const mapPoints = prev.mapPoints.filter(+ (point) => !ids.has(point.fileId),+ );+ //Rebuilding the mapIndex after removing the point from the mapPoints+ const mapIndex = buildMapIndex(mapPoints);++ let latestFileId = prev.latestFileId;+ if (latestFileId && ids.has(latestFileId)) {+ latestFileId = getLatestFileIdFromPoints(mapPoints);+ }+ return {+ ...prev,+ filesByID,+ thumbByFileID,+ mapIndex,+ mapPoints,+ latestFileId,+ mapCenter: mapPoints.length ? prev.mapCenter : null,+ };+ });+ }, []);++ /**+ * This function is used to update the visiblity of a file from+ * archive to unarchive or vice-versa.+ */+ const updateFileVisibility = useCallback(+ (file: EnteFile, visibility: ItemVisibility) => {+ setState((prev) => {+ //If the file ID is not in the fileByID or the magicMetadata for the file doesn't exist then return prev state+ if (!prev.filesByID.has(file.id)) return prev;+ if (!file.magicMetadata) return prev;++ const updatedMagicMetadata = {+ ...file.magicMetadata,+ data: { ...file.magicMetadata.data, visibility },+ };++ const updatedFile: EnteFile = {+ ...file,+ magicMetadata: updatedMagicMetadata,+ };+ const filesByID = new Map(prev.filesByID);+ filesByID.set(file.id, updatedFile);++ let mapPoints = prev.mapPoints;+ let mapIndex = prev.mapIndex;+ let latestFileId = prev.latestFileId;++ //If the file is not visible then removing it from the mapPoints and creating a new Supercluster Spatial Mapping+ if (visibility !== ItemVisibility.visible) {+ const filtered = prev.mapPoints.filter(+ (point) => point.fileId !== file.id,+ );+ if (filtered.length !== prev.mapPoints.length) {+ mapPoints = filtered;+ mapIndex = buildMapIndex(mapPoints);+ if (latestFileId === file.id) {+ latestFileId = getLatestFileIdFromPoints(mapPoints);+ }+ }+ } else if (!prev.mapPoints.some((p) => p.fileId === file.id)) {+ //If the file was previously hidden then adding it back to the existing list.+ const loc = fileLocation(file);+ if (loc) {+ const timestamp = fileCreationTime(file);+ mapPoints = [+ ...prev.mapPoints,+ {+ fileId: file.id,+ lat: loc.latitude,+ lng: loc.longitude,+ timestamp,+ },+ ];++ //Recomputing the latest file, since there are possiblities of change+ mapIndex = buildMapIndex(mapPoints);+ const latestPoint =+ latestFileId !== undefined+ ? getPointByFileId(prev.mapPoints, latestFileId)+ : undefined;+ if (!latestPoint || timestamp > latestPoint.timestamp) {+ latestFileId = file.id;+ }+ }+ }++ //Recomputing the map center in case the latestFile has changed.+ let mapCenter = prev.mapCenter;+ if (!mapPoints.length) {+ mapCenter = null;+ } else if (!mapCenter) {+ const centerPoint =+ latestFileId !== undefined+ ? mapPoints.find(+ (point) => point.fileId === latestFileId,+ )+ : mapPoints[0];+ if (centerPoint) {+ mapCenter = [centerPoint.lat, centerPoint.lng];+ }+ }++ return {+ ...prev,+ filesByID,+ mapPoints,+ mapIndex,+ latestFileId,+ mapCenter,+ };+ });+ },+ [],+ );++ return { ...state, removeFiles, updateFileVisibility, queueThumbnailFetch };+}++/**+ * Manages favorite files state and handles favorite/visibility updates+ * Responsibility: Load user's favorites, toggle favorite status, update file visibility+ */+function useFavorites(+ open: boolean,+ user: ReturnType<typeof useCurrentUser>,+): FavoritesState & {+ handleToggleFavorite: (file: EnteFile) => Promise<void>;+ handleFileVisibilityUpdate: (+ file: EnteFile,+ visibility: ItemVisibility,+ ) => Promise<void>;+} {+ //Set to store the ids of files which are currenly favorited+ const [favoriteFileIDs, setFavoriteFileIDs] = useState<Set<number>>(+ new Set(),+ );+ //Set to store the IDs of the files which are in-flight for updation(favorite/unfavorite)+ const [pendingFavoriteUpdates, setPendingFavoriteUpdates] = useState<+ Set<number>+ >(new Set());+ //Set to store the IDs of the files which are in-flight for updation(archive/unarchive)+ const [pendingVisibilityUpdates, setPendingVisibilityUpdates] = useState<+ Set<number>+ >(new Set());++ useEffect(() => {+ if (!open || !user) return;++ /**+ * Each collectionFile has a collectionID associated with them, checking whether+ * that id matches with the id of each collectionFiles and if so then adding it to the+ * favoriteFileIDs.+ */+ const loadFavorites = async () => {+ const collections = await savedCollections();+ const collectionFiles = await savedCollectionFiles();++ for (const collection of collections) {+ if (+ collection.type === "favorites" &&+ collection.owner.id === user.id+ ) {+ const favoriteIDs = new Set(+ collectionFiles+ .filter((f) => f.collectionID === collection.id)+ .map((f) => f.id),+ );+ setFavoriteFileIDs(favoriteIDs);+ break;+ }+ }+ };++ void loadFavorites();+ }, [open, user]);++ // Helper to add/remove from Set immutably - avoids recreating Set when unnecessary+ const addToSet = useCallback((set: Set<number>, id: number) => {+ if (set.has(id)) return set;+ const next = new Set(set);+ next.add(id);+ return next;+ }, []);++ const removeFromSet = useCallback((set: Set<number>, id: number) => {+ if (!set.has(id)) return set;+ const next = new Set(set);+ next.delete(id);+ return next;+ }, []);++ const handleToggleFavorite = useCallback(+ async (file: EnteFile) => {+ if (!user) return;+ const fileID = file.id;++ // Check favorite status at call time to avoid stale closure+ const isFavorite = favoriteFileIDs.has(fileID);++ setPendingFavoriteUpdates((prev) => addToSet(prev, fileID));+ try {+ const action = isFavorite+ ? removeFromFavoritesCollection+ : addToFavoritesCollection;+ await action([file]);+ setFavoriteFileIDs((prev) =>+ isFavorite+ ? removeFromSet(prev, fileID)+ : addToSet(prev, fileID),+ );+ } finally {+ setPendingFavoriteUpdates((prev) =>+ removeFromSet(prev, fileID),+ );+ }+ },+ [user, favoriteFileIDs, addToSet, removeFromSet],+ );++ const handleFileVisibilityUpdate = useCallback(+ async (file: EnteFile, visibility: ItemVisibility) => {+ const fileID = file.id;+ setPendingVisibilityUpdates((prev) => addToSet(prev, fileID));+ try {+ await updateFilesVisibility([file], visibility);+ } finally {+ setPendingVisibilityUpdates((prev) =>+ removeFromSet(prev, fileID),+ );+ }+ },+ [addToSet, removeFromSet],+ );++ return {+ favoriteFileIDs,+ pendingFavoriteUpdates,+ pendingVisibilityUpdates,+ handleToggleFavorite,+ handleFileVisibilityUpdate,+ };+}++/**+ * Manages the lifecycle of the currently visible journey photos.+ *+ * Tracks the ordered list of visible photos and exposes a setter to update them.+ * It's the visiblePhotos that are being shown in the Sidebar to the left of the map+ *+ * @returns An object containing the visible photos array and setter.+ */+function useVisiblePhotos() {+ const [visiblePhotos, setVisiblePhotos] = useState<JourneyPoint[]>([]);+ const [isVisiblePhotosUpdating, setIsVisiblePhotosUpdating] =+ useState(false);++ return {+ visiblePhotos,+ setVisiblePhotos,+ isVisiblePhotosUpdating,+ setIsVisiblePhotosUpdating,+ };+}++/**+ * Creates a marker icon for individual photos (no badge)+ * Used only in CollectionMapDialog for consistent styling+ */+function createMarkerIcon(+ imageSrc: string,+ size: number,+): import("leaflet").DivIcon | null {+ if (typeof window === "undefined") return null;++ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const leaflet = require("leaflet") as typeof import("leaflet");++ const pinSize = size + 16; // Add padding for consistent sizing with TripLayout+ const triangleHeight = 10;+ const pinHeight = pinSize + triangleHeight + 2;+ const hasImage = imageSrc && imageSrc.trim() !== "";++ // Border radius matching TripLayout style+ const outerBorderRadius = 16;+ const innerBorderRadius = 12;++ return leaflet.divIcon({+ html: `+ <div class="photo-pin" style="+ width: ${pinSize}px;+ height: ${pinHeight}px;+ position: relative;+ cursor: pointer;+ transition: all 0.3s ease;+ filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3)) drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));+ ">+ <div style="+ width: ${pinSize}px;+ height: ${pinSize}px;+ border-radius: ${outerBorderRadius}px;+ background: white;+ border: 2px solid #ffffff;+ padding: 4px;+ position: relative;+ overflow: hidden;+ transition: background-color 0.3s ease, border-color 0.3s ease;+ "+ onmouseover="this.style.background='#22c55e'; this.style.borderColor='#22c55e'; this.nextElementSibling.style.borderTopColor='#22c55e';"+ onmouseout="this.style.background='white'; this.style.borderColor='#ffffff'; this.nextElementSibling.style.borderTopColor='white';"+ >+ ${+ hasImage+ ? `<img src="${imageSrc}" style="width:100%;height:100%;object-fit:cover;border-radius:${innerBorderRadius}px;" alt="Location" />`+ : `<div style="width:100%;height:100%;border-radius:${innerBorderRadius}px;animation:skeleton-pulse 1.5s ease-in-out infinite;"></div>+ <style>@keyframes skeleton-pulse{0%{background-color:#ffffff}50%{background-color:#f0f0f0}100%{background-color:#ffffff}}</style>`+ }+ </div>+ <div style="+ position: absolute;+ bottom: 2px;+ left: 50%;+ transform: translateX(-50%);+ width: 0;+ height: 0;+ border-left: ${triangleHeight}px solid transparent;+ border-right: ${triangleHeight}px solid transparent;+ border-top: ${triangleHeight}px solid white;+ transition: border-top-color 0.3s ease;+ "></div>+ </div>+ `,+ className: "collection-marker",+ iconSize: [pinSize, pinHeight],+ iconAnchor: [pinSize / 2, pinHeight],+ popupAnchor: [0, -pinHeight],+ });+}++/**+ * Creates a cluster icon with badge popping out of the container+ * Used only in CollectionMapDialog for cluster markers+ */+function createClusterIcon(+ imageSrc: string,+ size: number,+ clusterCount: number,+ interactive = true,+): import("leaflet").DivIcon | null {+ if (typeof window === "undefined") return null;++ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const leaflet = require("leaflet") as typeof import("leaflet");++ const pinSize = size + 16; // Add padding for consistent sizing with TripLayout+ const triangleHeight = 10;+ const pinHeight = pinSize + triangleHeight + 2;+ const hasImage = imageSrc && imageSrc.trim() !== "";+ const badgeOverflow = 6;++ // Border radius matching TripLayout style+ const outerBorderRadius = 16;+ const innerBorderRadius = 12;++ const hoverHandlers = interactive+ ? "onmouseover=\"this.style.background='#22c55e'; this.style.borderColor='#22c55e'; this.parentElement.querySelector('.triangle').style.borderTopColor='#22c55e';\" onmouseout=\"this.style.background='white'; this.style.borderColor='#ffffff'; this.parentElement.querySelector('.triangle').style.borderTopColor='white';\""+ : "";++ const badgeLabel =+ clusterCount >= 2000+ ? `${Math.floor((clusterCount - 1) / 1000)}K+`+ : clusterCount >= 1000+ ? "1K+"+ : clusterCount > 999+ ? `${Math.floor(clusterCount / 100)}00+`+ : `${clusterCount}`;++ return leaflet.divIcon({+ html: `+ <div class="photo-pin" style="+ width: ${pinSize}px;+ height: ${pinHeight}px;+ position: relative;+ cursor: ${interactive ? "pointer" : "default"};+ transition: all 0.3s ease;+ overflow: visible;+ filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3)) drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));+ ">+ <div style="+ width: ${pinSize}px;+ height: ${pinSize}px;+ border-radius: ${outerBorderRadius}px;+ background: white;+ border: 2px solid #ffffff;+ padding: 4px;+ position: relative;+ overflow: hidden;+ transition: background-color 0.3s ease, border-color 0.3s ease;+ "+ ${hoverHandlers}+ >+ ${+ hasImage+ ? `<img src="${imageSrc}" style="width:100%;height:100%;object-fit:cover;border-radius:${innerBorderRadius}px;" alt="Location" />`+ : `<div style="width:100%;height:100%;border-radius:${innerBorderRadius}px;animation:skeleton-pulse 1.5s ease-in-out infinite;"></div>+ <style>@keyframes skeleton-pulse{0%{background-color:#ffffff}50%{background-color:#f0f0f0}100%{background-color:#ffffff}}</style>`+ }+ </div>+ <div style="+ position: absolute;+ top: -${badgeOverflow}px;+ right: -${badgeOverflow}px;+ background: #22c55e;+ color: #ffffff;+ border-radius: 7px;+ padding: 4px 7px;+ font-size: 12px;+ font-weight: 700;+ line-height: 1;+ box-shadow: 0 2px 6px rgba(0,0,0,0.2);+ z-index: 1;+ ">+ ${badgeLabel}+ </div>+ <style>+ .leaflet-marker-icon.collection-cluster-marker { overflow: visible !important; }+ </style>+ <div class="triangle" style="+ position: absolute;+ bottom: 2px;+ left: 50%;+ transform: translateX(-50%);+ width: 0;+ height: 0;+ border-left: ${triangleHeight}px solid transparent;+ border-right: ${triangleHeight}px solid transparent;+ border-top: ${triangleHeight}px solid white;+ transition: border-top-color 0.3s ease;+ "></div>+ </div>+ `,+ className: "collection-cluster-marker",+ iconSize: [pinSize + badgeOverflow, pinHeight + badgeOverflow],+ iconAnchor: [pinSize / 2, pinHeight],+ popupAnchor: [0, -pinHeight],+ });+}++// ============================================================================+// Helper Functions+// ============================================================================++/**+ * Returns true if the file is visible (not archived or hidden).+ */+function isFileVisible(file: EnteFile): boolean {+ const visibility = file.magicMetadata?.data.visibility;+ // Files without visibility metadata are considered visible (default state)+ return visibility === undefined || visibility === ItemVisibility.visible;+}++/**+ * Loads every locally stored file, filters those belonging to the+ * target collection, removes duplicates by ID, filters out hidden/archived+ * files, and returns the unique set of visible files. For "All", it also+ * excludes files that belong to hidden or archived collections.+ */+async function getFilesForCollection(+ collectionSummary: CollectionSummary,+ activeCollection: Collection | undefined,+): Promise<EnteFile[]> {+ if (collectionSummary.type === "all") {+ const [allFiles, collections] = await Promise.all([+ savedCollectionFiles(),+ savedCollections(),+ ]);+ // Filter out hidden and archived files to prevent leaking items users expect to remain hidden.+ const visibleFiles = allFiles.filter(isFileVisible);+ const hiddenCollectionIDs = new Set(+ collections+ .filter(isHiddenCollection)+ .map((collection) => collection.id),+ );+ const archivedCollectionIDs = new Set(+ collections+ .filter(isArchivedCollection)+ .map((collection) => collection.id),+ );+ const hiddenFileIDs = new Set(+ allFiles+ .filter((file) => hiddenCollectionIDs.has(file.collectionID))+ .map((file) => file.id),+ );+ const archivedFileIDs = new Set(+ allFiles+ .filter((file) => archivedCollectionIDs.has(file.collectionID))+ .map((file) => file.id),+ );+ const filtered = visibleFiles.filter(+ (file) =>+ !hiddenFileIDs.has(file.id) && !archivedFileIDs.has(file.id),+ );+ return uniqueFilesByID(filtered);+ }+ const allFiles = await savedCollectionFiles();+ // Filter out hidden and archived files to prevent leaking items users expect to remain hidden.+ const visibleFiles = allFiles.filter(isFileVisible);+ if (!activeCollection) {+ return [];+ }+ const filtered = visibleFiles.filter(+ (file) => file.collectionID === activeCollection.id,+ );+ return uniqueFilesByID(filtered);+}++// ============================================================================+// Main Component+// ============================================================================++/**+ * Main dialog component that displays a collection's photos on an interactive map+ * Responsibility: Coordinate all hooks, manage dialog state, render map layout or loading states+ */+export const CollectionMapDialog: React.FC<CollectionMapDialogProps> = ({+ open,+ onClose,+ collectionSummary,+ activeCollection,+ onRemotePull,+ onAddSaveGroup,+ onMarkTempDeleted,+ onAddFileToCollection,+ onRemoteFilesPull,+ onVisualFeedback,+ fileNormalCollectionIDs,+ collectionNameByID,+ onSelectCollection,+ onSelectPerson,+}) => {+ const { onGenericError } = useBaseContext();+ const mapComponents = useMapComponents();+ const user = useCurrentUser();+ const [isFileViewerOpen, setIsFileViewerOpen] = useState(false);+ const optimalZoom = calculateOptimalZoom();++ const {+ mapCenter,+ mapIndex,+ mapPoints,+ latestFileId,+ filesByID,+ thumbByFileID,+ isLoading,+ error,+ removeFiles: removeFilesFromMap,+ updateFileVisibility,+ queueThumbnailFetch,+ } = useMapData(open, collectionSummary, activeCollection, onGenericError);++ const {+ visiblePhotos,+ setVisiblePhotos,+ isVisiblePhotosUpdating,+ setIsVisiblePhotosUpdating,+ } = useVisiblePhotos();++ const {+ favoriteFileIDs,+ pendingFavoriteUpdates,+ pendingVisibilityUpdates,+ handleToggleFavorite,+ handleFileVisibilityUpdate,+ } = useFavorites(open, user);++ useEffect(() => {+ if (!open) {+ setIsVisiblePhotosUpdating(false);+ }+ }, [open, setIsVisiblePhotosUpdating]);++ const handleSetFileViewerOpen: Dispatch<SetStateAction<boolean>> =+ useCallback(+ (next) => {+ const nextValue =+ typeof next === "function"+ ? (next as (prev: boolean) => boolean)(isFileViewerOpen)+ : next;+ setIsFileViewerOpen(nextValue);+ },+ [isFileViewerOpen],+ );++ // Convert visible JourneyPoints to EnteFiles for FileListWithViewer+ const visibleFiles = useMemo(() => {+ return visiblePhotos+ .map((p) => filesByID.get(p.fileId))+ .filter((f): f is EnteFile => f !== undefined);+ }, [visiblePhotos, filesByID]);++ const handleRemotePull = useCallback(+ () =>+ onRemotePull ? onRemotePull({ silent: true }) : Promise.resolve(),+ [onRemotePull],+ );+ const visualFeedback = useMemo(() => onVisualFeedback, [onVisualFeedback]);++ // Empty selection state since we don't support selection in map view+ const emptySelected = useMemo<SelectedState>(+ () => ({+ ownCount: 0,+ count: 0,+ context: undefined,+ collectionID: activeCollection?.id ?? collectionSummary.id,+ }),+ [activeCollection?.id, collectionSummary.id],+ );++ /**+ * Since the map view actually doesn't support the selecting from the sidebar+ * adding a empty function, other wise the setSelection must be made optional+ * which is a more system wide change and unncessary.+ */+ const noOpSetSelected = useCallback(() => {+ /* no-op */+ }, []);++ const handleMarkTempDeleted = useCallback(+ (files: EnteFile[]) => {+ //Triggering the gallery reducer's markTempDeleted+ onMarkTempDeleted?.(files);++ //remove the deleted files from the visible photos which are shown in the sidebar+ const idsToRemove = new Set(files.map((file) => file.id));+ setVisiblePhotos((prev) =>+ prev.filter((photo) => !idsToRemove.has(photo.fileId)),+ );+ removeFilesFromMap([...idsToRemove]);+ },+ [onMarkTempDeleted, removeFilesFromMap, setVisiblePhotos],+ );++ const handleFileVisibilityUpdateWithLocalState = useCallback(+ async (file: EnteFile, visibility: ItemVisibility) => {+ await handleFileVisibilityUpdate(file, visibility);+ const updatedMagicMetadata = file.magicMetadata+ ? {+ ...file.magicMetadata,+ data: { ...file.magicMetadata.data, visibility },+ }+ : undefined;+ const updatedFile =+ updatedMagicMetadata !== undefined+ ? { ...file, magicMetadata: updatedMagicMetadata }+ : file;+ updateFileVisibility(updatedFile, visibility);+ },+ [handleFileVisibilityUpdate, updateFileVisibility],+ );++ const body = useMemo(() => {+ if (isLoading) {+ return (+ <CenteredBox>+ <ActivityIndicator size="28px" />+ </CenteredBox>+ );+ }++ if (error) {+ return (+ <CenteredBox>+ <Typography variant="body" color="text.secondary">+ {error}+ </Typography>+ </CenteredBox>+ );+ }++ // Wait for map components to load (they're dynamically imported)+ if (!mapComponents) {+ return (+ <CenteredBox>+ <ActivityIndicator size="28px" />+ </CenteredBox>+ );+ }++ if (!mapPoints.length || !mapCenter || !mapIndex) {+ return (+ <CenteredBox onClose={onClose} closeLabel={t("close")}>+ <Typography variant="body" color="text.secondary">+ {t("no_geotagged_photos")}+ </Typography>+ </CenteredBox>+ );+ }++ return (+ <MapLayout+ collectionSummary={collectionSummary}+ visiblePhotos={visiblePhotos}+ visibleFiles={visibleFiles}+ mapIndex={mapIndex}+ latestFileId={latestFileId}+ thumbByFileID={thumbByFileID}+ mapComponents={mapComponents}+ mapCenter={mapCenter}+ optimalZoom={optimalZoom}+ onClose={onClose}+ onVisiblePhotosChange={setVisiblePhotos}+ onVisiblePhotosLoadingChange={setIsVisiblePhotosUpdating}+ visiblePhotosUpdating={isVisiblePhotosUpdating}+ onPrefetchThumbnails={queueThumbnailFetch}+ user={user}+ favoriteFileIDs={favoriteFileIDs}+ pendingFavoriteUpdates={pendingFavoriteUpdates}+ pendingVisibilityUpdates={pendingVisibilityUpdates}+ onToggleFavorite={handleToggleFavorite}+ onFileVisibilityUpdate={+ handleFileVisibilityUpdateWithLocalState+ }+ onRemotePull={handleRemotePull}+ onVisualFeedback={visualFeedback}+ onAddSaveGroup={onAddSaveGroup}+ onMarkTempDeleted={handleMarkTempDeleted}+ onAddFileToCollection={onAddFileToCollection}+ onRemoteFilesPull={onRemoteFilesPull}+ fileNormalCollectionIDs={fileNormalCollectionIDs}+ collectionNameByID={collectionNameByID}+ onSelectCollection={onSelectCollection}+ onSelectPerson={onSelectPerson}+ selected={emptySelected}+ setSelected={noOpSetSelected}+ onSetOpenFileViewer={handleSetFileViewerOpen}+ />+ );+ }, [+ collectionSummary,+ emptySelected,+ error,+ favoriteFileIDs,+ handleFileVisibilityUpdateWithLocalState,+ handleRemotePull,+ handleToggleFavorite,+ visualFeedback,+ isLoading,+ mapCenter,+ mapComponents,+ mapIndex,+ mapPoints,+ latestFileId,+ noOpSetSelected,+ optimalZoom,+ onAddFileToCollection,+ onAddSaveGroup,+ onRemoteFilesPull,+ pendingFavoriteUpdates,+ pendingVisibilityUpdates,+ setIsVisiblePhotosUpdating,+ setVisiblePhotos,+ collectionNameByID,+ fileNormalCollectionIDs,+ handleMarkTempDeleted,+ onSelectCollection,+ onSelectPerson,+ thumbByFileID,+ queueThumbnailFetch,+ user,+ visibleFiles,+ visiblePhotos,+ isVisiblePhotosUpdating,+ onClose,+ handleSetFileViewerOpen,+ ]);++ return (+ <Dialog+ fullScreen+ keepMounted+ open={open}+ onClose={onClose}+ sx={{+ // When the FileViewer is open, lower this dialog's z-index below+ // PhotoSwipe's z-index (1199) so that FileViewer appears on top.+ // This avoids the visual glitch caused by closing/reopening the+ // dialog during transitions.+ ...(isFileViewerOpen && {+ zIndex: (theme) =>+ `calc(${theme.zIndex.drawer} - 2) !important`,+ }),+ }}+ >+ <Box+ sx={{+ position: "relative",+ width: "100vw",+ height: "100vh",+ bgcolor: "background.default",+ }}+ >+ <DialogContent sx={{ padding: "0 !important", height: "100%" }}>+ {body}+ </DialogContent>+ </Box>+ </Dialog>+ );+};++// ============================================================================+// Layout Components+// ============================================================================++/**+ * Main layout container for map and sidebar+ * Responsibility: Position sidebar and map canvas side-by-side+ */+interface MapLayoutProps {+ collectionSummary: CollectionSummary;+ visiblePhotos: JourneyPoint[];+ visibleFiles: EnteFile[];+ visiblePhotosUpdating: boolean;+ mapIndex: MapIndex | null;+ latestFileId: number | undefined;+ thumbByFileID: Map<number, string>;+ mapComponents: MapComponents;+ mapCenter: [number, number];+ optimalZoom: number;+ onClose: () => void;+ onVisiblePhotosChange: (photosInView: JourneyPoint[]) => void;+ onVisiblePhotosLoadingChange: (loading: boolean) => void;+ onPrefetchThumbnails: (fileIDs: number[]) => void;+ user: ReturnType<typeof useCurrentUser>;+ favoriteFileIDs: Set<number>;+ pendingFavoriteUpdates: Set<number>;+ pendingVisibilityUpdates: Set<number>;+ onToggleFavorite: (file: EnteFile) => Promise<void>;+ onFileVisibilityUpdate: (+ file: EnteFile,+ visibility: ItemVisibility,+ ) => Promise<void>;+ onRemotePull: () => Promise<void>;+ onVisualFeedback: () => void;+ onAddSaveGroup: FileListWithViewerProps["onAddSaveGroup"];+ onMarkTempDeleted?: FileListWithViewerProps["onMarkTempDeleted"];+ onAddFileToCollection?: FileListWithViewerProps["onAddFileToCollection"];+ onRemoteFilesPull?: FileListWithViewerProps["onRemoteFilesPull"];+ fileNormalCollectionIDs?: FileListWithViewerProps["fileNormalCollectionIDs"];+ collectionNameByID?: FileListWithViewerProps["collectionNameByID"];+ onSelectCollection?: FileListWithViewerProps["onSelectCollection"];+ onSelectPerson?: FileListWithViewerProps["onSelectPerson"];+ onSetOpenFileViewer?: (open: boolean) => void;+ selected: SelectedState;+ setSelected: () => void;+}++function MapLayout({+ collectionSummary,+ visiblePhotos,+ visibleFiles,+ visiblePhotosUpdating,+ mapIndex,+ latestFileId,+ thumbByFileID,+ mapComponents,+ mapCenter,+ optimalZoom,+ onClose,+ onVisiblePhotosChange,+ onVisiblePhotosLoadingChange,+ onPrefetchThumbnails,+ user,+ favoriteFileIDs,+ pendingFavoriteUpdates,+ pendingVisibilityUpdates,+ onToggleFavorite,+ onFileVisibilityUpdate,+ onRemotePull,+ onVisualFeedback,+ onAddSaveGroup,+ onMarkTempDeleted,+ onAddFileToCollection,+ onRemoteFilesPull,+ fileNormalCollectionIDs,+ collectionNameByID,+ onSelectCollection,+ onSelectPerson,+ onSetOpenFileViewer,+ selected,+ setSelected,+}: MapLayoutProps) {+ return (+ <Box sx={{ position: "relative", height: "100%", width: "100%" }}>+ <CollectionSidebar+ collectionSummary={collectionSummary}+ visibleCount={visiblePhotos.length}+ visibleFiles={visibleFiles}+ isVisiblePhotosUpdating={visiblePhotosUpdating}+ latestFileId={latestFileId}+ thumbByFileID={thumbByFileID}+ onClose={onClose}+ user={user}+ favoriteFileIDs={favoriteFileIDs}+ pendingFavoriteUpdates={pendingFavoriteUpdates}+ pendingVisibilityUpdates={pendingVisibilityUpdates}+ onToggleFavorite={onToggleFavorite}+ onFileVisibilityUpdate={onFileVisibilityUpdate}+ onRemotePull={onRemotePull}+ onVisualFeedback={onVisualFeedback}+ onAddSaveGroup={onAddSaveGroup}+ onMarkTempDeleted={onMarkTempDeleted}+ onAddFileToCollection={onAddFileToCollection}+ onRemoteFilesPull={onRemoteFilesPull}+ fileNormalCollectionIDs={fileNormalCollectionIDs}+ collectionNameByID={collectionNameByID}+ onSelectCollection={onSelectCollection}+ onSelectPerson={onSelectPerson}+ selected={selected}+ setSelected={setSelected}+ onSetOpenFileViewer={onSetOpenFileViewer}+ />+ <Box sx={{ width: "100%", height: "100%" }}>+ <MapCanvas+ mapComponents={mapComponents}+ mapCenter={mapCenter}+ mapIndex={mapIndex}+ optimalZoom={optimalZoom}+ thumbByFileID={thumbByFileID}+ onVisiblePhotosChange={onVisiblePhotosChange}+ onVisiblePhotosLoadingChange={onVisiblePhotosLoadingChange}+ onPrefetchThumbnails={onPrefetchThumbnails}+ />+ </Box>+ </Box>+ );+}++// ============================================================================+// Sidebar Components+// ============================================================================++/**+ * Sidebar displaying collection details and photo thumbnails using FileListWithViewer+ * Responsibility: Show collection cover, header, and file list with integrated viewer+ */+interface CollectionSidebarProps {+ collectionSummary: CollectionSummary;+ visibleCount: number;+ visibleFiles: EnteFile[];+ isVisiblePhotosUpdating: boolean;+ latestFileId: number | undefined;+ thumbByFileID: Map<number, string>;+ onClose: () => void;+ user: ReturnType<typeof useCurrentUser>;+ favoriteFileIDs: Set<number>;+ pendingFavoriteUpdates: Set<number>;+ pendingVisibilityUpdates: Set<number>;+ onToggleFavorite: (file: EnteFile) => Promise<void>;+ onFileVisibilityUpdate: (+ file: EnteFile,+ visibility: ItemVisibility,+ ) => Promise<void>;+ onRemotePull: () => Promise<void>;+ onVisualFeedback: () => void;+ onAddSaveGroup: FileListWithViewerProps["onAddSaveGroup"];+ onMarkTempDeleted?: FileListWithViewerProps["onMarkTempDeleted"];+ onAddFileToCollection?: FileListWithViewerProps["onAddFileToCollection"];+ onRemoteFilesPull?: FileListWithViewerProps["onRemoteFilesPull"];+ fileNormalCollectionIDs?: FileListWithViewerProps["fileNormalCollectionIDs"];+ collectionNameByID?: FileListWithViewerProps["collectionNameByID"];+ onSelectCollection?: FileListWithViewerProps["onSelectCollection"];+ onSelectPerson?: FileListWithViewerProps["onSelectPerson"];+ onSetOpenFileViewer?: (open: boolean) => void;+ selected: SelectedState;+ setSelected: () => void;+}++// Fixed height for the cover image container (px)+const COVER_IMAGE_HEIGHT = 320;+const MOBILE_SIDEBAR_HEIGHT = "50%";+// Mobile has less padding: 8px top + 12px bottom + 2px margin = 22px+// Desktop has more padding: 16px top + 16px bottom + 2px margin = 34px+// Use desktop value for consistency in the virtualized list+const COVER_HEADER_HEIGHT = COVER_IMAGE_HEIGHT + 34;++function CollectionSidebar({+ collectionSummary,+ visibleFiles,+ isVisiblePhotosUpdating,+ latestFileId,+ thumbByFileID,+ onClose,+ user,+ favoriteFileIDs,+ pendingFavoriteUpdates,+ pendingVisibilityUpdates,+ onToggleFavorite,+ onFileVisibilityUpdate,+ onRemotePull,+ onVisualFeedback,+ onAddSaveGroup,+ onMarkTempDeleted,+ onAddFileToCollection,+ onRemoteFilesPull,+ fileNormalCollectionIDs,+ collectionNameByID,+ onSelectCollection,+ onSelectPerson,+ onSetOpenFileViewer,+ selected,+ setSelected,+}: CollectionSidebarProps) {+ const [currentDate, setCurrentDate] = useState<string | undefined>(+ undefined,+ );+ const [scrollOffset, setScrollOffset] = useState(0);+ const shouldShowCover = collectionSummary.type !== "all";+ const theme = useTheme();+ const isDarkMode = theme.palette.mode === "dark";+ const isMobile = useMediaQuery(theme.breakpoints.down("md"));++ // Get cover image: prioritize collection's coverFile, fallback to first photo+ const coverFile = collectionSummary.coverFile;+ const coverImageUrl = useMemo(() => {+ const coverThumb = coverFile && thumbByFileID.get(coverFile.id);+ if (coverThumb) return coverThumb;++ const fallbackId = latestFileId;+ return fallbackId ? thumbByFileID.get(fallbackId) : undefined;+ }, [coverFile, latestFileId, thumbByFileID]);++ // Create header component for FileListWithViewer (cover scrolls with content)+ const coverHeader = useMemo(() => {+ if (!shouldShowCover) return undefined;+ return {+ component: (+ <MapCover+ name={collectionSummary.name}+ coverImageUrl={coverImageUrl}+ totalCount={collectionSummary.fileCount}+ onClose={onClose}+ />+ ),+ height: COVER_HEADER_HEIGHT,+ extendToInlineEdges: true,+ };+ }, [+ shouldShowCover,+ collectionSummary.name,+ collectionSummary.fileCount,+ coverImageUrl,+ onClose,+ ]);++ // Handle scroll events from the file list+ const handleScroll = useCallback((offset: number) => {+ setScrollOffset(offset);+ }, []);++ // Handle visible date changes from the file list+ const handleVisibleDateChange = useCallback((date: string | undefined) => {+ setCurrentDate(date);+ }, []);++ // Only show sticky date after scrolling past the cover header, or always for "All"+ const showStickyHeader =+ !shouldShowCover ||+ (scrollOffset > COVER_HEADER_HEIGHT && !!currentDate);+ const hasScrolled = scrollOffset > 0;+ const hideDateForAllNoScroll = !shouldShowCover && !hasScrolled;+ const hideDateForMobileNoScroll = isMobile && !hasScrolled;+ const visibleDate =+ currentDate && !hideDateForAllNoScroll && !hideDateForMobileNoScroll+ ? currentDate+ : undefined;++ return (+ <SidebarWrapper>+ <SidebarContainer>+ <StickyDateHeader+ visible={showStickyHeader}+ variant={shouldShowCover ? "overlay" : "static"}+ >+ <Box+ sx={{+ display: "flex",+ justifyContent: "space-between",+ alignItems: "center",+ }}+ >+ <Box>+ <Typography+ variant="body"+ sx={{ fontWeight: 700, fontSize: "18px" }}+ >+ {collectionSummary.name}+ </Typography>+ <Typography+ variant="small"+ sx={{ color: "text.muted", fontSize: "14px" }}+ >+ {t("photos_count", {+ count: collectionSummary.fileCount,+ })}+ {visibleDate && ` · ${visibleDate}`}+ </Typography>+ </Box>+ <Box+ sx={{+ display: "flex",+ alignItems: "center",+ gap: 1,+ }}+ >+ <IconButton+ onClick={onClose}+ size="small"+ sx={{+ color: "text.secondary",+ bgcolor: "fill.faint",+ "&:hover": { bgcolor: "fill.muted" },+ }}+ >+ <CloseIcon />+ </IconButton>+ </Box>+ </Box>+ </StickyDateHeader>+ <FileListContainer>+ {visibleFiles.length > 0 ? (+ <FileListWithViewer+ files={visibleFiles}+ user={user}+ favoriteFileIDs={favoriteFileIDs}+ pendingFavoriteUpdates={pendingFavoriteUpdates}+ pendingVisibilityUpdates={pendingVisibilityUpdates}+ onToggleFavorite={onToggleFavorite}+ onFileVisibilityUpdate={onFileVisibilityUpdate}+ onRemotePull={onRemotePull}+ onVisualFeedback={onVisualFeedback}+ onAddSaveGroup={onAddSaveGroup}+ onMarkTempDeleted={onMarkTempDeleted}+ onAddFileToCollection={onAddFileToCollection}+ onRemoteFilesPull={onRemoteFilesPull}+ fileNormalCollectionIDs={fileNormalCollectionIDs}+ collectionNameByID={collectionNameByID}+ onSelectCollection={onSelectCollection}+ onSelectPerson={onSelectPerson}+ enableImageEditing={false}+ enableDownload={true}+ activeCollectionID={collectionSummary.id}+ selected={selected}+ setSelected={setSelected}+ onSetOpenFileViewer={onSetOpenFileViewer}+ listBorderRadius={isMobile ? "0" : "0 0 32px 32px"}+ header={coverHeader}+ onScroll={handleScroll}+ onVisibleDateChange={handleVisibleDateChange}+ />+ ) : isVisiblePhotosUpdating ? null : (+ <EmptyState>+ {shouldShowCover && (+ <MapCover+ name={collectionSummary.name}+ coverImageUrl={coverImageUrl}+ totalCount={collectionSummary.fileCount}+ onClose={onClose}+ />+ )}+ <EmptyStateMessage>+ <Typography+ variant="body"+ sx={{ fontWeight: 600 }}+ >+ {t("no_photos_found_here")}+ </Typography>+ <Typography+ variant="small"+ color="text.secondary"+ >+ {t("zoom_out_to_see_photos")}+ </Typography>+ </EmptyStateMessage>+ </EmptyState>+ )}+ </FileListContainer>+ </SidebarContainer>+ {isDarkMode && <SidebarGradient />}+ </SidebarWrapper>+ );+}++// ============================================================================+// Map Components+// ============================================================================++/**+ * Renders the Leaflet map with markers, clusters, and controls+ * Responsibility: Display interactive map with photo markers and handle viewport changes+ */+interface MapCanvasProps {+ mapComponents: MapComponents;+ mapCenter: [number, number];+ mapIndex: MapIndex | null;+ optimalZoom: number;+ thumbByFileID: Map<number, string>;+ onVisiblePhotosChange: (photosInView: JourneyPoint[]) => void;+ onVisiblePhotosLoadingChange: (loading: boolean) => void;+ onPrefetchThumbnails: (fileIDs: number[]) => void;+}++const openStreetMapAttribution =+ '© <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener noreferrer">OpenStreetMap</a> contributors';++const leafletAttributionPrefix =+ '<a href="https://leafletjs.com" target="_blank" rel="noopener noreferrer">Leaflet</a>';++const MapCanvas = React.memo(function MapCanvas({+ mapComponents,+ mapCenter,+ mapIndex,+ optimalZoom,+ thumbByFileID,+ onVisiblePhotosChange,+ onVisiblePhotosLoadingChange,+ onPrefetchThumbnails,+}: MapCanvasProps) {+ const { MapContainer, TileLayer, Marker, useMap } = mapComponents;++ return (+ <MapCanvasContainer>+ <MapContainer+ center={mapCenter}+ zoom={optimalZoom}+ scrollWheelZoom+ zoomControl={false}+ style={{ width: "100%", height: "100%" }}+ >+ <TileLayer+ attribution={openStreetMapAttribution}+ url="https://tile.openstreetmap.org/{z}/{x}/{y}.png"+ maxZoom={MAX_MAP_ZOOM}+ updateWhenZooming+ />+ <MapControls useMap={useMap} />+ {mapIndex && (+ <MapClusters+ useMap={useMap}+ mapIndex={mapIndex}+ thumbByFileID={thumbByFileID}+ onVisiblePhotosChange={onVisiblePhotosChange}+ onVisiblePhotosLoadingChange={+ onVisiblePhotosLoadingChange+ }+ onPrefetchThumbnails={onPrefetchThumbnails}+ Marker={Marker}+ />+ )}+ </MapContainer>+ </MapCanvasContainer>+ );+});++/**+ * Floating map control buttons (open in Maps, zoom in/out)+ * Responsibility: Provide map navigation and external link controls+ */+interface MapControlsProps {+ useMap: typeof import("react-leaflet").useMap;+}++const MapControls = React.memo(function MapControls({+ useMap,+}: MapControlsProps) {+ const map = useMap();++ useEffect(() => {+ map.attributionControl.setPrefix(leafletAttributionPrefix);+ }, [map]);++ const handleOpenInMaps = useCallback(() => {+ const center = map.getCenter();+ const url = `https://www.google.com/maps?q=${center.lat},${center.lng}&z=${map.getZoom()}`;+ window.open(url, "_blank", "noopener,noreferrer");+ }, [map]);++ const handleZoomIn = useCallback(() => map.zoomIn(), [map]);+ const handleZoomOut = useCallback(() => map.zoomOut(), [map]);++ return (+ <>+ {/* Zoom controls: top left on mobile, bottom right on desktop */}+ <Stack+ spacing={1}+ sx={(theme) => ({+ position: "absolute",+ left: 24,+ top: 24,+ zIndex: 1000,+ [theme.breakpoints.up("md")]: {+ left: "auto",+ top: "auto",+ right: 24,+ bottom: 48,+ },+ })}+ >+ <FloatingIconButton onClick={handleZoomIn}>+ <AddIcon />+ </FloatingIconButton>+ <FloatingIconButton onClick={handleZoomOut}>+ <RemoveIcon />+ </FloatingIconButton>+ {/* Location button: hidden on mobile, shown in stack on desktop */}+ <FloatingIconButton+ onClick={handleOpenInMaps}+ sx={(theme) => ({+ display: "none",+ [theme.breakpoints.up("md")]: { display: "flex" },+ })}+ >+ <LocationOnIcon />+ </FloatingIconButton>+ </Stack>++ {/* Location button: top right on mobile only */}+ <FloatingIconButton+ onClick={handleOpenInMaps}+ sx={(theme) => ({+ position: "absolute",+ right: 24,+ top: 24,+ zIndex: 1000,+ [theme.breakpoints.up("md")]: { display: "none" },+ })}+ >+ <LocationOnIcon />+ </FloatingIconButton>+ </>+ );+});++interface MapClustersProps {+ useMap: typeof import("react-leaflet").useMap;+ mapIndex: MapIndex;+ thumbByFileID: Map<number, string>;+ onVisiblePhotosChange: (photosInView: JourneyPoint[]) => void;+ onVisiblePhotosLoadingChange: (loading: boolean) => void;+ onPrefetchThumbnails: (fileIDs: number[]) => void;+ Marker: typeof import("react-leaflet").Marker;+}++const MapClusters = React.memo(function MapClusters({+ useMap,+ mapIndex,+ thumbByFileID,+ onVisiblePhotosChange,+ onVisiblePhotosLoadingChange,+ onPrefetchThumbnails,+ Marker,+}: MapClustersProps) {+ const map = useMap();+ const [features, setFeatures] = useState<MapFeature[]>([]);+ const previousVisibleIdsRef = useRef<Set<number>>(new Set());+ const visibleRequestIdRef = useRef(0);+ const iconCacheRef = useRef(+ new Map<string, ReturnType<typeof createMarkerIcon>>(),+ );++ const isClusterFeature = useCallback(+ (feature: MapFeature): feature is MapClusterFeature =>+ feature.properties.cluster === true,+ [],+ );++ const updateVisibleLeaves = useCallback(+ async (+ requestId: number,+ clusters: MapFeature[],+ bounds: { contains: (latlng: [number, number]) => boolean },+ ) => {+ if (requestId !== visibleRequestIdRef.current) return;+ onVisiblePhotosLoadingChange(true);++ const inBounds = (lat: number, lng: number) =>+ bounds.contains([lat, lng]);++ const leaves: MapPointFeature[] = [];+ let processedClusters = 0;++ for (const feature of clusters) {+ if (requestId !== visibleRequestIdRef.current) return;++ if (isClusterFeature(feature)) {+ const clusterProps = feature.properties;+ const totalLeaves = clusterProps.point_count;+ const batchSize = 1000;+ for (+ let offset = 0;+ offset < totalLeaves;+ offset += batchSize+ ) {+ if (requestId !== visibleRequestIdRef.current) return;+ const clusterLeaves = mapIndex.getLeaves(+ clusterProps.cluster_id,+ batchSize,+ offset,+ );+ clusterLeaves.forEach((leaf) => {+ const [lng, lat] = leaf.geometry.coordinates;+ if (inBounds(lat, lng)) {+ leaves.push(leaf);+ }+ });+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+ processedClusters += 1;+ if (processedClusters % 5 === 0) {+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+ } else {+ const [lng, lat] = feature.geometry.coordinates;+ if (inBounds(lat, lng)) {+ leaves.push(feature);+ }+ }+ }++ if (requestId !== visibleRequestIdRef.current) return;++ leaves.sort(+ (a, b) => b.properties.timestamp - a.properties.timestamp,+ );++ const visibleIds = new Set(+ leaves.map((leaf) => leaf.properties.fileId),+ );+ const previousIds = previousVisibleIdsRef.current;+ const idsChanged =+ visibleIds.size !== previousIds.size ||+ [...visibleIds].some((id) => !previousIds.has(id));++ if (idsChanged) {+ previousVisibleIdsRef.current = visibleIds;+ const nextVisiblePhotos = leaves.map((leaf) => {+ const [lng, lat] = leaf.geometry.coordinates;+ return {+ lat,+ lng,+ name: "",+ country: "",+ timestamp: new Date(+ leaf.properties.timestamp / 1000,+ ).toISOString(),+ image: "",+ fileId: leaf.properties.fileId,+ };+ });+ startTransition(() => {+ onVisiblePhotosChange(nextVisiblePhotos);+ });+ }++ if (requestId === visibleRequestIdRef.current) {+ onVisiblePhotosLoadingChange(false);+ }+ },+ [+ isClusterFeature,+ mapIndex,+ onVisiblePhotosChange,+ onVisiblePhotosLoadingChange,+ ],+ );++ const updateClusters = useCallback(() => {+ const bounds = map.getBounds();+ const zoom = Math.round(map.getZoom());+ const bbox: [number, number, number, number] = [+ bounds.getWest(),+ bounds.getSouth(),+ bounds.getEast(),+ bounds.getNorth(),+ ];++ const nextZoom = Math.min(zoom + 1, MAX_MAP_ZOOM);+ const clusters = mapIndex.getClusters(bbox, zoom);+ setFeatures(clusters);++ const requestId = ++visibleRequestIdRef.current;+ void updateVisibleLeaves(requestId, clusters, bounds);++ const prefetchBounds = bounds.pad(PREFETCH_BOUNDS_PADDING);+ const prefetchBbox: [number, number, number, number] = [+ prefetchBounds.getWest(),+ prefetchBounds.getSouth(),+ prefetchBounds.getEast(),+ prefetchBounds.getNorth(),+ ];++ const prefetchTargets = new Set<number>();+ const collectTargets = (items: MapFeature[]) => {+ items.forEach((feature) => {+ if (isClusterFeature(feature)) {+ prefetchTargets.add(feature.properties.latestFileId);+ } else {+ prefetchTargets.add(feature.properties.fileId);+ }+ });+ };++ collectTargets(clusters);+ collectTargets(mapIndex.getClusters(prefetchBbox, nextZoom));++ if (prefetchTargets.size > 0) {+ onPrefetchThumbnails(Array.from(prefetchTargets));+ }+ }, [+ isClusterFeature,+ map,+ mapIndex,+ onPrefetchThumbnails,+ updateVisibleLeaves,+ ]);++ useEffect(() => {+ iconCacheRef.current.clear();+ previousVisibleIdsRef.current = new Set();+ visibleRequestIdRef.current += 1;+ }, [mapIndex]);++ const handleClusterClick = useCallback(+ (lat: number, lng: number, expansionZoom: number) => {+ map.setView([lat, lng], expansionZoom, { animate: true });+ },+ [map],+ );++ useEffect(() => {+ updateClusters();+ }, [updateClusters]);++ useEffect(() => {+ map.on("moveend", updateClusters);+ map.on("zoomend", updateClusters);+ return () => {+ map.off("moveend", updateClusters);+ map.off("zoomend", updateClusters);+ };+ }, [map, updateClusters]);++ const currentZoom = Math.round(map.getZoom());++ return (+ <>+ {features.map((feature) => {+ const [lng, lat] = feature.geometry.coordinates;+ const isCluster = isClusterFeature(feature);++ if (isCluster) {+ const clusterProps = feature.properties;+ const clusterId = clusterProps.cluster_id;+ const count = clusterProps.point_count;+ const expansionZoom = Math.min(+ mapIndex.getClusterExpansionZoom(clusterId),+ MAX_MAP_ZOOM,+ );+ const isInteractive = expansionZoom > currentZoom;+ const thumb =+ thumbByFileID.get(clusterProps.latestFileId) ?? "";+ const cacheKey = `cluster-${clusterId}-${count}-${thumb}-${isInteractive ? "i" : "n"}`;+ let icon = iconCacheRef.current.get(cacheKey);+ if (!icon) {+ icon = createClusterIcon(+ thumb,+ 68,+ count,+ isInteractive,+ );+ if (icon) {+ iconCacheRef.current.set(cacheKey, icon);+ }+ }+ return (+ <Marker+ key={`cluster-${clusterId}`}+ position={[lat, lng]}+ icon={icon ?? undefined}+ eventHandlers={+ isInteractive+ ? {+ click: () =>+ handleClusterClick(+ lat,+ lng,+ expansionZoom,+ ),+ }+ : undefined+ }+ />+ );+ }++ const fileId = feature.properties.fileId;+ const thumb = thumbByFileID.get(fileId) ?? "";+ const cacheKey = `point-${fileId}-${thumb}`;+ let icon = iconCacheRef.current.get(cacheKey);+ if (!icon) {+ icon = createMarkerIcon(thumb, 68);+ if (icon) {+ iconCacheRef.current.set(cacheKey, icon);+ }+ }+ return (+ <Marker+ key={`point-${fileId}`}+ position={[lat, lng]}+ icon={icon ?? undefined}+ />+ );+ })}+ </>+ );+});++// ============================================================================+// UI Components+// ============================================================================++/**+ * Styled floating action button with consistent styling+ * Responsibility: Provide consistent button styling for map controls+ */+const FloatingIconButton: React.FC<IconButtonProps> = ({ sx, ...props }) => {+ const baseSx = {+ bgcolor: (theme: {+ vars: { palette: { background: { paper: string } } };+ }) => theme.vars.palette.background.paper,+ boxShadow: (theme: { shadows: string[] }) => theme.shadows[4],+ width: 48,+ height: 48,+ borderRadius: "16px",+ transition: "transform 0.2s ease-out",+ "&:hover": {+ bgcolor: (theme: {+ vars: { palette: { background: { paper: string } } };+ }) => theme.vars.palette.background.paper,+ transform: "scale(1.05)",+ },+ };++ const mergedSx =+ sx == null+ ? baseSx+ : Array.isArray(sx)+ ? // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ [baseSx, ...sx]+ : [baseSx, sx];++ return <IconButton {...props} sx={mergedSx} />;+};++/**+ * Centered container for loading/error states with optional close button+ * Responsibility: Display centered content like loading spinners or error messages+ */+interface CenteredBoxProps extends React.PropsWithChildren {+ onClose?: () => void;+ closeLabel?: string;+}++function CenteredBox({ children, onClose, closeLabel }: CenteredBoxProps) {+ return (+ <CenteredBoxContainer>+ {onClose && (+ <IconButton+ aria-label={closeLabel ?? "Close"}+ onClick={onClose}+ sx={{ position: "absolute", top: 16, right: 16 }}+ >+ <CloseIcon />+ </IconButton>+ )}+ {children}+ </CenteredBoxContainer>+ );+}++/**+ * Empty state placeholder for when no photos are visible+ * Responsibility: Display empty state message when no photos match filters+ */+function EmptyState({ children }: React.PropsWithChildren) {+ return <EmptyStateContainer>{children}</EmptyStateContainer>;+}++// ============================================================================+// Map Cover Component+// ============================================================================++/**+ * Hero image cover for the collection with title and memory count+ * Responsibility: Display collection cover image, name, and visible memory count+ */+interface MapCoverProps {+ name: string;+ coverImageUrl: string | undefined;+ totalCount: number;+ onClose: () => void;+}++const MapCover = React.memo(function MapCover({+ name,+ coverImageUrl,+ totalCount,+ onClose,+}: MapCoverProps) {+ return (+ <CoverContainer>+ <CoverImageContainer>+ <img+ src={coverImageUrl}+ alt="Cover"+ style={{+ position: "absolute",+ inset: 0,+ width: "100%",+ height: "100%",+ objectFit: "cover",+ objectPosition: "Center",+ }}+ />+ <CoverGradientOverlay />++ <CoverCloseButton aria-label="Close" onClick={onClose}>+ <CloseIcon sx={{ fontSize: 20 }} />+ </CoverCloseButton>++ <CoverContentContainer>+ <CoverTitle>{name}</CoverTitle>+ <CoverSubtitle>+ {t("photos_count", { count: totalCount })}+ </CoverSubtitle>+ </CoverContentContainer>+ </CoverImageContainer>+ </CoverContainer>+ );+});++const MapCanvasContainer = styled(Box)(({ theme }) => ({+ width: "100%",+ height: "100%",+ [theme.breakpoints.down("md")]: {+ "& .leaflet-bottom.leaflet-right": { bottom: MOBILE_SIDEBAR_HEIGHT },+ },+}));++const CoverContainer = styled(Box)(({ theme }) => ({+ width: "100%",+ flexShrink: 0,+ paddingTop: "16px",+ paddingBottom: "16px",+ [theme.breakpoints.down("md")]: {+ padding: "8px",+ paddingTop: "20px",+ paddingBottom: "12px",+ },+}));++const CoverImageContainer = styled(Box)(({ theme }) => ({+ height: `${COVER_IMAGE_HEIGHT}px`,+ position: "relative",+ overflow: "hidden",+ backgroundColor: "#333",+ borderRadius: "36px 36px 24px 24px",+ marginTop: "2px",+ [theme.breakpoints.down("md")]: { borderRadius: "20px 20px 20px 20px" },+}));++const CoverGradientOverlay = styled(Box)({+ position: "absolute",+ inset: 0,+ background:+ "linear-gradient(to bottom, rgba(0,0,0,0.4), transparent 35%, transparent 60%, rgba(0,0,0,0.75))",+});++const CoverCloseButton = styled(IconButton)({+ position: "absolute",+ top: "12px",+ right: "12px",+ color: "white",+ backgroundColor: "rgba(0, 0, 0, 0.3)",+ "&:hover": { backgroundColor: "rgba(0, 0, 0, 0.5)" },+});++const CoverContentContainer = styled(Box)({+ position: "absolute",+ bottom: 0,+ left: 0,+ right: 0,+ padding: "24px",+ paddingLeft: "18px",+ color: "white",+});++const CoverTitle = styled(Typography)({+ fontSize: "22px",+ fontWeight: "bold",+ marginBottom: "6px",+ lineHeight: 1.2,+});++const CoverSubtitle = styled(Typography)({+ color: "rgba(255, 255, 255, 0.85)",+ fontSize: "14px",+ fontWeight: "500",+});++// ============================================================================+// Sidebar Styled Components+// ============================================================================++const SidebarWrapper = styled(Box)(({ theme }) => ({+ position: "absolute",+ left: 0,+ top: "auto",+ bottom: 0,+ right: 0,+ width: "100%",+ height: MOBILE_SIDEBAR_HEIGHT,+ zIndex: 1000,+ [theme.breakpoints.up("md")]: {+ left: 16,+ top: 16,+ bottom: 16,+ right: "auto",+ height: "auto",+ width: "30%",+ maxWidth: "600px",+ minWidth: "450px",+ },+}));++const SidebarContainer = styled(Box)(({ theme }) => ({+ position: "relative",+ width: "100%",+ height: "100%",+ backgroundColor: theme.vars.palette.background.paper,+ boxShadow: theme.shadows[10],+ display: "flex",+ flexDirection: "column",+ overflow: "hidden",+ borderRadius: "24px 24px 0 0",+ [theme.breakpoints.up("md")]: { borderRadius: "48px" },+}));++const SidebarGradient = styled(Box)(({ theme }) => ({+ position: "absolute",+ bottom: 0,+ left: 0,+ right: 0,+ height: "80px",+ background:+ "linear-gradient(to top, rgba(0,0,0,1) 0%, rgba(0,0,0,0.65) 2%, rgba(0,0,0,0) 100%)",+ pointerEvents: "none",+ borderRadius: "0",+ [theme.breakpoints.up("md")]: {+ height: "150px",+ borderRadius: "0 0 48px 48px",+ },+}));++const FileListContainer = styled(Box)(({ theme }) => ({+ flex: 1,+ minHeight: 0,+ position: "relative",+ display: "flex",+ flexDirection: "column",+ paddingLeft: "8px",+ paddingRight: "8px",+ paddingTop: "0px",+ paddingBottom: "calc(env(safe-area-inset-bottom, 0px) + 16px)",+ [theme.breakpoints.up("md")]: {+ paddingTop: "0px",+ paddingLeft: "16px",+ paddingRight: "16px",+ paddingBottom: "18px",+ },+}));++const StickyDateHeader = styled(Box)<{+ visible: boolean;+ variant: "overlay" | "static";+}>(({ theme, visible, variant }) => {+ const isStatic = variant === "static";+ return {+ position: isStatic ? "relative" : "absolute",+ top: 0,+ left: 0,+ right: 0,+ zIndex: 10,+ backgroundColor: theme.vars.palette.background.paper,+ padding: "28px 24px 24px 24px",+ borderBottom: `1px solid ${theme.vars.palette.divider}`,+ opacity: isStatic || visible ? 1 : 0,+ transform: isStatic || visible ? "translateY(0)" : "translateY(-10px)",+ pointerEvents: isStatic || visible ? "auto" : "none",+ transition: isStatic+ ? "none"+ : "opacity 0.25s ease-out, transform 0.25s ease-out",+ [theme.breakpoints.down("md")]: { padding: "24px 20px 20px 20px" },+ };+});++const CenteredBoxContainer = styled(Box)({+ width: "100%",+ height: "100%",+ minHeight: "420px",+ position: "relative",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ gap: 8,+ flexDirection: "column",+ textAlign: "center",+});++const EmptyStateContainer = styled(Box)(({ theme }) => ({+ minHeight: "100%",+ position: "relative",+ display: "flex",+ flexDirection: "column",+ alignItems: "stretch",+ justifyContent: "flex-start",+ paddingTop: 0,+ paddingBottom: theme.spacing(4),+ color: theme.vars.palette.text.secondary,+ overflow: "auto",+}));++const EmptyStateMessage = styled(Box)(({ theme }) => ({+ position: "absolute",+ top: "50%",+ left: "50%",+ transform: "translate(-50%, -50%)",+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "center",+ textAlign: "center",+ gap: theme.spacing(1),+}));diff --git a/web/apps/albums/vendor/photos/components/DownloadStatusNotifications.tsx b/web/apps/albums/vendor/photos/components/DownloadStatusNotifications.tsxnew file mode 100644index 0000000000..e7b5250a49--- /dev/null+++ b/web/apps/albums/vendor/photos/components/DownloadStatusNotifications.tsx@@ -0,0 +1,500 @@+import {+ Download01Icon,+ Loading03Icon,+ Tick02Icon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline";+import ReplayIcon from "@mui/icons-material/Replay";+import {+ Box,+ Button,+ Dialog,+ keyframes,+ styled,+ Typography,+} from "@mui/material";+import { useBaseContext } from "ente-base/context";+import {+ isSaveComplete,+ isSaveCompleteWithErrors,+ type SaveGroup,+} from "ente-gallery/components/utils/save-groups";+import { Notification } from "ente-new/photos/components/Notification";+import { t } from "i18next";+import { useState } from "react";++/** Maximum characters for album name before truncation */+const MAX_ALBUM_NAME_LENGTH = 25;+const SINGLE_FILE_SUCCESS_AUTO_CLOSE_DELAY_MS = 3000;++/** Truncate album name with ellipsis if it exceeds max length */+const truncateAlbumName = (name: string): string => {+ if (name.length <= MAX_ALBUM_NAME_LENGTH) return name;+ return name.slice(0, MAX_ALBUM_NAME_LENGTH) + "...";+};++interface DownloadStatusNotificationsProps {+ /**+ * A list of user-initiated downloads for which a status should be shown.+ *+ * An entry is added to this list when the user initiates the download, and+ * remains here until the user explicitly closes the corresponding+ * {@link Notification} component that was showing the save group's status.+ */+ saveGroups: SaveGroup[];+ /**+ * Called when the user closes the download status associated with the given+ * {@link saveGroup}.+ */+ onRemoveSaveGroup: (saveGroup: SaveGroup) => void;+ /**+ * Called when the collection summary with the given {@link collectionID}+ * should be shown. If {@link isHiddenCollectionSummary} is set, then any+ * reauthentication as appropriate before switching to the hidden section of+ * the app is performed first.+ *+ * and hidden attribute should be shown.+ *+ * This is only relevant in the context of the photos app, and can be+ * omitted by the public albums app. See the documentation of+ * {@link SaveGroup}'s {@link collectionSummaryID} property for why we don't+ * store the collection summary itself.+ */+ onShowCollectionSummary?: (+ collectionSummaryID: number | undefined,+ isHiddenCollectionSummary: boolean | undefined,+ ) => void;+ /**+ * If true, make each notification full width on mobile phones (MUI "sm"+ * and below). Tablet and desktop widths remain unchanged.+ */+ fullWidthOnMobile?: boolean;+}++/**+ * A component that shows a list of notifications, one each for an active+ * user-initiated download.+ */+export const DownloadStatusNotifications: React.FC<+ DownloadStatusNotificationsProps+> = ({+ saveGroups,+ onRemoveSaveGroup,+ onShowCollectionSummary,+ fullWidthOnMobile,+}) => {+ const { showMiniDialog } = useBaseContext();+ const fileLabel = t("file").toLowerCase();+ const [cancelDownloadGroup, setCancelDownloadGroup] =+ useState<SaveGroup | null>(null);++ const closeCancelDownloadDialog = () => setCancelDownloadGroup(null);++ const confirmCancelDownload = (group: SaveGroup) => {+ if (fullWidthOnMobile) {+ setCancelDownloadGroup(group);+ return;+ }++ showMiniDialog({+ title: t("stop_downloads_title"),+ message: t("stop_downloads_message"),+ continue: {+ text: t("yes_stop_downloads"),+ color: "critical",+ action: () => {+ group.canceller.abort();+ onRemoveSaveGroup(group);+ },+ },+ cancel: t("no"),+ });+ };++ const handleConfirmCancelDownload = () => {+ if (!cancelDownloadGroup) return;+ cancelDownloadGroup.canceller.abort();+ onRemoveSaveGroup(cancelDownloadGroup);+ closeCancelDownloadDialog();+ };++ const createOnClose = (group: SaveGroup) => () => {+ if (isSaveComplete(group)) {+ onRemoveSaveGroup(group);+ } else {+ confirmCancelDownload(group);+ }+ };++ const createOnClick = (group: SaveGroup) => () => {+ const electron = globalThis.electron;+ if (electron && group.downloadDirPath) {+ void electron.openDirectory(group.downloadDirPath);+ } else if (onShowCollectionSummary) {+ onShowCollectionSummary(+ group.collectionSummaryID,+ group.isHiddenCollectionSummary,+ );+ } else {+ return undefined;+ }+ };++ return (+ <>+ {saveGroups.map((group, index) => {+ const hasErrors = isSaveCompleteWithErrors(group);+ const isComplete = isSaveComplete(group);+ const canRetry = hasErrors && !!group.retry;+ const shouldAutoClose =+ group.total === 1 && isComplete && !hasErrors;++ // Determine if this is a ZIP download (web with multiple files or live photo)+ const isZipDownload = !group.downloadDirPath && group.total > 1;+ const shouldShowZipPart =+ isZipDownload &&+ (group.includeZipNumber || (group.currentPart ?? 1) > 1);+ const isDesktopOrSingleFile =+ !!group.downloadDirPath || group.total === 1;++ // Build the status text for the caption+ let statusText: React.ReactNode;+ if (hasErrors) {+ // Show specific error message based on failure reason+ if (group.failureReason === "network_offline") {+ statusText = t("download_failed_network_offline");+ } else if (group.failureReason === "file_error") {+ statusText = t("download_failed_file_error");+ } else {+ statusText = t("download_failed");+ }+ } else if (isComplete) {+ statusText = t("download_complete");+ } else if (shouldShowZipPart) {+ const part = group.currentPart ?? 1;+ statusText = group.isDownloadingZip+ ? t("downloading_part", { part })+ : t("preparing_part", { part });+ } else if (isZipDownload) {+ statusText = group.isDownloadingZip+ ? t("downloading")+ : t("preparing");+ } else if (isDesktopOrSingleFile) {+ statusText =+ group.total === 1+ ? t("downloading_file")+ : t("downloading_files");+ } else {+ statusText = t("downloading");+ }++ // Build caption: "Status • X / Y files"+ const completedCount = group.success + group.failed;+ const progress =+ group.total === 1+ ? `${t("processed_counts", {+ count: completedCount,+ total: group.total,+ })} ${fileLabel}`+ : t("download_progress", {+ count: completedCount,+ total: group.total,+ });+ const caption = (+ <Box+ component="span"+ sx={{+ color: hasErrors ? "white" : "text.muted",+ fontVariantNumeric: "tabular-nums",+ }}+ >+ {statusText}+ {!isComplete && (+ <>+ {" "}+ {"\u2022"} {progress}+ </>+ )}+ </Box>+ );++ // Determine the start icon based on state+ let startIcon: React.ReactNode;+ if (hasErrors) {+ startIcon = <ErrorOutlineIcon />;+ } else if (isComplete) {+ startIcon = (+ <GlowingIconWrapper>+ <HugeiconsIcon icon={Tick02Icon} size={28} />+ </GlowingIconWrapper>+ );+ } else if (isZipDownload && !group.isDownloadingZip) {+ // Preparing state - use loading icon+ startIcon = <SpinningIcon />;+ } else {+ // Downloading state+ startIcon = (+ <DroppingIconWrapper>+ <HugeiconsIcon icon={Download01Icon} size={28} />+ </DroppingIconWrapper>+ );+ }++ // Title is always the album name (truncated)+ const filesCountTitle = t("files_count", {+ count: group.total,+ });+ const title =+ group.total === 1 && group.title === filesCountTitle+ ? `${group.total} ${fileLabel}`+ : group.title;+ const truncatedName = truncateAlbumName(title);++ return (+ <Notification+ key={group.id}+ horizontal="left"+ sx={(theme) => ({+ "&&": { bottom: `${index * 80 + 20}px` },+ width: "min(400px, 100vw)",+ borderRadius: "20px",+ "& .MuiButton-root": {+ borderRadius: "20px",+ padding: "16px 16px 16px 20px",+ },+ "& .MuiIconButton-root": {+ width: "40px",+ height: "40px",+ "& svg": { fontSize: "22px" },+ },+ [theme.breakpoints.down("sm")]: {+ "&&": {+ bottom: `${index * 70 + 16}px`,+ ...(fullWidthOnMobile+ ? { left: "8px" }+ : {}),+ },+ width: fullWidthOnMobile+ ? "calc(100vw - 16px)"+ : "min(340px, calc(100vw - 16px))",+ borderRadius: "16px",+ "& .MuiButton-root": {+ borderRadius: "16px",+ padding: "12px 12px 12px 16px",+ },+ "& .MuiIconButton-root": {+ width: "36px",+ height: "36px",+ "& svg": { fontSize: "20px" },+ },+ },+ })}+ open={true}+ onClose={createOnClose(group)}+ autoHideDuration={+ shouldAutoClose+ ? SINGLE_FILE_SUCCESS_AUTO_CLOSE_DELAY_MS+ : undefined+ }+ keepOpenOnClick+ attributes={{+ color: hasErrors ? "critical" : "secondary",+ startIcon,+ title: truncatedName,+ caption,+ onClick: createOnClick(group),+ endIcon: canRetry ? (+ <ReplayIcon+ titleAccess={t("retry")}+ sx={{ color: "white" }}+ />+ ) : undefined,+ onEndIconClick: canRetry+ ? () => group.retry?.()+ : undefined,+ }}+ />+ );+ })}++ {fullWidthOnMobile && (+ <StyledStopDownloadDialog+ open={!!cancelDownloadGroup}+ onClose={closeCancelDownloadDialog}+ >+ <StopDownloadDialogWrapper>+ <StopDownloadTitleSection>+ <Typography+ sx={{+ fontWeight: 600,+ fontSize: 24,+ lineHeight: "28px",+ letterSpacing: "-0.48px",+ textAlign: "center",+ }}+ >+ {t("stop_downloads_title")}+ </Typography>+ <StopDownloadSubtitle>+ {t("stop_downloads_message")}+ </StopDownloadSubtitle>+ </StopDownloadTitleSection>+ <StopDownloadButtonsSection>+ <StopDownloadPrimaryButton+ fullWidth+ onClick={handleConfirmCancelDownload}+ >+ {t("yes_stop_downloads")}+ </StopDownloadPrimaryButton>+ <StopDownloadSecondaryButton+ fullWidth+ onClick={closeCancelDownloadDialog}+ >+ {t("no")}+ </StopDownloadSecondaryButton>+ </StopDownloadButtonsSection>+ </StopDownloadDialogWrapper>+ </StyledStopDownloadDialog>+ )}+ </>+ );+};++const StyledStopDownloadDialog = styled(Dialog)(({ theme }) => ({+ "& .MuiDialog-paper": {+ width: 381,+ maxWidth: "calc(100% - 32px)",+ borderRadius: 28,+ backgroundColor: "#fff",+ padding: 0,+ margin: 16,+ boxShadow: "none",+ border: "1px solid #E0E0E0",+ ...theme.applyStyles("dark", {+ backgroundColor: "#1b1b1b",+ border: "1px solid rgba(255, 255, 255, 0.18)",+ }),+ },+ "& .MuiBackdrop-root": { backgroundColor: "rgba(0, 0, 0, 0.5)" },+}));++const StopDownloadDialogWrapper = styled(Box)(() => ({+ padding: "40px 16px 16px 16px",+}));++const StopDownloadTitleSection = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "center",+ gap: 9,+ textAlign: "center",+ marginBottom: 36,+}));++const StopDownloadButtonsSection = styled(Box)(() => ({+ width: "100%",+ display: "flex",+ flexDirection: "column",+ gap: 12,+}));++const StopDownloadSubtitle = styled(Typography)(({ theme }) => ({+ fontWeight: 500,+ fontSize: 14,+ lineHeight: "20px",+ color: "#666666",+ maxWidth: 295,+ textAlign: "center",+ marginInline: "auto",+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.7)" }),+}));++const StopDownloadSecondaryButton = styled(Button)(({ theme }) => ({+ display: "flex",+ padding: "20px 16px",+ justifyContent: "center",+ alignItems: "center",+ gap: 8,+ borderRadius: 20,+ backgroundColor: "rgba(0, 0, 0, 0.04)",+ border: "none",+ fontSize: 16,+ fontWeight: 500,+ textTransform: "none",+ color: "#000",+ "&:hover": { backgroundColor: "rgba(0, 0, 0, 0.08)", border: "none" },+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.08)",+ color: "#fff",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.12)" },+ }),+}));++const StopDownloadPrimaryButton = styled(Button)(({ theme }) => ({+ display: "flex",+ padding: "20px 16px",+ justifyContent: "center",+ alignItems: "center",+ gap: 8,+ borderRadius: 20,+ backgroundColor: theme.vars.palette.critical.main,+ fontSize: 16,+ fontWeight: 500,+ textTransform: "none",+ color: theme.vars.palette.critical.contrastText,+ "&:hover": { backgroundColor: theme.vars.palette.critical.dark },+}));++/** CSS keyframes for spinning animation */+const spinAnimation = keyframes`+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+`;++/** CSS keyframes for drop from top animation */+const dropAnimation = keyframes`+ 0% { transform: translateY(-100%); opacity: 0.15; }+ 50% { transform: translateY(10%); opacity: 0.6; }+ 100% { transform: translateY(0); opacity: 1; }+`;++/** CSS keyframes for green glow animation */+const glowAnimation = keyframes`+ 0% { color: var(--mui-palette-fixed-success); }+ 100% { color: inherit; }+`;++/** CSS keyframes for fade in animation */+const fadeInAnimation = keyframes`+ 0% { opacity: 0; }+ 100% { opacity: 1; }+`;++/** Drop animation icon wrapper */+const DroppingIconWrapper = styled("span")`+ display: inline-flex;+ animation: ${dropAnimation} 0.8s ease-out forwards;+`;++/** Glowing icon wrapper for success state */+const GlowingIconWrapper = styled("span")`+ display: inline-flex;+ animation: ${glowAnimation} 2s ease-out forwards;+`;++/** Spinning loading icon wrapper */+const SpinningIconWrapper = styled("span")`+ display: inline-flex;+ animation:+ ${fadeInAnimation} 0.5s ease-out forwards,+ ${spinAnimation} 3s linear infinite;+`;++/** Spinning loading icon */+const SpinningIcon: React.FC = () => (+ <SpinningIconWrapper>+ <HugeiconsIcon icon={Loading03Icon} size={28} />+ </SpinningIconWrapper>+);diff --git a/web/apps/albums/vendor/photos/components/FileList.tsx b/web/apps/albums/vendor/photos/components/FileList.tsxnew file mode 100644index 0000000000..9819a6acd8--- /dev/null+++ b/web/apps/albums/vendor/photos/components/FileList.tsx@@ -0,0 +1,2143 @@+import AlbumOutlinedIcon from "@mui/icons-material/AlbumOutlined";+import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";+import PlayArrowRoundedIcon from "@mui/icons-material/PlayArrowRounded";+import PlayCircleOutlineOutlinedIcon from "@mui/icons-material/PlayCircleOutlineOutlined";+import { Box, Checkbox, Fab, Typography, styled } from "@mui/material";+import Avatar from "components/Avatar";+import type { LocalUser } from "ente-accounts/services/user";+import { assertionFailed } from "ente-base/assert";+import { Overlay } from "ente-base/components/containers";+import { formattedDateRelative } from "ente-base/i18n-date";+import log from "ente-base/log";+import { downloadManager } from "ente-gallery/services/download";+import type { EnteFile } from "ente-media/file";+import { fileDurationString } from "ente-media/file-metadata";+import { FileType } from "ente-media/file-type";+import {+ FileContextMenu,+ type ContextMenuPosition,+} from "ente-new/photos/components/FileContextMenu";+import type { GalleryBarMode } from "ente-new/photos/components/gallery/reducer";+import { StarIcon } from "ente-new/photos/components/icons/StarIcon";+import {+ LoadingThumbnail,+ StaticThumbnail,+} from "ente-new/photos/components/PlaceholderThumbnails";+import { TileBottomTextOverlay } from "ente-new/photos/components/Tiles";+import {+ computeThumbnailGridLayoutParams,+ thumbnailGap,+ type ThumbnailGridLayoutParams,+} from "ente-new/photos/components/utils/thumbnail-grid-layout";+import {+ PseudoCollectionID,+ type CollectionSummary,+} from "ente-new/photos/services/collection-summary";+import {+ getAvailableFileActions,+ type FileContextAction,+} from "ente-new/photos/utils/file-actions";+import { batch } from "ente-utils/array";+import { t } from "i18next";+import React, {+ memo,+ useCallback,+ useDeferredValue,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import {+ VariableSizeList,+ areEqual,+ type ListChildComponentProps,+} from "react-window";+import { type SelectedState } from "utils/file";+import {+ handleSelectCreator,+ handleSelectCreatorMulti,+} from "utils/photoFrame";++/**+ * 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;+ }[];+ }+ | {+ 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;+}++/**+ * A file augmented with the date when it will be permanently deleted.+ *+ * See: [Note: Files in trash pseudo collection have deleteBy]+ */+export type EnteTrashFile = EnteFile & {+ /**+ * Timestamp (epoch microseconds) when the trash item (and its corresponding+ * {@link EnteFile}) will be permanently deleted.+ */+ deleteBy?: number;+};++interface MasonryLayoutItem {+ file: EnteFile;+ fileIndex: number;+ left: number;+ top: number;+ bottom: number;+ width: number;+ height: number;+}++interface MasonryLayout {+ items: MasonryLayoutItem[];+ rows: MasonryLayoutItem[][];+ totalHeight: number;+}++interface MasonrySourceItem {+ file: EnteFile;+ fileIndex: number;+ aspectRatio: number;+}++interface Dimensions {+ width: number;+ height: number;+}++export interface FileListProps {+ /** The height we should occupy (needed since the list is virtualized). */+ height: number;+ /** The width we should occupy.*/+ width: number;+ /**+ * Optional border radius to apply to the scrollable list container.+ */+ listBorderRadius?: string;+ /**+ * The files to show, annotated with cached precomputed properties that are+ * frequently needed by the {@link FileList}.+ */+ annotatedFiles: FileListAnnotatedFile[];+ mode?: GalleryBarMode;+ /**+ * This is an experimental prop, to see if we can merge the separate+ * "isInSearchMode" state kept by the gallery to be instead provided as a+ * another mode in which the gallery operates.+ */+ modePlus?: GalleryBarMode | "search";+ /**+ * 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;+ /**+ * The logged in user, if any.+ *+ * This is only expected to be present when the listing is shown within the+ * photos app, where we have a logged in user. The public albums app can+ * omit this prop.+ */+ user?: LocalUser;+ /**+ * If `true`, then the default behaviour of grouping files by their date is+ * suppressed.+ *+ * This behaviour is used when showing magic search results.+ */+ disableGrouping?: boolean;+ /**+ * 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;+ /** This will be set if mode is not "people". */+ activeCollectionID: number;+ /** This will be set if mode is "people". */+ activePersonID?: string | undefined;+ /**+ * File IDs of all the files that the user has marked as a favorite.+ *+ * Not set in the context of the shared albums app.+ */+ favoriteFileIDs?: Set<number>;+ /**+ * A map from known Ente user IDs to their emails.+ *+ * This is only expected in the context of the photos app, and will be+ * omitted when running in the public albums app.+ */+ emailByUserID?: Map<number, string>;+ /**+ * 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;+ /**+ * Called when the list scrolls, providing the current scroll offset.+ */+ onScroll?: (scrollOffset: number) => void;+ /**+ * Called when the visible date at the top of the viewport changes.+ */+ onVisibleDateChange?: (date: string | undefined) => void;+ /**+ * The collection summary for the current view.+ *+ * Used to determine available context menu actions.+ */+ collectionSummary?: CollectionSummary;+ /**+ * Called when a context menu action is triggered on a file.+ *+ * @param action The action that was triggered.+ */+ onContextMenuAction?: (+ action: FileContextAction,+ targetFile?: EnteFile,+ meta?: { isEphemeralSingleSelection: boolean },+ ) => void;+ /**+ * Whether to show the "Add Person" action in the context menu.+ */+ showAddPersonAction?: boolean;+ /**+ * Whether to show the "Edit Location" action in the context menu.+ */+ showEditLocationAction?: boolean;+ /**+ * Called when the context menu opens or closes.+ */+ onContextMenuOpenChange?: (open: boolean) => void;+ /**+ * Hide selection visuals/interactions while keeping selection data.+ */+ suppressSelectionUI?: boolean;+}++/**+ * A virtualized list of files, each represented by their thumbnail.+ */+export const FileList: React.FC<FileListProps> = ({+ height,+ width,+ listBorderRadius,+ mode,+ modePlus,+ layout = "grid",+ header,+ footer,+ user,+ annotatedFiles,+ disableGrouping,+ enableSelect,+ selected,+ setSelected,+ activeCollectionID,+ activePersonID,+ favoriteFileIDs,+ emailByUserID,+ onItemClick,+ onScroll,+ onVisibleDateChange,+ collectionSummary,+ onContextMenuAction,+ showAddPersonAction,+ showEditLocationAction,+ onContextMenuOpenChange,+ suppressSelectionUI = false,+}) => {+ const [_items, setItems] = useState<FileListItem[]>([]);+ const items = useDeferredValue(_items);++ const [rangeStartIndex, setRangeStartIndex] = useState<number | undefined>(+ undefined,+ );+ const [hoverIndex, setHoverIndex] = useState<number | undefined>(undefined);+ const [isShiftKeyPressed, setIsShiftKeyPressed] = useState(false);+ const [masonryScrollTop, setMasonryScrollTop] = useState(0);+ const [masonryIsScrolling, setMasonryIsScrolling] = useState(false);+ 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>());+ // Show back-to-top button when scrolled past threshold+ const [showBackToTop, setShowBackToTop] = useState(false);++ // Context menu state+ const [contextMenu, setContextMenu] = useState<{+ position: ContextMenuPosition;+ file: EnteFile;+ fileIndex: number;+ } | null>(null);++ // Track selection state before right-click modified it.+ // If there are already 3 files explicitly selected via checkmarks,+ // right-clicking an unselected item will store the previous selections+ // in this ref and temporarily select only the right-clicked file.+ // If no action is taken from the context menu, the previous selection+ // is restored when the menu closes.+ const previousSelectionRef = useRef<SelectedState | null>(null);+ // Track whether an action was taken from the context menu.+ // This ref works in conjunction with previousSelectionRef: if an action+ // is taken, the previous selection is not reverted when the context menu closes.+ const contextMenuActionTakenRef = useRef(false);++ const listRef = useRef<VariableSizeList | null>(null);+ const outerRef = useRef<HTMLDivElement | null>(null);++ const layoutParams = useMemo(+ () => computeThumbnailGridLayoutParams(width),+ [width],+ );+ const shouldUseMasonry = layout === "masonry";++ useEffect(() => {+ if (shouldUseMasonry) {+ setItems([]);+ 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;+ if (disableGrouping) {+ items = items.concat(+ batch(annotatedFiles, columns).map(+ (batchFiles, batchIndex) => ({+ height: fileItemHeight,+ type: "file",+ groups: [+ {+ annotatedFiles: batchFiles,+ annotatedFilesStartIndex: batchIndex * columns,+ },+ ],+ }),+ ),+ );+ } else {+ // 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[][]) =>+ ({+ height: fileItemHeight,+ type: "file",+ groups: splits.map((split) => {+ const group = {+ annotatedFiles: split,+ annotatedFilesStartIndex: fileIndex,+ };+ fileIndex += split.length;+ return group;+ }),+ }) satisfies FileListItem;++ 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",+ groups: splits.map((s) => ({+ date: s[0]!.timelineDateString,+ dateSpan: s.length,+ })),+ });+ 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",+ groups: splits.map((s) => ({+ date: s[0]!.timelineDateString,+ dateSpan: columns,+ })),+ });+ items = items.concat(+ batch(splits[0]!, columns).map((batchFiles) =>+ createFileItem([batchFiles]),+ ),+ );+ }+ };++ const spaceBetweenDatesToImageContainerWidthRatio = 0.244;++ let pendingSplits = new Array<FileListAnnotatedFile[]>();+ for (const split of splitByDate(annotatedFiles)) {+ const filledColumns = pendingSplits.reduce(+ (a, s) => a + s.length,+ 0,+ );+ const incomingColumns = split.length;++ // Check if the files in this split can be added to same row.+ if (+ !isSmallerLayout &&+ filledColumns ++ incomingColumns ++ Math.ceil(+ pendingSplits.length *+ spaceBetweenDatesToImageContainerWidthRatio,+ ) <=+ columns+ ) {+ pendingSplits.push(split);+ continue;+ }++ if (pendingSplits.length) pushItemsFromSplits(pendingSplits);+ pendingSplits = [split];+ }+ if (pendingSplits.length) pushItemsFromSplits(pendingSplits);+ }++ if (!annotatedFiles.length) {+ items.push({+ height: height - 48,+ type: "span",+ component: (+ <NoFilesListItem>+ <Typography sx={{ color: "text.faint" }}>+ {t("nothing_here")}+ </Typography>+ </NoFilesListItem>+ ),+ });+ }++ let leftoverHeight = height - (footer?.height ?? 0);+ for (const item of items) {+ leftoverHeight -= item.height;+ if (leftoverHeight <= 0) break;+ }+ if (leftoverHeight > 0) {+ items.push({+ height: leftoverHeight,+ type: "span",+ component: <></>,+ });+ }++ if (footer) items.push(asFullSpanFileListItem(footer));++ setItems(items);+ }, [+ width,+ height,+ header,+ footer,+ annotatedFiles,+ disableGrouping,+ shouldUseMasonry,+ layoutParams,+ ]);++ useEffect(() => {+ // Refresh list+ listRef.current?.resetAfterIndex(0);+ }, [items]);++ useEffect(() => {+ const notSelectedFiles = annotatedFiles.filter(+ (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;+ });+ }, [annotatedFiles, selected]);++ const handleSelectMulti = useMemo(+ () =>+ handleSelectCreatorMulti(+ setSelected,+ mode,+ user?.id,+ activeCollectionID,+ activePersonID,+ ),+ [setSelected, mode, user?.id, activeCollectionID, activePersonID],+ );++ const onChangeSelectAllCheckBox = useCallback(+ (date: string) => {+ const next = new Set(checkedTimelineDateStrings);+ let isDateSelected: boolean;+ if (!next.has(date)) {+ next.add(date);+ isDateSelected = true;+ } else {+ next.delete(date);+ isDateSelected = false;+ }+ setCheckedTimelineDateStrings(next);++ // All files on a checked/unchecked day.+ const filesOnADay = annotatedFiles.filter(+ (af) => af.timelineDateString === date,+ );++ handleSelectMulti(filesOnADay.map((af) => af.file))(isDateSelected);+ },+ [annotatedFiles, checkedTimelineDateStrings, handleSelectMulti],+ );++ const handleSelect = useMemo(+ () =>+ handleSelectCreator(+ setSelected,+ mode,+ user?.id,+ activeCollectionID,+ activePersonID,+ setRangeStartIndex,+ ),+ [setSelected, mode, user?.id, activeCollectionID, activePersonID],+ );++ const isSelectionContextMatching = useMemo(() => {+ if (!mode) return selected.collectionID === activeCollectionID;+ if (mode !== selected.context?.mode) return false;+ if (selected.context.mode === "people") {+ return selected.context.personID === activePersonID;+ }+ return selected.context.collectionID === activeCollectionID;+ }, [activeCollectionID, activePersonID, mode, selected]);++ const isFileSelected = useCallback(+ (file: EnteFile) => {+ if (suppressSelectionUI) return false;+ return isSelectionContextMatching && !!selected[file.id];+ },+ [isSelectionContextMatching, selected, suppressSelectionUI],+ );++ const haveSelection = !suppressSelectionUI && selected.count > 0;++ const handleRangeSelect = useCallback(+ (index: number) => {+ if (rangeStartIndex === undefined || rangeStartIndex == index)+ return;++ const direction = index > rangeStartIndex ? 1 : -1;+ let checked = true;+ for (+ let i = rangeStartIndex;+ (index - i) * direction >= 0;+ i += direction+ ) {+ checked = checked && !!selected[annotatedFiles[i]!.file.id];+ }+ for (+ let i = rangeStartIndex;+ (index - i) * direction > 0;+ i += direction+ ) {+ handleSelect(annotatedFiles[i]!.file)(!checked);+ }+ handleSelect(annotatedFiles[index]!.file, index)(!checked);+ },+ [annotatedFiles, selected, rangeStartIndex, handleSelect],+ );++ useEffect(() => {+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key == "Shift") {+ setIsShiftKeyPressed(true);+ }+ };++ const handleKeyUp = (e: KeyboardEvent) => {+ if (e.key == "Shift") {+ setIsShiftKeyPressed(false);+ }+ };++ document.addEventListener("keydown", handleKeyDown);+ document.addEventListener("keyup", handleKeyUp);++ return () => {+ document.removeEventListener("keydown", handleKeyDown);+ document.removeEventListener("keyup", handleKeyUp);+ };+ }, []);++ useEffect(() => {+ if (selected.count == 0) setRangeStartIndex(undefined);+ }, [selected]);++ const selectedFavoriteCount = useMemo(() => {+ if (!favoriteFileIDs || selected.count == 0) return 0;+ let count = 0;+ for (const [key, value] of Object.entries(selected)) {+ if (typeof value === "boolean" && value) {+ if (favoriteFileIDs.has(Number(key))) {+ count += 1;+ }+ }+ }+ return count;+ }, [favoriteFileIDs, selected]);++ // Compute available context menu actions based on stable context and+ // the favorite status of the current selection (for toggling).+ const contextMenuActions = useMemo(() => {+ if (!onContextMenuAction) return [];+ const actions = getAvailableFileActions({+ barMode: mode,+ isInSearchMode: modePlus === "search",+ collectionSummary,+ showAddPerson: !!showAddPersonAction,+ showEditLocation: !!showEditLocationAction && selected.ownCount > 0,+ showSendLink: selected.ownCount > 0,+ });+ if (!actions.includes("favorite")) return actions;+ if (+ selectedFavoriteCount > 0 &&+ selectedFavoriteCount < selected.count+ ) {+ return actions.filter(+ (action) => action !== "favorite" && action !== "unfavorite",+ );+ }+ if (selectedFavoriteCount === selected.count && selected.count > 0) {+ return actions.map((action) =>+ action === "favorite" ? "unfavorite" : action,+ );+ }+ return actions;+ }, [+ onContextMenuAction,+ mode,+ modePlus,+ collectionSummary,+ showAddPersonAction,+ showEditLocationAction,+ selected.ownCount,+ selectedFavoriteCount,+ selected.count,+ ]);++ // Handle context menu open+ const handleContextMenu = useCallback(+ (event: React.MouseEvent, file: EnteFile, fileIndex: number) => {+ if (!onContextMenuAction) return;++ event.preventDefault();+ event.stopPropagation();++ // Reset tracking for this menu open.+ previousSelectionRef.current = null;+ contextMenuActionTakenRef.current = false;++ // Handle selection behavior on right-click+ if (!selected[file.id]) {+ // Store current selection before replacing it+ previousSelectionRef.current = { ...selected };++ // File not selected: clear selection and select only this file+ const isOwnFile = file.ownerID === user?.id;+ const context =+ mode === "people" && activePersonID+ ? { mode: "people" as const, personID: activePersonID }+ : {+ mode: (mode ?? "albums") as+ | "albums"+ | "hidden-albums",+ collectionID: activeCollectionID,+ };+ setSelected({+ [file.id]: true,+ ownCount: isOwnFile ? 1 : 0,+ count: 1,+ collectionID: activeCollectionID,+ context,+ });+ }+ // If file is already selected, keep current multi-selection++ setContextMenu({+ position: { top: event.clientY, left: event.clientX },+ file,+ fileIndex,+ });+ onContextMenuOpenChange?.(true);+ },+ [+ onContextMenuAction,+ onContextMenuOpenChange,+ selected,+ setSelected,+ user,+ activeCollectionID,+ activePersonID,+ mode,+ ],+ );++ // Handle context menu close+ const handleContextMenuClose = useCallback(() => {+ // Defer restore so a menu-item click can mark the close as action-driven.+ void Promise.resolve().then(() => {+ if (+ !contextMenuActionTakenRef.current &&+ previousSelectionRef.current+ ) {+ setSelected(previousSelectionRef.current);+ }+ previousSelectionRef.current = null;+ contextMenuActionTakenRef.current = false;+ });++ setContextMenu(null);+ onContextMenuOpenChange?.(false);+ }, [onContextMenuOpenChange, setSelected]);++ const handleContextMenuActionWithTracking = useCallback(+ (action: FileContextAction) => {+ const isEphemeralSingleSelection =+ selected.count === 1 &&+ previousSelectionRef.current?.count === 0;+ contextMenuActionTakenRef.current = true;+ onContextMenuAction?.(action, contextMenu?.file, {+ isEphemeralSingleSelection,+ });+ },+ [onContextMenuAction, contextMenu, selected.count],+ );++ const renderListItem = useCallback(+ (item: FileListItem, isScrolling: boolean) => {+ const haveSelection =+ !!enableSelect && !suppressSelectionUI && selected.count > 0;+ const showGroupCheckbox =+ haveSelection && !(contextMenu && selected.count === 1);+ switch (item.type) {+ case "date":+ return intersperseWithGaps(+ item.groups,+ ({ date, dateSpan }) => [+ <DateListItem key={date} span={dateSpan}>+ {showGroupCheckbox && (+ <Checkbox+ key={date}+ name={date}+ checked={checkedTimelineDateStrings.has(+ date,+ )}+ onChange={() =>+ onChangeSelectAllCheckBox(date)+ }+ size="small"+ sx={{ pl: 0 }}+ />+ )}+ {date}+ </DateListItem>,+ ],+ ({ date }) => <div key={`${date}-gap`} />,+ );+ case "file":+ return intersperseWithGaps(+ item.groups,+ ({ annotatedFiles, annotatedFilesStartIndex }) =>+ annotatedFiles.map((annotatedFile, j) => {+ const file = annotatedFile.file;+ const index = annotatedFilesStartIndex + j;+ return (+ <FileThumbnail+ key={`tile-${file.id}-selected-${selected[file.id] ?? false}`}+ {...{+ user,+ emailByUserID,+ enableSelect:+ !!enableSelect &&+ !suppressSelectionUI,+ }}+ file={file}+ selected={isFileSelected(file)}+ selectOnClick={haveSelection}+ isRangeSelectActive={+ isShiftKeyPressed && haveSelection+ }+ isInSelectRange={+ rangeStartIndex !== undefined &&+ hoverIndex !== undefined &&+ ((index >= rangeStartIndex &&+ index <= hoverIndex) ||+ (index >= hoverIndex &&+ index <= rangeStartIndex))+ }+ activeCollectionID={activeCollectionID}+ showPlaceholder={isScrolling}+ isFav={!!favoriteFileIDs?.has(file.id)}+ onClick={() => onItemClick(index)}+ onSelect={handleSelect(file, index)}+ onHover={() => setHoverIndex(index)}+ onRangeSelect={() =>+ handleRangeSelect(index)+ }+ onContextMenu={+ onContextMenuAction+ ? (e) =>+ handleContextMenu(+ e,+ file,+ index,+ )+ : undefined+ }+ />+ );+ }),+ ({ annotatedFilesStartIndex }) => (+ <div key={`${annotatedFilesStartIndex}-gap`} />+ ),+ );+ case "span":+ return item.component;+ }+ },+ [+ activeCollectionID,+ checkedTimelineDateStrings,+ contextMenu,+ emailByUserID,+ favoriteFileIDs,+ haveSelection,+ handleContextMenu,+ handleRangeSelect,+ handleSelect,+ hoverIndex,+ isShiftKeyPressed,+ isFileSelected,+ onChangeSelectAllCheckBox,+ onContextMenuAction,+ onItemClick,+ rangeStartIndex,+ enableSelect,+ selected,+ suppressSelectionUI,+ user,+ ],+ );++ const itemData = useMemo(+ () => ({ items, layoutParams, renderListItem }),+ [items, layoutParams, renderListItem],+ );++ const itemSize = useCallback(+ (index: number) => itemData.items[index]!.height,+ [itemData],+ );++ const itemKey = useCallback((index: number, itemData: FileListItemData) => {+ const item = itemData.items[index]!;+ switch (item.type) {+ case "date":+ return `date-${item.groups[0]!.date}-${index}`;+ case "file":+ return `file-${item.groups[0]!.annotatedFilesStartIndex}-${index}`;+ case "span":+ return `span-${index}`;+ }+ }, []);++ // Track the last reported date to avoid unnecessary callbacks+ const lastVisibleDateRef = useRef<string | undefined>(undefined);++ const handleScroll = useCallback(+ ({ scrollOffset }: { scrollOffset: number }) => {+ onScroll?.(scrollOffset);++ // Show back-to-top button when scrolled past threshold+ setShowBackToTop(scrollOffset > 500);++ // Calculate which date is visible at the current scroll position+ if (onVisibleDateChange && items.length > 0) {+ let cumulativeHeight = 0;+ let currentDate: string | undefined;++ for (const item of items) {+ if (item.type === "date") {+ currentDate = item.groups[0]?.date;+ }+ cumulativeHeight += item.height;+ // Found the item that contains the scroll position+ if (cumulativeHeight > scrollOffset) {+ break;+ }+ }++ // Only call callback if date changed+ if (currentDate !== lastVisibleDateRef.current) {+ lastVisibleDateRef.current = currentDate;+ onVisibleDateChange(currentDate);+ }+ }+ },+ [onScroll, onVisibleDateChange, items],+ );++ const masonryTargetRowHeight = useMemo(+ () => preferredMasonryRowHeight(layoutParams.containerWidth),+ [layoutParams.containerWidth],+ );+ const masonryInnerWidth = useMemo(+ () => Math.max(0, width - 2 * layoutParams.paddingInline),+ [layoutParams.paddingInline, width],+ );+ const masonryLayout = useMemo<MasonryLayout>(() => {+ if (+ !shouldUseMasonry ||+ masonryTargetRowHeight <= 0 ||+ masonryInnerWidth <= 0 ||+ !annotatedFiles.length+ ) {+ return { items: [], rows: [], totalHeight: 0 };+ }++ const rows = new Array<MasonryLayoutItem[]>();+ const items: MasonryLayoutItem[] = [];+ const masonrySourceItems = new Array<MasonrySourceItem>();+ let rowTop = 0;+ let currentRow = new Array<MasonrySourceItem>();+ let currentRowAspectRatio = 0;+ const useAdaptiveMobileRows = shouldUseAdaptiveMobileMasonryRows(+ layoutParams.containerWidth,+ );++ const placeCurrentRow = (fitToWidth: boolean) => {+ if (!currentRow.length || currentRowAspectRatio <= 0) return;+ const totalGapWidth = (currentRow.length - 1) * layoutParams.gap;+ const maxContentWidth = Math.max(+ 1,+ masonryInnerWidth - totalGapWidth,+ );+ const naturalRowHeight = Math.max(+ 1,+ maxContentWidth / currentRowAspectRatio,+ );+ const rowHeight = fitToWidth+ ? naturalRowHeight+ : Math.min(masonryTargetRowHeight, naturalRowHeight);+ const row = new Array<MasonryLayoutItem>();+ let left = 0;++ for (const { file, fileIndex, aspectRatio } of currentRow) {+ const itemWidth = Math.max(1, rowHeight * aspectRatio);+ const item = {+ file,+ fileIndex,+ top: rowTop,+ bottom: rowTop + rowHeight,+ left,+ width: itemWidth,+ height: rowHeight,+ } satisfies MasonryLayoutItem;+ items.push(item);+ row.push(item);+ left += itemWidth + layoutParams.gap;+ }++ rows.push(row);+ rowTop += rowHeight + layoutParams.gap;+ currentRow = [];+ currentRowAspectRatio = 0;+ };++ for (const [fileIndex, { file }] of annotatedFiles.entries()) {+ const dimensions = fileMasonryDimensions(file);+ const aspectRatio = Math.max(+ 0.1,+ dimensions.width / dimensions.height,+ );+ masonrySourceItems.push({ file, fileIndex, aspectRatio });+ }++ if (useAdaptiveMobileRows) {+ let sourceIndex = 0;+ let rowIndex = 0;+ while (sourceIndex < masonrySourceItems.length) {+ const desiredCount = preferredMobileMasonryRowItemCount(+ masonrySourceItems,+ sourceIndex,+ rowIndex,+ );+ const boundedCount = Math.max(+ 1,+ Math.min(+ desiredCount,+ masonrySourceItems.length - sourceIndex,+ ),+ );+ for (let i = 0; i < boundedCount; i += 1) {+ const sourceItem = masonrySourceItems[sourceIndex + i]!;+ currentRow.push(sourceItem);+ currentRowAspectRatio += sourceItem.aspectRatio;+ }+ placeCurrentRow(true);+ sourceIndex += boundedCount;+ rowIndex += 1;+ }+ } else {+ for (const sourceItem of masonrySourceItems) {+ currentRow.push(sourceItem);+ currentRowAspectRatio += sourceItem.aspectRatio;++ const rowWidthAtTargetHeight =+ currentRowAspectRatio * masonryTargetRowHeight ++ (currentRow.length - 1) * layoutParams.gap;+ if (rowWidthAtTargetHeight >= masonryInnerWidth) {+ placeCurrentRow(true);+ }+ }+ placeCurrentRow(false);+ }++ const totalHeight = Math.max(0, rowTop - layoutParams.gap);+ return { items, rows, totalHeight };+ }, [+ annotatedFiles,+ masonryInnerWidth,+ layoutParams.containerWidth,+ layoutParams.gap,+ masonryTargetRowHeight,+ shouldUseMasonry,+ ]);+ const masonryHeaderHeight = header?.height ?? 0;+ const masonryViewportTop = Math.max(+ 0,+ masonryScrollTop - masonryHeaderHeight,+ );+ const masonryViewportBottom = masonryViewportTop + height;+ const masonryOverscan = Math.max(height, 800);+ const masonryVisibleItems = useMemo(() => {+ const minTop = masonryViewportTop - masonryOverscan;+ const maxTop = masonryViewportBottom + masonryOverscan;+ const visible = new Array<MasonryLayoutItem>();+ const startRowIndex = firstVisibleMasonryRowIndex(+ masonryLayout.rows,+ minTop,+ );++ for (+ let rowIndex = startRowIndex;+ rowIndex < masonryLayout.rows.length;+ rowIndex += 1+ ) {+ const row = masonryLayout.rows[rowIndex]!;+ if (!row.length) continue;+ if (row[0]!.top > maxTop) break;+ const startIndex = firstVisibleIndexForMasonryTrack(row, minTop);+ for (let i = startIndex; i < row.length; i += 1) {+ const item = row[i]!;+ if (item.top > maxTop) break;+ visible.push(item);+ }+ }++ return visible;+ }, [+ masonryLayout.rows,+ masonryOverscan,+ masonryViewportBottom,+ masonryViewportTop,+ ]);++ const handleMasonryScroll: React.UIEventHandler<HTMLDivElement> =+ useCallback(+ (event) => {+ const scrollOffset = event.currentTarget.scrollTop;+ onScroll?.(scrollOffset);+ setShowBackToTop(scrollOffset > 500);+ setMasonryScrollTop(scrollOffset);+ setMasonryIsScrolling(true);+ if (masonryScrollIdleTimeoutRef.current) {+ clearTimeout(masonryScrollIdleTimeoutRef.current);+ }+ masonryScrollIdleTimeoutRef.current = setTimeout(() => {+ setMasonryIsScrolling(false);+ masonryScrollIdleTimeoutRef.current = undefined;+ }, masonryScrollIdleMs);+ },+ [onScroll],+ );++ useEffect(+ () => () => {+ if (masonryScrollIdleTimeoutRef.current) {+ clearTimeout(masonryScrollIdleTimeoutRef.current);+ }+ },+ [],+ );++ useEffect(() => {+ if (!shouldUseMasonry) {+ setMasonryScrollTop(0);+ setMasonryIsScrolling(false);+ if (masonryScrollIdleTimeoutRef.current) {+ clearTimeout(masonryScrollIdleTimeoutRef.current);+ masonryScrollIdleTimeoutRef.current = undefined;+ }+ }+ }, [shouldUseMasonry]);++ useEffect(() => {+ if (!shouldUseMasonry || !onVisibleDateChange) return;+ const topVisibleItem = masonryVisibleItems.reduce<+ MasonryLayoutItem | undefined+ >(+ (best, item) =>+ item.bottom > masonryViewportTop &&+ (!best || item.top < best.top)+ ? item+ : best,+ undefined,+ );+ const visibleDate =+ topVisibleItem &&+ annotatedFiles[topVisibleItem.fileIndex]?.timelineDateString;+ const currentDate =+ visibleDate ?? annotatedFiles[0]?.timelineDateString;+ if (currentDate !== lastVisibleDateRef.current) {+ lastVisibleDateRef.current = currentDate;+ onVisibleDateChange(currentDate);+ }+ }, [+ annotatedFiles,+ masonryVisibleItems,+ masonryViewportTop,+ onVisibleDateChange,+ shouldUseMasonry,+ ]);++ const renderMasonryItem = useCallback(+ ({+ file,+ fileIndex,+ top,+ left,+ width,+ height,+ bottom,+ }: MasonryLayoutItem) => {+ const isInViewport =+ bottom > masonryViewportTop && top < masonryViewportBottom;+ return (+ <Box+ key={`masonry-photo-${file.id}-${fileIndex}`}+ sx={{ position: "absolute", top, left, width, height }}+ >+ <FileThumbnail+ key={`tile-${file.id}-selected-${selected[file.id] ?? false}`}+ {...{+ user,+ emailByUserID,+ enableSelect:+ !!enableSelect && !suppressSelectionUI,+ }}+ file={file}+ selected={isFileSelected(file)}+ selectOnClick={haveSelection}+ isRangeSelectActive={isShiftKeyPressed && haveSelection}+ isInSelectRange={+ rangeStartIndex !== undefined &&+ hoverIndex !== undefined &&+ ((fileIndex >= rangeStartIndex &&+ fileIndex <= hoverIndex) ||+ (fileIndex >= hoverIndex &&+ fileIndex <= rangeStartIndex))+ }+ activeCollectionID={activeCollectionID}+ showPlaceholder={masonryIsScrolling && !isInViewport}+ isFav={!!favoriteFileIDs?.has(file.id)}+ onClick={() => onItemClick(fileIndex)}+ onSelect={handleSelect(file, fileIndex)}+ onHover={() => setHoverIndex(fileIndex)}+ onRangeSelect={() => handleRangeSelect(fileIndex)}+ onContextMenu={+ onContextMenuAction+ ? (e) => handleContextMenu(e, file, fileIndex)+ : undefined+ }+ isMasonry+ style={{ width: "100%", height: "100%" }}+ />+ </Box>+ );+ },+ [+ activeCollectionID,+ emailByUserID,+ enableSelect,+ favoriteFileIDs,+ handleContextMenu,+ handleRangeSelect,+ handleSelect,+ haveSelection,+ hoverIndex,+ isFileSelected,+ isShiftKeyPressed,+ masonryIsScrolling,+ masonryViewportBottom,+ masonryViewportTop,+ onContextMenuAction,+ onItemClick,+ rangeStartIndex,+ selected,+ suppressSelectionUI,+ user,+ ],+ );++ const handleScrollToTop = useCallback(() => {+ outerRef.current?.scrollTo({ top: 0, behavior: "smooth" });+ }, []);++ if (shouldUseMasonry) {+ return (+ <Box sx={{ position: "relative", width, height }}>+ <Box+ ref={outerRef}+ sx={{+ width: "100%",+ height: "100%",+ overflowY: "auto",+ ...(listBorderRadius && {+ borderRadius: listBorderRadius,+ }),+ }}+ onScroll={handleMasonryScroll}+ >+ {header && (+ <Box+ sx={{+ px: header.extendToInlineEdges+ ? 0+ : `${layoutParams.paddingInline}px`,+ }}+ >+ {header.component}+ </Box>+ )}+ {masonryLayout.items.length > 0 ? (+ <Box sx={{ px: `${layoutParams.paddingInline}px` }}>+ <Box+ sx={{+ width: masonryInnerWidth,+ position: "relative",+ height: masonryLayout.totalHeight,+ }}+ >+ {masonryVisibleItems.map(renderMasonryItem)}+ </Box>+ </Box>+ ) : (+ <NoFilesListItem sx={{ minHeight: "100%" }}>+ <Typography sx={{ color: "text.faint" }}>+ {t("nothing_here")}+ </Typography>+ </NoFilesListItem>+ )}+ {footer && (+ <Box+ sx={{+ px: footer.extendToInlineEdges+ ? 0+ : `${layoutParams.paddingInline}px`,+ }}+ >+ {footer.component}+ </Box>+ )}+ </Box>+ {showBackToTop && (+ <BackToTopButton+ size="small"+ aria-label="scroll to top"+ onClick={handleScrollToTop}+ >+ <KeyboardArrowUpIcon />+ </BackToTopButton>+ )}+ {onContextMenuAction && (+ <FileContextMenu+ open={contextMenu !== null}+ anchorPosition={contextMenu?.position}+ onClose={handleContextMenuClose}+ actions={contextMenuActions}+ onAction={handleContextMenuActionWithTracking}+ />+ )}+ </Box>+ );+ }++ if (!items.length) {+ return <></>;+ }++ // The old, mode unaware, behaviour.+ let key = `${activeCollectionID}`;+ if (modePlus) {+ // If the new experimental modePlus prop is provided, use it to derive a+ // mode specific key.+ if (modePlus == "search") {+ key = "search";+ } else if (modePlus == "people") {+ if (!activePersonID) {+ assertionFailed();+ } else {+ key = activePersonID;+ }+ }+ }++ return (+ <Box sx={{ position: "relative", width, height }}>+ <VariableSizeList+ key={key}+ ref={listRef}+ outerRef={outerRef}+ {...{ width, height, itemData, itemSize, itemKey }}+ itemCount={items.length}+ overscanCount={3}+ useIsScrolling+ onScroll={handleScroll}+ style={+ listBorderRadius+ ? { borderRadius: listBorderRadius }+ : undefined+ }+ >+ {FileListRow}+ </VariableSizeList>+ {showBackToTop && (+ <BackToTopButton+ size="small"+ aria-label="scroll to top"+ onClick={handleScrollToTop}+ >+ <KeyboardArrowUpIcon />+ </BackToTopButton>+ )}+ {onContextMenuAction && (+ <FileContextMenu+ open={contextMenu !== null}+ anchorPosition={contextMenu?.position}+ onClose={handleContextMenuClose}+ actions={contextMenuActions}+ onAction={handleContextMenuActionWithTracking}+ />+ )}+ </Box>+ );+};++/**+ * 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) => (+ splits.at(-1)?.at(0)?.timelineDateString ==+ annotatedFile.timelineDateString+ ? splits.at(-1)?.push(annotatedFile)+ : splits.push([annotatedFile]),+ splits+ ),+ new Array<FileListAnnotatedFile[]>(),+ );++const firstVisibleIndexForMasonryTrack = (+ track: MasonryLayoutItem[],+ minTop: number,+) => {+ let low = 0;+ let high = track.length;+ while (low < high) {+ const mid = Math.floor((low + high) / 2);+ if (track[mid]!.bottom < minTop) {+ low = mid + 1;+ } else {+ high = mid;+ }+ }+ return low;+};++const firstVisibleMasonryRowIndex = (+ rows: MasonryLayoutItem[][],+ minTop: number,+) => {+ let low = 0;+ let high = rows.length;+ while (low < high) {+ const mid = Math.floor((low + high) / 2);+ const row = rows[mid]!;+ const rowBottom = row.length ? row[row.length - 1]!.bottom : -Infinity;+ if (rowBottom < minTop) {+ low = mid + 1;+ } else {+ high = mid;+ }+ }+ return low;+};++const fileMasonryDimensions = (file: EnteFile) => {+ if (shouldUseSquareMasonryDimensions(file)) {+ return { width: 1, height: 1 };+ }++ const width = file.pubMagicMetadata?.data.w;+ const height = file.pubMagicMetadata?.data.h;+ if (width && height && width > 0 && height > 0) {+ return { width, height };+ }++ return { width: 1, height: 1 };+};++const shouldUseSquareMasonryDimensions = (file: EnteFile) =>+ file.metadata.fileType === FileType.video ||+ file.metadata.fileType === FileType.livePhoto;++const masonryScrollIdleMs = 120;++const preferredMasonryRowHeight = (containerWidth: number) => {+ if (containerWidth < 560) return 210;+ if (containerWidth < 900) return 250;+ if (containerWidth < 1280) return 300;+ if (containerWidth < 1800) return 345;+ return 385;+};++const shouldUseAdaptiveMobileMasonryRows = (containerWidth: number) =>+ containerWidth < 560;++const preferredMobileMasonryRowItemCount = (+ sourceItems: MasonrySourceItem[],+ startIndex: number,+ rowIndex: number,+) => {+ const first = sourceItems[startIndex];+ const second = sourceItems[startIndex + 1];+ const third = sourceItems[startIndex + 2];+ if (!first || !second) return 1;++ const firstRatio = first.aspectRatio;+ const secondRatio = second.aspectRatio;+ if (firstRatio >= 1.25) return 1;++ const firstIsPortrait = firstRatio < 0.9;+ 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.+ if (firstRatio <= 0.62 && rowIndex % 4 === 1) return 1;++ if (firstIsPortrait && secondIsPortrait && third && thirdIsPortrait) {+ return rowIndex % 3 === 0 ? 3 : 2;+ }+ if (firstIsPortrait && secondIsPortrait) return 2;++ if (firstRatio + secondRatio >= 1.6) return 2;+ if (third && firstRatio + secondRatio + third.aspectRatio >= 1.9) return 3;+ 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[],+ g: (x: T) => U,+) => {+ const ys = xs.map((x) => [...f(x), g(x)]).flat();+ 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;+`;++const NoFilesListItem = styled(FullSpanListItem)`+ min-height: 100%;+ justify-content: center;+`;++/**+ * Floating button to scroll back to the top of the file list.+ */+const BackToTopButton = styled(Fab)(({ theme }) => ({+ position: "absolute",+ bottom: 24,+ right: 24,+ backgroundColor: theme.vars.palette.fill.faint,+ color: theme.vars.palette.text.base,+ boxShadow: "none",+ "&:hover": { backgroundColor: theme.vars.palette.fill.faintHover },+ [theme.breakpoints.down("sm")]: { display: "none" },+}));++/**+ * Convert a {@link FileListHeaderOrFooter} into a {@link FileListItem}+ * that spans the entire width available to the row.+ */+const asFullSpanFileListItem = ({+ component,+ ...rest+}: FileListHeaderOrFooter): FileListItem => ({+ ...rest,+ type: "span",+ 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)(+ ({ theme }) => `+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ height: ${dateListItemHeight}px;+ color: ${theme.vars.palette.text.muted};+`,+);++interface FileListItemData {+ items: FileListItem[];+ layoutParams: ThumbnailGridLayoutParams;+ renderListItem: (+ item: FileListItem,+ isScrolling: boolean,+ ) => React.ReactNode;+}++const FileListRow = memo(+ ({+ index,+ style,+ isScrolling,+ data,+ }: ListChildComponentProps<FileListItemData>) => {+ const { items, layoutParams, renderListItem } = data;+ const { itemWidth, paddingInline, gap } = layoutParams;++ const item = items[index]!;+ const itemSpans = (() => {+ switch (item.type) {+ case "date":+ return item.groups.map((g) => g.dateSpan);+ case "file":+ return item.groups.map((g) => g.annotatedFiles.length);+ case "span":+ return [];+ }+ })();+ const px =+ item.type == "span" && item.extendToInlineEdges ? 0 : paddingInline;++ return (+ <Box+ style={style}+ sx={[+ { width: "100%", paddingInline: `${px}px` },+ itemSpans.length > 0 && {+ display: "grid",+ gridTemplateColumns: itemSpans+ .map((x) => `repeat(${x}, ${itemWidth}px)`)+ .join(" 44px "),+ columnGap: `${gap}px`,+ },+ ]}+ >+ {renderListItem(item, !!isScrolling)}+ </Box>+ );+ },+ areEqual,+);++type FileThumbnailProps = {+ file: EnteFile;+ selected: boolean;+ isRangeSelectActive: boolean;+ selectOnClick: boolean;+ isInSelectRange: boolean;+ activeCollectionID: number;+ showPlaceholder: boolean;+ isFav: boolean;+ onClick: () => void;+ onSelect: (checked: boolean) => void;+ onHover: () => void;+ onRangeSelect: () => void;+ onContextMenu?: (event: React.MouseEvent) => void;+ onImageDimensions?: (dimensions: Dimensions) => void;+ isMasonry?: boolean;+ style?: React.CSSProperties;+} & Pick<FileListProps, "user" | "emailByUserID" | "enableSelect">;++const FileThumbnail: React.FC<FileThumbnailProps> = ({+ file,+ user,+ enableSelect,+ selected,+ selectOnClick,+ isRangeSelectActive,+ isInSelectRange,+ isFav,+ emailByUserID,+ activeCollectionID,+ showPlaceholder,+ onClick,+ onSelect,+ onHover,+ onRangeSelect,+ onContextMenu,+ onImageDimensions,+ isMasonry,+ style,+}) => {+ const [imageURL, setImageURL] = useState<string | undefined>(undefined);+ const [isLongPressing, setIsLongPressing] = useState(false);++ const longPressHandlers = useMemo(+ () => ({+ onMouseDown: () => setIsLongPressing(true),+ onMouseUp: () => setIsLongPressing(false),+ onMouseLeave: () => setIsLongPressing(false),+ onTouchStart: () => setIsLongPressing(true),+ onTouchMove: () => setIsLongPressing(false),+ onTouchEnd: () => setIsLongPressing(false),+ onTouchCancel: () => setIsLongPressing(false),+ }),+ [],+ );++ useEffect(() => {+ const timerID = isLongPressing+ ? setTimeout(() => onSelect(!selected), 500)+ : undefined;+ return () => {+ if (timerID) clearTimeout(timerID);+ };+ }, [selected, onSelect, isLongPressing]);++ useEffect(() => {+ let didCancel = false;++ void downloadManager+ .renderableThumbnailURL(file, showPlaceholder)+ .then((url) => !didCancel && setImageURL(url))+ .catch((e: unknown) => {+ log.warn("Failed to fetch thumbnail", e);+ });++ return () => {+ didCancel = true;+ };+ }, [file, showPlaceholder]);++ const handleClick = () => {+ if (selectOnClick) {+ if (isRangeSelectActive) {+ onRangeSelect();+ } else {+ onSelect(!selected);+ }+ } else if (imageURL) {+ onClick();+ }+ };++ const handleSelect: React.ChangeEventHandler<HTMLInputElement> = (e) => {+ if (isRangeSelectActive) {+ onRangeSelect();+ } else {+ onSelect(e.target.checked);+ }+ };++ const handleHover = () => {+ if (isRangeSelectActive) {+ onHover();+ }+ };++ // See: [Note: Files in trash pseudo collection have deleteBy]+ const deleteBy =+ activeCollectionID == PseudoCollectionID.trash &&+ (file as EnteTrashFile).deleteBy;++ return (+ <FileThumbnail_+ key={`thumb-${file.id}}`}+ onClick={handleClick}+ onContextMenu={onContextMenu}+ onMouseEnter={handleHover}+ disabled={!imageURL}+ $disableBottomMargin={!!isMasonry}+ style={style}+ {...(enableSelect && longPressHandlers)}+ >+ {enableSelect && (+ <Check+ type="checkbox"+ checked={selected}+ onChange={handleSelect}+ $active={isRangeSelectActive && isInSelectRange}+ onClick={(e) => e.stopPropagation()}+ />+ )}+ {file.metadata.hasStaticThumbnail ? (+ <StaticThumbnail fileType={file.metadata.fileType} />+ ) : imageURL ? (+ <img+ src={imageURL}+ onLoad={(event) => {+ const { naturalWidth, naturalHeight } =+ event.currentTarget;+ onImageDimensions?.({+ width: naturalWidth,+ height: naturalHeight,+ });+ }}+ />+ ) : (+ <LoadingThumbnail />+ )}+ {file.metadata.fileType == FileType.livePhoto ? (+ <FileTypeIndicatorOverlay>+ <AlbumOutlinedIcon fontSize="small" />+ </FileTypeIndicatorOverlay>+ ) : (+ file.metadata.fileType == FileType.video && (+ <VideoDurationOverlay duration={fileDurationString(file)} />+ )+ )}+ {selected && <SelectedOverlay />}+ {shouldShowAvatar(file, user) && (+ <AvatarOverlay>+ <Avatar {...{ user, file, emailByUserID }} />+ </AvatarOverlay>+ )}+ {isFav && (+ <FavoriteOverlay>+ <StarIcon fontSize="small" />+ </FavoriteOverlay>+ )}++ <HoverOverlay+ className="preview-card-hover-overlay"+ checked={selected}+ />+ {isRangeSelectActive && isInSelectRange && <InSelectRangeOverlay />}++ {deleteBy && (+ <TileBottomTextOverlay>+ <Typography variant="small">+ {formattedDateRelative(deleteBy)}+ </Typography>+ </TileBottomTextOverlay>+ )}+ </FileThumbnail_>+ );+};++const FileThumbnail_ = styled("div")<{+ disabled: boolean;+ $disableBottomMargin: boolean;+}>`+ display: flex;+ width: fit-content;+ margin-bottom: ${({ $disableBottomMargin }) =>+ $disableBottomMargin ? "0px" : `${thumbnailGap}px`};+ min-width: 100%;+ overflow: hidden;+ position: relative;+ flex: 1;+ cursor: ${(props) => (props.disabled ? "not-allowed" : "pointer")};+ user-select: none;+ & > img {+ object-fit: cover;+ max-width: 100%;+ min-height: 100%;+ flex: 1;+ pointer-events: none;+ }++ @media (pointer: fine) {+ &:hover {+ input[type="checkbox"] {+ visibility: visible;+ opacity: 0.5;+ }++ .preview-card-hover-overlay {+ opacity: 1;+ }+ }+ }++ border-radius: 4px;+`;++const Check = styled("input")<{ $active: boolean }>(+ ({ theme, $active }) => `+ appearance: none;+ -webkit-appearance: none;+ -moz-appearance: none;+ position: absolute;+ z-index: 1;+ left: 0;+ outline: none;+ cursor: pointer;+ width: 31px;+ height: 31px;+ box-sizing: border-box;++ @media (pointer: coarse) {+ pointer-events: none;+ }++ &::before {+ content: "";+ display: block; /* Critical for Safari */+ 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 */+ }++ &::after {+ content: "";+ display: block; /* Critical for Safari */+ position: absolute;+ top: 50%;+ left: 50%;+ width: 5px;+ height: 11px;+ border: solid #333;+ border-width: 0 2px 2px 0;+ transform: translate(-50%, -60%) rotate(45deg);+ transition: border-color 0.3s ease, opacity 0.3s ease;+ transform-origin: center;+ }++ /* Default state - hide both */+ visibility: hidden;++ /* When $active - show both with reduced opacity */+ ${+ $active &&+ `+ visibility: visible;+ opacity: 0.5;+ `+ };++ /* 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;+ }++ &:checked::before {+ background-color: ${theme.vars.palette.accent.main};+ }++ &:checked::after {+ border-color: #ddd;+ }+`,+);++const HoverOverlay = styled("div")<{ checked: boolean }>`+ opacity: 0;+ left: 0;+ top: 0;+ outline: none;+ height: 40%;+ width: 100%;+ position: absolute;+ ${(props) =>+ !props.checked &&+ "background:linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0))"};+`;++/**+ * An overlay showing the avatars of the person who shared the item, at the top+ * right.+ */+const AvatarOverlay = styled(Overlay)`+ display: flex;+ justify-content: flex-end;+ align-items: flex-start;+ padding: 5px;+`;++/**+ * An overlay showing the favorite icon at bottom left.+ */+const FavoriteOverlay = styled(Overlay)`+ display: flex;+ justify-content: flex-start;+ align-items: flex-end;+ padding: 5px;+ color: white;+ opacity: 0.6;+`;++/**+ * 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;+ align-items: flex-end;+ padding: 5px;+ color: white;+ background: linear-gradient(+ 315deg,+ rgba(0 0 0 / 0.14) 0%,+ rgba(0 0 0 / 0.05) 30%,+ transparent 50%+ );+`;++const InSelectRangeOverlay = styled(Overlay)(+ ({ theme }) => `+ outline: none;+ background: ${theme.vars.palette.accent.main};+ opacity: 0.14;+`,+);++const SelectedOverlay = styled(Overlay)(+ ({ theme }) => `+ border: 2px solid ${theme.vars.palette.accent.main};+ border-radius: 4px;+`,+);++interface VideoDurationOverlayProps {+ duration: string | undefined;+}++const VideoDurationOverlay: React.FC<VideoDurationOverlayProps> = ({+ duration,+}) => (+ <FileTypeIndicatorOverlay>+ {duration ? (+ <Box sx={{ display: "flex", alignItems: "center" }}>+ <PlayArrowRoundedIcon+ sx={{ fontSize: 14, display: "block", mr: 0.5 }}+ />+ <Typography variant="mini">{duration}</Typography>+ </Box>+ ) : (+ <PlayCircleOutlineOutlinedIcon fontSize="small" />+ )}+ </FileTypeIndicatorOverlay>+);++/**+ * Return `true` if the owner or uploader name avatar indicator should be shown+ * for the given {@link file}.+ */+const shouldShowAvatar = (file: EnteFile, user: LocalUser | undefined) => {+ // Public albums app.+ if (!user) return false;+ // A file shared with the user.+ if (file.ownerID != user.id) return true;+ // A public collected file (i.e. a file owned by the user, uploaded by an+ // named guest via a public collect link)+ if (file.pubMagicMetadata?.data.uploaderName) return true;+ // Regular file.+ return false;+};diff --git a/web/apps/albums/vendor/photos/components/FileListWithViewer.tsx b/web/apps/albums/vendor/photos/components/FileListWithViewer.tsxnew file mode 100644index 0000000000..d3b9fcc9b2--- /dev/null+++ b/web/apps/albums/vendor/photos/components/FileListWithViewer.tsx@@ -0,0 +1,486 @@+import { IconButton, Tooltip, styled } from "@mui/material";+import { useColorScheme, useTheme } from "@mui/material/styles";+import { CollectionMapDialog } from "components/Collections/CollectionMapDialog";+import { useModalVisibility } from "ente-base/components/utils/modal";+import { useBaseContext } from "ente-base/context";+import { isSameDay } from "ente-base/date";+import { formattedDate } from "ente-base/i18n-date";+import type { AddSaveGroup } from "ente-gallery/components/utils/save-groups";+import {+ FileViewer,+ type FileViewerInitialSidebar,+ type FileViewerProps,+} from "ente-gallery/components/viewer/FileViewer";+import { downloadAndSaveFiles } from "ente-gallery/services/save";+import type { Collection } from "ente-media/collection";+import type { EnteFile } from "ente-media/file";+import { fileCreationTime, fileFileName } from "ente-media/file-metadata";+import { useSettingsSnapshot } from "ente-new/photos/components/utils/use-snapshot";+import { moveToTrash } from "ente-new/photos/services/collection";+import type { CollectionSummary } from "ente-new/photos/services/collection-summary";+import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";+import { updateMapEnabled } from "ente-new/photos/services/settings";+import { t } from "i18next";+import { useCallback, useEffect, useMemo, useState } from "react";+import AutoSizer from "react-virtualized-auto-sizer";+import { uploadManager } from "services/upload-manager";+import {+ FileList,+ type FileListAnnotatedFile,+ type FileListProps,+} from "./FileList";++export type FileListWithViewerProps = {+ /**+ * The list of files to show.+ */+ files: EnteFile[];+ enableDownload?: boolean;+ enableImageEditing?: boolean;+ /**+ * Called when the component wants to mark the given files as deleted in the+ * the in-memory, unsynced, state maintained by the top level gallery.+ *+ * For more details, see {@link unsyncedFavoriteUpdates} in the gallery+ * reducer's documentation.+ *+ * Not set in the context of the shared albums app.+ */+ onMarkTempDeleted?: (files: EnteFile[]) => void;+ /**+ * Called when the visibility of the file viewer dialog changes.+ */+ onSetOpenFileViewer?: (open: boolean) => void;+ /**+ * Called when an action in the file viewer requires us to perform a full+ * pull from remote.+ */+ onRemotePull: () => Promise<void>;+ activeCollectionSummary?: CollectionSummary;+ activeCollection?: Collection;+ /**+ * 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;+ /**+ * 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;++ onAddFileToCollection?: (+ file: EnteFile,+ sourceCollectionSummaryID?: number,+ ) => void;+ /**+ * Called when the list scrolls, providing the current scroll offset.+ */+ onScroll?: (scrollOffset: number) => void;+ /**+ * Called when the visible date at the top of the viewport changes.+ */+ onVisibleDateChange?: (date: string | undefined) => void;+} & Pick<+ FileListProps,+ | "mode"+ | "modePlus"+ | "layout"+ | "header"+ | "footer"+ | "disableGrouping"+ | "enableSelect"+ | "selected"+ | "setSelected"+ | "activeCollectionID"+ | "activePersonID"+ | "favoriteFileIDs"+ | "emailByUserID"+ | "listBorderRadius"+ | "onContextMenuAction"+ | "onContextMenuOpenChange"+ | "showAddPersonAction"+ | "showEditLocationAction"+ | "suppressSelectionUI"+> &+ Pick<+ FileViewerProps,+ | "user"+ | "isInIncomingSharedCollection"+ | "isInHiddenSection"+ | "fileNormalCollectionIDs"+ | "collectionSummaries"+ | "collectionNameByID"+ | "pendingFavoriteUpdates"+ | "pendingVisibilityUpdates"+ | "onRemoteFilesPull"+ | "onVisualFeedback"+ | "onToggleFavorite"+ | "onFileVisibilityUpdate"+ | "onSendLink"+ | "onSelectCollection"+ | "onSelectPerson"+ | "publicAlbumsCredentials"+ | "collectionKey"+ | "onJoinAlbum"+ | "enableComment"+ | "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> = ({+ mode,+ modePlus,+ layout,+ header,+ footer,+ user,+ files,+ enableDownload,+ enableImageEditing = true,+ disableGrouping,+ enableSelect,+ selected,+ setSelected,+ activeCollectionID,+ activePersonID,+ activeCollectionSummary,+ activeCollection,+ favoriteFileIDs,+ emailByUserID,+ listBorderRadius,+ onContextMenuAction,+ onContextMenuOpenChange,+ showAddPersonAction,+ showEditLocationAction,+ suppressSelectionUI,+ isInIncomingSharedCollection,+ isInHiddenSection,+ fileNormalCollectionIDs,+ collectionSummaries,+ collectionNameByID,+ pendingFavoriteUpdates,+ pendingVisibilityUpdates,+ onSetOpenFileViewer,+ onRemotePull,+ onRemoteFilesPull,+ onVisualFeedback,+ onAddSaveGroup,+ onToggleFavorite,+ onFileVisibilityUpdate,+ onSendLink,+ onMarkTempDeleted,+ onSelectCollection,+ onSelectPerson,+ onAddFileToCollection,+ onScroll,+ onVisibleDateChange,+ pendingFileIndex,+ pendingFileSidebar,+ pendingHighlightCommentID,+ onPendingNavigationConsumed,+ publicAlbumsCredentials,+ collectionKey,+ onJoinAlbum,+ enableComment,+ enableJoin,+}) => {+ const [openFileViewer, setOpenFileViewer] = useState(false);+ const [currentIndex, setCurrentIndex] = useState(0);+ const [initialSidebar, setInitialSidebar] = useState<+ FileViewerInitialSidebar | undefined+ >(undefined);+ const [highlightCommentID, setHighlightCommentID] = useState<+ string | undefined+ >(undefined);+ const { show: showMapDialog, props: mapDialogVisibilityProps } =+ useModalVisibility();+ const { onGenericError } = useBaseContext();+ const { mapEnabled } = useSettingsSnapshot();+ const { mode: colorSchemeMode, systemMode } = useColorScheme();+ const theme = useTheme();+ const resolvedMode =+ colorSchemeMode === "system"+ ? systemMode+ : (colorSchemeMode ?? theme.palette.mode);+ const isDarkMode = resolvedMode === "dark";++ // Handle pending navigation from feed item clicks+ useEffect(() => {+ if (pendingFileIndex !== undefined) {+ setCurrentIndex(pendingFileIndex);+ setInitialSidebar(pendingFileSidebar);+ setHighlightCommentID(pendingHighlightCommentID);+ setOpenFileViewer(true);+ onSetOpenFileViewer?.(true);+ onPendingNavigationConsumed?.();+ }+ }, [+ pendingFileIndex,+ pendingFileSidebar,+ pendingHighlightCommentID,+ onSetOpenFileViewer,+ onPendingNavigationConsumed,+ ]);++ // Clear initial sidebar state when file viewer closes+ const handleCloseFileViewerInternal = useCallback(() => {+ setInitialSidebar(undefined);+ setHighlightCommentID(undefined);+ onSetOpenFileViewer?.(false);+ setOpenFileViewer(false);+ }, [onSetOpenFileViewer]);++ const annotatedFiles = useMemo(+ (): FileListAnnotatedFile[] =>+ files.map((file) => ({+ file,+ timelineDateString: fileTimelineDateString(file),+ })),+ [files],+ );++ const handleThumbnailClick = useCallback(+ (index: number) => {+ setCurrentIndex(index);+ setOpenFileViewer(true);+ onSetOpenFileViewer?.(true);+ },+ [onSetOpenFileViewer],+ );++ const handleTriggerRemotePull = useCallback(+ () => void onRemotePull(),+ [onRemotePull],+ );++ const handleDownload = useCallback(+ (file: EnteFile) =>+ downloadAndSaveFiles([file], fileFileName(file), onAddSaveGroup),+ [onAddSaveGroup],+ );++ const handleDelete = useMemo(() => {+ return onMarkTempDeleted+ ? (file: EnteFile) =>+ moveToTrash([file]).then(() => onMarkTempDeleted([file]))+ : undefined;+ }, [onMarkTempDeleted]);++ const handleSaveEditedImageCopy = useMemo(() => {+ if (!enableImageEditing) return undefined;+ return (+ editedFile: File,+ collection: Collection,+ enteFile: EnteFile,+ ) => {+ uploadManager.prepareForNewUpload();+ uploadManager.showUploadProgressDialog();+ void uploadManager.uploadFile(editedFile, collection, enteFile);+ };+ }, [enableImageEditing]);++ const shouldShowMapButton =+ modePlus !== "search" &&+ activeCollectionSummary?.type === "all" &&+ (activeCollectionSummary.fileCount > 0 || files.length > 0);++ const handleShowMap = useCallback(async () => {+ if (!activeCollectionSummary) return;+ if (!mapEnabled) {+ try {+ await updateMapEnabled(true);+ } catch (e) {+ onGenericError(e);+ return;+ }+ }+ showMapDialog();+ }, [activeCollectionSummary, mapEnabled, onGenericError, showMapDialog]);++ const headerWithMap = useMemo(() => {+ if (!shouldShowMapButton || !header) return header;+ return {+ ...header,+ component: (+ <HeaderWithMap>+ <HeaderMain>{header.component}</HeaderMain>+ <Tooltip title={t("map")}>+ <IconButton+ className="map-button"+ size="small"+ aria-label={t("map")}+ onClick={handleShowMap}+ >+ <MapIcon+ src="/images/gallery-globe/globe.svg"+ alt=""+ aria-hidden+ $isDarkMode={isDarkMode}+ />+ </IconButton>+ </Tooltip>+ </HeaderWithMap>+ ),+ };+ }, [header, handleShowMap, isDarkMode, shouldShowMapButton]);++ return (+ <Container>+ <AutoSizer>+ {({ height, width }) => (+ <FileList+ {...{ width, height, annotatedFiles }}+ {...{+ mode,+ modePlus,+ layout,+ header: headerWithMap,+ footer,+ user,+ disableGrouping,+ enableSelect,+ selected,+ setSelected,+ activeCollectionID,+ activePersonID,+ favoriteFileIDs,+ emailByUserID,+ listBorderRadius,+ onScroll,+ onVisibleDateChange,+ collectionSummary: activeCollectionSummary,+ onContextMenuAction,+ onContextMenuOpenChange,+ showAddPersonAction,+ showEditLocationAction,+ suppressSelectionUI,+ }}+ onItemClick={handleThumbnailClick}+ />+ )}+ </AutoSizer>+ <FileViewer+ open={openFileViewer}+ onClose={handleCloseFileViewerInternal}+ initialIndex={currentIndex}+ initialSidebar={initialSidebar}+ highlightCommentID={highlightCommentID}+ disableDownload={!enableDownload}+ isInTrashSection={+ activeCollectionID == PseudoCollectionID.trash+ }+ {...{+ user,+ files,+ isInHiddenSection,+ isInIncomingSharedCollection,+ favoriteFileIDs,+ fileNormalCollectionIDs,+ collectionSummaries,+ collectionNameByID,+ pendingFavoriteUpdates,+ pendingVisibilityUpdates,+ onRemoteFilesPull,+ onVisualFeedback,+ onToggleFavorite,+ onFileVisibilityUpdate,+ onSendLink,+ onSelectCollection,+ onSelectPerson,+ publicAlbumsCredentials,+ collectionKey,+ onJoinAlbum,+ enableComment,+ enableJoin,+ }}+ isCommentsFeatureEnabled+ onTriggerRemotePull={handleTriggerRemotePull}+ onDownload={handleDownload}+ onDelete={handleDelete}+ onSaveEditedImageCopy={handleSaveEditedImageCopy}+ onAddFileToCollection={onAddFileToCollection}+ activeCollectionID={activeCollectionID}+ />+ {shouldShowMapButton && (+ <CollectionMapDialog+ {...mapDialogVisibilityProps}+ collectionSummary={activeCollectionSummary}+ activeCollection={activeCollection}+ onRemotePull={onRemotePull}+ {...{+ onAddSaveGroup,+ onMarkTempDeleted,+ onAddFileToCollection,+ onRemoteFilesPull,+ onVisualFeedback,+ fileNormalCollectionIDs,+ collectionNameByID,+ onSelectCollection,+ onSelectPerson,+ }}+ />+ )}+ </Container>+ );+};++const Container = styled("div")`+ flex: 1;+ width: 100%;+`;++const HeaderWithMap = styled("div")`+ display: flex;+ align-items: center;+ justify-content: flex-start;+ gap: 12px;+ width: 100%;+ & > .map-button {+ flex-shrink: 0;+ margin-left: auto;+ }+`;++const HeaderMain = styled("div")`+ flex: 1;+ min-width: 0;+`;++const MapIcon = styled("img")<{ $isDarkMode: boolean }>(+ ({ theme, $isDarkMode }) => ({+ display: "block",+ width: 24,+ height: 24,+ filter:+ $isDarkMode || theme.palette.mode === "dark" ? "invert(1)" : "none",+ }),+);++/**+ * See: [Note: Timeline date string]+ */+const fileTimelineDateString = (file: EnteFile) => {+ const date = new Date(fileCreationTime(file) / 1000);+ return isSameDay(date, new Date())+ ? t("today")+ : isSameDay(date, new Date(Date.now() - 24 * 60 * 60 * 1000))+ ? t("yesterday")+ : formattedDate(date);+};diff --git a/web/apps/albums/vendor/photos/components/PublicAlbumSingleFileViewer.tsx b/web/apps/albums/vendor/photos/components/PublicAlbumSingleFileViewer.tsxnew file mode 100644index 0000000000..84c0eb9f26--- /dev/null+++ b/web/apps/albums/vendor/photos/components/PublicAlbumSingleFileViewer.tsx@@ -0,0 +1,852 @@+import CheckIcon from "@mui/icons-material/Check";+import ContentCopyIcon from "@mui/icons-material/ContentCopy";+import DownloadOutlinedIcon from "@mui/icons-material/DownloadOutlined";+import FullscreenOutlinedIcon from "@mui/icons-material/FullscreenOutlined";+import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";+import MoreVertIcon from "@mui/icons-material/MoreVert";+import ShareOutlinedIcon from "@mui/icons-material/ShareOutlined";+import {+ Box,+ Button,+ CircularProgress,+ GlobalStyles,+ IconButton,+ Menu,+ MenuItem,+ Stack,+ styled,+ Typography,+} from "@mui/material";+import { EnteLogo } from "ente-base/components/EnteLogo";+import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";+import { useBaseContext } from "ente-base/context";+import type { PublicAlbumsCredentials } from "ente-base/http";+import log from "ente-base/log";+import type { AddSaveGroup } from "ente-gallery/components/utils/save-groups";+import { FileViewer } from "ente-gallery/components/viewer/FileViewer";+import { createPSRegisterElementIconHTML } from "ente-gallery/components/viewer/icons";+import { downloadManager } from "ente-gallery/services/download";+import { downloadAndSaveFiles } from "ente-gallery/services/save";+import type { EnteFile } from "ente-media/file";+import { fileFileName } from "ente-media/file-metadata";+import { FileType } from "ente-media/file-type";+import { Notification } from "ente-new/photos/components/Notification";+import { t } from "i18next";+import { useCallback, useEffect, useMemo, useState } from "react";+import { getEnteURL } from "utils/public-album";++interface PublicAlbumSingleFileViewerProps {+ file: EnteFile;+ publicAlbumsCredentials: PublicAlbumsCredentials;+ collectionKey: string;+ enableDownload: boolean;+ enableComment: boolean;+ enableJoin?: boolean;+ onJoinAlbum?: () => void;+ onVisualFeedback: () => void;+ onAddSaveGroup: AddSaveGroup;+}++const bodyClassName = "ente-public-single-file-viewer";+interface LivePhotoControlsState {+ playAvailable: boolean;+ muteAvailable: boolean;+ isPlayOff: boolean;+ isMuteOff: boolean;+}++const inlineFileViewerIconPath = (name: "live" | "vol") =>+ createPSRegisterElementIconHTML(name).inner.replace(+ /\s+id="pswp__icn-[^"]+"/g,+ "",+ );++const liveIconPath = inlineFileViewerIconPath("live");+const volumeIconPath = inlineFileViewerIconPath("vol");++/**+ * A dedicated public-album single-file viewer mode with a bespoke header/menu.+ *+ * This wraps the regular FileViewer but overlays its own controls.+ */+export const PublicAlbumSingleFileViewer: React.FC<+ PublicAlbumSingleFileViewerProps+> = ({+ file,+ publicAlbumsCredentials,+ collectionKey,+ enableDownload,+ enableComment,+ enableJoin,+ onJoinAlbum,+ onVisualFeedback,+ onAddSaveGroup,+}) => {+ const { onGenericError } = useBaseContext();+ const [menuAnchorEl, setMenuAnchorEl] = useState<HTMLElement | null>(null);+ const [showCopiedMessage, setShowCopiedMessage] = useState(false);+ const [isPhotoSwipeUIVisible, setIsPhotoSwipeUIVisible] = useState(true);+ const [isPhotoSwipeContentLoading, setIsPhotoSwipeContentLoading] =+ useState(false);+ const isLivePhotoFile = file.metadata.fileType === FileType.livePhoto;+ const [livePhotoControls, setLivePhotoControls] =+ useState<LivePhotoControlsState>({+ playAvailable: false,+ muteAvailable: false,+ isPlayOff: true,+ isMuteOff: true,+ });+ const needsThumbnailPrime =+ file.metadata.fileType === FileType.image ||+ file.metadata.fileType === FileType.livePhoto;+ const needsOriginalPrime = needsThumbnailPrime;+ const [viewerFile, setViewerFile] = useState(file);+ const [primedFileID, setPrimedFileID] = useState<number | undefined>(() =>+ needsThumbnailPrime ? undefined : file.id,+ );+ const isViewerPrimed = !needsThumbnailPrime || primedFileID === file.id;+ const viewerFiles = useMemo(() => [viewerFile], [viewerFile]);++ useEffect(() => {+ document.body.classList.add(bodyClassName);+ return () => document.body.classList.remove(bodyClassName);+ }, []);++ useEffect(() => {+ if (+ file.id !== viewerFile.id ||+ file.collectionID !== viewerFile.collectionID ||+ file.updationTime !== viewerFile.updationTime+ ) {+ setViewerFile(file);+ }+ }, [+ file,+ file.collectionID,+ file.id,+ file.updationTime,+ viewerFile.collectionID,+ viewerFile.id,+ viewerFile.updationTime,+ ]);++ useEffect(() => {+ let classObserver: MutationObserver | undefined;+ let preloaderObserver: MutationObserver | undefined;+ let pswpElement: HTMLElement | null = null;+ let preloaderElement: HTMLElement | null = null;++ const updateVisibility = () => {+ setIsPhotoSwipeUIVisible(+ pswpElement?.classList.contains("pswp--ui-visible") ?? true,+ );+ };++ const updateLoading = () => {+ setIsPhotoSwipeContentLoading(+ preloaderElement?.classList.contains(+ "pswp__preloader--active",+ ) ?? false,+ );+ };++ const bindToPreloaderElement = () => {+ const next =+ pswpElement?.querySelector<HTMLElement>(".pswp__preloader");+ if (next === preloaderElement) return;++ preloaderObserver?.disconnect();+ preloaderObserver = undefined;+ preloaderElement = next ?? null;++ if (!preloaderElement) {+ setIsPhotoSwipeContentLoading(false);+ return;+ }++ preloaderObserver = new MutationObserver(updateLoading);+ preloaderObserver.observe(preloaderElement, {+ attributes: true,+ attributeFilter: ["class"],+ });+ updateLoading();+ };++ const bindToPhotoSwipeElement = () => {+ const next = document.querySelector<HTMLElement>(".pswp");+ if (next !== pswpElement) {+ classObserver?.disconnect();+ classObserver = undefined;+ pswpElement = next;++ if (!pswpElement) {+ preloaderObserver?.disconnect();+ preloaderObserver = undefined;+ preloaderElement = null;+ setIsPhotoSwipeUIVisible(true);+ setIsPhotoSwipeContentLoading(false);+ return;+ }++ classObserver = new MutationObserver(updateVisibility);+ classObserver.observe(pswpElement, {+ attributes: true,+ attributeFilter: ["class"],+ });+ updateVisibility();+ }++ bindToPreloaderElement();+ };++ const treeObserver = new MutationObserver(bindToPhotoSwipeElement);+ treeObserver.observe(document.body, { childList: true, subtree: true });+ bindToPhotoSwipeElement();++ return () => {+ treeObserver.disconnect();+ classObserver?.disconnect();+ preloaderObserver?.disconnect();+ };+ }, []);++ useEffect(() => {+ if (!isLivePhotoFile) {+ setLivePhotoControls({+ playAvailable: false,+ muteAvailable: false,+ isPlayOff: true,+ isMuteOff: true,+ });+ return;+ }++ let playButtonObserver: MutationObserver | undefined;+ let muteButtonObserver: MutationObserver | undefined;+ let playButton: HTMLButtonElement | null = null;+ let muteButton: HTMLButtonElement | null = null;++ const updateLivePhotoControls = () => {+ const nextState: LivePhotoControlsState = {+ playAvailable:+ !!playButton &&+ !playButton.classList.contains("pswp__hidden"),+ muteAvailable:+ !!muteButton &&+ !muteButton.classList.contains("pswp__hidden"),+ isPlayOff: playButton?.classList.contains("pswp-ente-off")+ ? true+ : false,+ isMuteOff: muteButton?.classList.contains("pswp-ente-off")+ ? true+ : false,+ };++ setLivePhotoControls((prev) =>+ prev.playAvailable === nextState.playAvailable &&+ prev.muteAvailable === nextState.muteAvailable &&+ prev.isPlayOff === nextState.isPlayOff &&+ prev.isMuteOff === nextState.isMuteOff+ ? prev+ : nextState,+ );+ };++ const observeButtonClassChanges = () => {+ const nextPlayButton = document.querySelector<HTMLButtonElement>(+ ".pswp .pswp__button--live",+ );+ if (nextPlayButton !== playButton) {+ playButtonObserver?.disconnect();+ playButtonObserver = undefined;+ playButton = nextPlayButton;+ if (playButton) {+ playButtonObserver = new MutationObserver(+ updateLivePhotoControls,+ );+ playButtonObserver.observe(playButton, {+ attributes: true,+ attributeFilter: ["class"],+ });+ }+ }++ const nextMuteButton = document.querySelector<HTMLButtonElement>(+ ".pswp .pswp__button--vol",+ );+ if (nextMuteButton !== muteButton) {+ muteButtonObserver?.disconnect();+ muteButtonObserver = undefined;+ muteButton = nextMuteButton;+ if (muteButton) {+ muteButtonObserver = new MutationObserver(+ updateLivePhotoControls,+ );+ muteButtonObserver.observe(muteButton, {+ attributes: true,+ attributeFilter: ["class"],+ });+ }+ }++ updateLivePhotoControls();+ };++ const treeObserver = new MutationObserver(observeButtonClassChanges);+ treeObserver.observe(document.body, { childList: true, subtree: true });+ observeButtonClassChanges();++ return () => {+ treeObserver.disconnect();+ playButtonObserver?.disconnect();+ muteButtonObserver?.disconnect();+ };+ }, [isLivePhotoFile]);++ useEffect(() => {+ if (!needsThumbnailPrime) {+ setPrimedFileID(file.id);+ return;+ }+ if (primedFileID === file.id) return;++ let isActive = true;+ void downloadManager+ .renderableThumbnailURL(file)+ .catch((error: unknown) =>+ log.warn(+ "Failed to prime thumbnail for public single-file viewer",+ error,+ ),+ )+ .finally(() => {+ if (isActive) setPrimedFileID(file.id);+ });++ return () => {+ isActive = false;+ };+ }, [file, file.id, needsThumbnailPrime, primedFileID]);++ useEffect(() => {+ if (!needsOriginalPrime) return;++ // Give thumbnail fetch a brief head-start, then warm the original.+ const prefetchTimer = window.setTimeout(() => {+ void downloadManager+ .renderableSourceURLs(file)+ .catch((error: unknown) =>+ log.warn(+ "Failed to prime original for public single-file viewer",+ error,+ ),+ );+ }, 120);++ return () => window.clearTimeout(prefetchTimer);+ }, [file, needsOriginalPrime]);++ const handleViewerClose = useCallback(() => {+ window.history.back();+ }, []);++ const handleMenuClose = useCallback(() => setMenuAnchorEl(null), []);++ const handleDownload = useCallback(+ (targetFile: EnteFile) =>+ downloadAndSaveFiles(+ [targetFile],+ fileFileName(targetFile),+ onAddSaveGroup,+ ),+ [onAddSaveGroup],+ );++ const handleShare = useCallback(async () => {+ handleMenuClose();+ const shareUrl = window.location.href;+ const isMobile = window.matchMedia("(width < 720px)").matches;++ if (isMobile && typeof navigator.share === "function") {+ try {+ await navigator.share({ text: shareUrl });+ return;+ } catch (error) {+ if (error instanceof Error && error.name === "AbortError") {+ return;+ }+ }+ }++ try {+ await navigator.clipboard.writeText(shareUrl);+ setShowCopiedMessage(true);+ window.setTimeout(() => setShowCopiedMessage(false), 2000);+ } catch (error) {+ onGenericError(error);+ }+ }, [handleMenuClose, onGenericError]);++ const canCopyAsPNG = useMemo(+ () =>+ enableDownload &&+ (file.metadata.fileType === FileType.image ||+ file.metadata.fileType === FileType.livePhoto),+ [enableDownload, file.metadata.fileType],+ );++ const handleCopyAsPNG = useCallback(async () => {+ handleMenuClose();+ if (!canCopyAsPNG) return;++ try {+ const imageElement =+ document.querySelector<HTMLImageElement>(+ ".pswp .pswp__item--active img.pswp__img",+ ) ??+ document.querySelector<HTMLImageElement>(".pswp img.pswp__img");++ const imageURL = imageElement?.currentSrc || imageElement?.src;+ if (!imageURL) return;++ await navigator.clipboard.write([+ new ClipboardItem({+ "image/png": createImagePNGBlob(imageURL),+ }),+ ]);+ onVisualFeedback();+ } catch (error) {+ onGenericError(error);+ }+ }, [canCopyAsPNG, handleMenuClose, onGenericError, onVisualFeedback]);++ const handleOpenInfo = useCallback(() => {+ handleMenuClose();+ document+ .querySelector<HTMLButtonElement>(".pswp .pswp__button--info")+ ?.click();+ }, [handleMenuClose]);++ const handleToggleFullscreen = useCallback(() => {+ handleMenuClose();+ void (+ document.fullscreenElement+ ? document.exitFullscreen()+ : document.body.requestFullscreen()+ ).catch(onGenericError);+ }, [handleMenuClose, onGenericError]);++ const handleTryEnte = useCallback(() => {+ window.location.href = getEnteURL();+ }, []);++ const handleToggleLivePhotoPlay = useCallback(() => {+ document+ .querySelector<HTMLButtonElement>(+ ".pswp .pswp__button--live:not(.pswp__hidden)",+ )+ ?.click();+ }, []);++ const handleToggleLivePhotoMute = useCallback(() => {+ document+ .querySelector<HTMLButtonElement>(+ ".pswp .pswp__button--vol:not(.pswp__hidden)",+ )+ ?.click();+ }, []);++ const topControlsVisible = isViewerPrimed && isPhotoSwipeUIVisible;++ useEffect(() => {+ if (!topControlsVisible) {+ setMenuAnchorEl(null);+ }+ }, [topControlsVisible]);++ return (+ <>+ <GlobalStyles+ styles={{+ [`body.${bodyClassName} .pswp-ente-public-album .pswp__counter`]:+ { display: "none !important" },+ [`body.${bodyClassName} .pswp-ente-public-album .pswp__button--zoom`]:+ { display: "none !important" },+ [`body.${bodyClassName} .pswp-ente-public-album .pswp__button--close`]:+ { display: "none !important" },+ [`body.${bodyClassName} .pswp-ente-public-album .pswp__button--more`]:+ { display: "none !important" },+ [`body.${bodyClassName} .pswp-ente-public-album .pswp__button--info`]:+ { display: "none !important" },+ [`body.${bodyClassName} .pswp-ente-public-album .pswp__button--ente-logo`]:+ { display: "none !important" },+ [`body.${bodyClassName} .pswp-ente-public-album .pswp__button--download`]:+ { display: "none !important" },+ [`body.${bodyClassName} .pswp-ente-public-album .pswp__button--live`]:+ { display: "none !important" },+ [`body.${bodyClassName} .pswp-ente-public-album .pswp__button--vol`]:+ { display: "none !important" },+ [`body.${bodyClassName} .pswp-ente-public-album .pswp__preloader`]:+ { display: "none !important" },+ }}+ />+ <FileViewer+ open+ onClose={handleViewerClose}+ files={viewerFiles}+ initialIndex={0}+ disableEscapeClose+ disableDownload={!enableDownload}+ onDownload={enableDownload ? handleDownload : undefined}+ onVisualFeedback={onVisualFeedback}+ publicAlbumsCredentials={publicAlbumsCredentials}+ shouldCloseOnBrowserBack={false}+ collectionKey={collectionKey}+ onJoinAlbum={onJoinAlbum}+ enableComment={enableComment}+ enableJoin={enableJoin}+ />+ {isViewerPrimed && (+ <>+ <Box+ sx={{+ position: "fixed",+ top: {+ xs: "calc(env(titlebar-area-height, 0px) * 0.4 + 12px)",+ sm: "calc(env(titlebar-area-height, 0px) * 0.4 + 40px)",+ },+ left: 0,+ right: 0,+ pl: { xs: 1.5, sm: 5.5 },+ pr: { xs: 0.5, sm: 4 },+ zIndex: (theme) => theme.zIndex.drawer,+ pointerEvents: "none",+ opacity: topControlsVisible ? 1 : 0,+ transform: topControlsVisible+ ? "translateY(0)"+ : "translateY(-8px)",+ transition:+ "opacity 220ms ease, transform 220ms ease",+ }}+ >+ <Stack+ direction="row"+ justifyContent="space-between"+ alignItems="center"+ sx={{+ pointerEvents: topControlsVisible+ ? "auto"+ : "none",+ }}+ >+ <Stack+ direction="row"+ alignItems="center"+ spacing={1.5}+ >+ <Box+ component="a"+ href="https://ente.io"+ target="_blank"+ rel="noopener noreferrer"+ sx={{+ color: "white",+ opacity: 0.85,+ lineHeight: 0,+ "& svg": {+ width: "auto",+ height: { xs: 15, sm: 19 },+ },+ "&:hover": { opacity: 1 },+ }}+ >+ <EnteLogo height={15} />+ </Box>+ {isPhotoSwipeContentLoading ? (+ <CircularProgress+ size={16}+ thickness={5}+ sx={{+ color: "rgb(255 255 255 / 0.85)",+ }}+ />+ ) : (+ isLivePhotoFile && (+ <Stack+ direction="row"+ alignItems="center"+ spacing={0.5}+ >+ <FileViewerStyleButton+ onClick={+ handleToggleLivePhotoPlay+ }+ disabled={+ !livePhotoControls.playAvailable+ }+ aria-label={t("live")}+ className={+ livePhotoControls.isPlayOff+ ? "pswp-ente-off"+ : undefined+ }+ >+ <svg+ viewBox="0 0 32 32"+ width="32"+ height="32"+ fill="currentColor"+ aria-hidden="true"+ dangerouslySetInnerHTML={{+ __html: liveIconPath,+ }}+ />+ </FileViewerStyleButton>+ <FileViewerStyleButton+ onClick={+ handleToggleLivePhotoMute+ }+ disabled={+ !livePhotoControls.muteAvailable+ }+ aria-label={t("audio")}+ className={+ livePhotoControls.isMuteOff+ ? "pswp-ente-off"+ : undefined+ }+ >+ <svg+ viewBox="0 0 32 32"+ width="32"+ height="32"+ fill="currentColor"+ aria-hidden="true"+ dangerouslySetInnerHTML={{+ __html: volumeIconPath,+ }}+ />+ </FileViewerStyleButton>+ </Stack>+ )+ )}+ </Stack>+ <Stack+ direction="row"+ alignItems="center"+ spacing={1}+ >+ <Button+ variant="contained"+ onClick={handleTryEnte}+ sx={{+ borderRadius: "16px",+ paddingBlock: "11px",+ paddingInline: "20px",+ minHeight: "unset",+ textTransform: "none",+ fontWeight: "medium",+ color: "#fff",+ backgroundColor: "#08C225",+ "&:hover": {+ color: "#fff",+ backgroundColor: "#07A820",+ },+ }}+ >+ {t("try_ente")}+ </Button>+ <IconButton+ onClick={(event) =>+ setMenuAnchorEl(event.currentTarget)+ }+ aria-label={t("more")}+ sx={{+ color: "white",+ width: 40,+ height: 40,+ p: 0.75,+ bgcolor: "rgba(0, 0, 0, 0.4)",+ "&:hover": {+ bgcolor: "rgba(0, 0, 0, 0.55)",+ },+ }}+ >+ <MoreVertIcon />+ </IconButton>+ </Stack>+ </Stack>+ </Box>+ <MoreMenu+ open={!!menuAnchorEl}+ anchorEl={menuAnchorEl}+ onClose={handleMenuClose}+ disableAutoFocusItem+ slotProps={{ paper: { sx: { mt: "10px" } } }}+ >+ {enableDownload && (+ <MoreMenuItem+ onClick={() => {+ handleMenuClose();+ void handleDownload(file);+ }}+ >+ <MoreMenuItemTitle>+ {t("download")}+ </MoreMenuItemTitle>+ <DownloadOutlinedIcon />+ </MoreMenuItem>+ )}+ <MoreMenuItem onClick={handleOpenInfo}>+ <MoreMenuItemTitle>{t("info")}</MoreMenuItemTitle>+ <InfoOutlinedIcon />+ </MoreMenuItem>+ <MoreMenuItem onClick={() => void handleShare()}>+ <MoreMenuItemTitle>+ {t("share_action")}+ </MoreMenuItemTitle>+ <ShareOutlinedIcon />+ </MoreMenuItem>+ {canCopyAsPNG && (+ <MoreMenuItem+ onClick={() => void handleCopyAsPNG()}+ >+ <MoreMenuItemTitle>+ {t("copy_as_png")}+ </MoreMenuItemTitle>+ <ContentCopyIcon+ sx={{ "&&": { fontSize: "18px" } }}+ />+ </MoreMenuItem>+ )}+ <MoreMenuItem onClick={handleToggleFullscreen}>+ <MoreMenuItemTitle>+ {t("go_fullscreen")}+ </MoreMenuItemTitle>+ <FullscreenOutlinedIcon />+ </MoreMenuItem>+ </MoreMenu>+ </>+ )}+ {!isViewerPrimed && (+ <Box+ sx={{+ position: "fixed",+ inset: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ backgroundColor: "black",+ zIndex: (theme) => theme.zIndex.modal + 2,+ }}+ >+ <ActivityIndicator />+ </Box>+ )}+ <Notification+ open={showCopiedMessage}+ onClose={() => setShowCopiedMessage(false)}+ horizontal="left"+ attributes={{+ color: "secondary",+ startIcon: <CheckIcon />,+ title: "Copied!",+ }}+ />+ </>+ );+};++const MoreMenu = styled(Menu)(+ ({ theme }) => `+ & .MuiPaper-root {+ background-color: ${theme.vars.palette.fixed.dark.background.paper};+ }+ & .MuiList-root {+ padding-block: 2px;+ }+`,+);++const MoreMenuItem = styled(MenuItem)(+ ({ theme }) => `+ min-width: 210px;+ padding-block: 12px;+ min-height: auto;+ gap: 1;+ justify-content: space-between;+ align-items: center;+ color: rgba(255 255 255 / 0.85);+ &:hover {+ color: rgba(255 255 255 / 1);+ background-color: ${theme.vars.palette.fixed.dark.background.paper2}+ }++ .MuiSvgIcon-root {+ font-size: 20px;+ }+`,+);++const MoreMenuItemTitle: React.FC<React.PropsWithChildren> = ({ children }) => (+ <Typography sx={{ fontWeight: "medium" }}>{children}</Typography>+);++const FileViewerStyleButton = styled("button")`+ width: 44px;+ height: 44px;+ min-width: 44px;+ padding: 0;+ margin: 0;+ border: 0;+ background: transparent;+ display: flex;+ align-items: center;+ justify-content: center;+ cursor: pointer;+ opacity: 0.85;+ -webkit-appearance: none;+ -webkit-touch-callout: none;++ &:hover,+ &:active,+ &:focus {+ transition: none;+ opacity: 1;+ }++ svg {+ display: block;+ fill: white;+ }++ &.pswp-ente-off svg {+ fill: rgb(255 255 255 / 0.6);+ }++ &:disabled {+ opacity: 0.3;+ cursor: default;+ }+`;++/**+ * Return an "image/png" blob derived from the given source URL.+ */+const createImagePNGBlob = async (imageURL: string): Promise<Blob> =>+ new Promise((resolve, reject) => {+ const image = new Image();+ image.onload = () => {+ const canvas = document.createElement("canvas");+ canvas.width = image.width;+ canvas.height = image.height;+ canvas.getContext("2d")!.drawImage(image, 0, 0);+ canvas.toBlob(+ (blob) =>+ blob ? resolve(blob) : reject(new Error("toBlob failed")),+ "image/png",+ );+ };+ image.onerror = reject;+ image.src = imageURL;+ });diff --git a/web/apps/albums/vendor/photos/components/TripLayout/MapEvents.tsx b/web/apps/albums/vendor/photos/components/TripLayout/MapEvents.tsxnew file mode 100644index 0000000000..c85b8f5fad--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/MapEvents.tsx@@ -0,0 +1,31 @@+import { memo, useEffect } from "react";+import { useMap } from "react-leaflet";++interface MapEventsProps {+ setMapRef: (map: import("leaflet").Map) => void;+ setCurrentZoom: (zoom: number) => void;+ setTargetZoom: (zoom: number | null) => void;+}++export const MapEvents = memo<MapEventsProps>(+ ({ setMapRef, setCurrentZoom, setTargetZoom }) => {+ const map = useMap();++ useEffect(() => {+ setMapRef(map);++ const handleZoomEnd = () => {+ setCurrentZoom(map.getZoom());+ setTargetZoom(null);+ };++ map.on("zoomend", handleZoomEnd);++ return () => {+ map.off("zoomend", handleZoomEnd);+ };+ }, [map, setMapRef, setCurrentZoom, setTargetZoom]);++ return null;+ },+);diff --git a/web/apps/albums/vendor/photos/components/TripLayout/MobileCover.tsx b/web/apps/albums/vendor/photos/components/TripLayout/MobileCover.tsxnew file mode 100644index 0000000000..afe825a711--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/MobileCover.tsx@@ -0,0 +1,138 @@+import { Box, Skeleton, styled, Typography } from "@mui/material";+import { memo } from "react";+import type { JourneyPoint } from "./types";++interface MobileCoverProps {+ journeyData: JourneyPoint[];+ albumTitle?: string;+ coverImageUrl?: string | null;+}++export const MobileCover = memo<MobileCoverProps>(+ ({ journeyData, albumTitle, coverImageUrl }) => {+ const sortedData = [...journeyData].sort(+ (a, b) =>+ new Date(a.timestamp).getTime() -+ new Date(b.timestamp).getTime(),+ );+ const firstData = sortedData[0];+ const lastData = sortedData[sortedData.length - 1];+ if (!firstData || !lastData) {+ return null;+ }+ const firstDate = new Date(firstData.timestamp);+ const lastDate = new Date(lastData.timestamp);+ const diffTime = Math.abs(lastDate.getTime() - firstDate.getTime());+ const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));+ const monthYear = firstDate.toLocaleDateString("en-US", {+ month: "long",+ year: "numeric",+ });++ // Count unique locations based on unique name+country combinations+ const uniqueLocations = new Set(+ journeyData+ .filter((point) => point.name && point.country)+ .map((point) => `${point.name}, ${point.country}`),+ );+ const locationCount = uniqueLocations.size;++ return (+ <MobileCoverContainer>+ {coverImageUrl ? (+ <>+ <img+ src={coverImageUrl}+ alt="Trip Cover"+ style={{+ position: "absolute",+ inset: 0,+ width: "100%",+ height: "100%",+ objectFit: "cover",+ }}+ />+ <GradientOverlay />+ </>+ ) : (+ <Skeleton+ variant="rectangular"+ width="100%"+ height="100%"+ sx={{ bgcolor: "#f5f5f5" }}+ />+ )}++ <ContentContainer>+ {coverImageUrl ? (+ <>+ <TripTitle>{albumTitle || "Trip"}</TripTitle>+ <TripSubtitle>+ {monthYear} • {diffDays} days • {locationCount}{" "}+ locations+ </TripSubtitle>+ </>+ ) : (+ <>+ <Skeleton+ variant="text"+ width="200px"+ height="40px"+ sx={{+ mb: "5px",+ bgcolor: "rgba(255,255,255,0.95)",+ }}+ />+ <Skeleton+ variant="text"+ width="270px"+ height="24px"+ sx={{+ mb: "20px",+ bgcolor: "rgba(255,255,255,0.7)",+ }}+ />+ </>+ )}+ </ContentContainer>+ </MobileCoverContainer>+ );+ },+);++const MobileCoverContainer = styled(Box)({+ position: "relative",+ width: "100%",+ height: "100%",+ backgroundColor: "#e0e0e0",+});++const GradientOverlay = styled(Box)({+ position: "absolute",+ inset: 0,+ background:+ "linear-gradient(to bottom, rgba(0,0,0,0.3), transparent 30%, transparent 65%, rgba(0,0,0,0.9))",+});++const ContentContainer = styled(Box)({+ position: "absolute",+ bottom: "20px",+ left: "20px",+ right: "20px",+ color: "white",+});++const TripTitle = styled(Typography)({+ fontSize: "28px",+ fontWeight: "bold",+ marginBottom: "8px",+ lineHeight: 1.2,+ component: "h1",+});++const TripSubtitle = styled(Typography)({+ color: "rgba(255, 255, 255, 0.8)",+ fontSize: "15px",+ fontWeight: "600",+ paddingBottom: "20px",+});diff --git a/web/apps/albums/vendor/photos/components/TripLayout/MobileNavBar.tsx b/web/apps/albums/vendor/photos/components/TripLayout/MobileNavBar.tsxnew file mode 100644index 0000000000..d9f0c41916--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/MobileNavBar.tsx@@ -0,0 +1,206 @@+import AddPhotoAlternateOutlinedIcon from "@mui/icons-material/AddPhotoAlternateOutlined";+import CheckIcon from "@mui/icons-material/Check";+import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";+import ShareIcon from "@mui/icons-material/Share";+import { Box, Button, IconButton, styled } from "@mui/material";+import { FeedIcon } from "components/Collections/CollectionHeader";+import { EnteLogo } from "ente-base/components/EnteLogo";+import type { PublicAlbumsCredentials } from "ente-base/http";+import type { Collection } from "ente-media/collection";+import { Notification } from "ente-new/photos/components/Notification";+import { useJoinAlbum } from "hooks/useJoinAlbum";+import { t } from "i18next";+import { useState } from "react";+import { getEnteURL } from "utils/public-album";++interface MobileNavBarProps {+ onAddPhotos?: () => void;+ downloadAllFiles: () => void;+ enableDownload?: boolean;+ onShowFeed?: () => void;+ collectionTitle?: string;+ publicCollection?: Collection;+ accessToken?: string;+ collectionKey?: string;+ credentials?: React.RefObject<PublicAlbumsCredentials | undefined>;+}++export const MobileNavBar: React.FC<MobileNavBarProps> = ({+ onAddPhotos,+ downloadAllFiles,+ enableDownload,+ onShowFeed,+ collectionTitle,+ publicCollection,+ accessToken,+ collectionKey,+ credentials,+}) => {+ const [showCopiedMessage, setShowCopiedMessage] = useState(false);++ const enableJoin = publicCollection?.publicURLs[0]?.enableJoin;+ const { handleJoinAlbum } = useJoinAlbum({+ publicCollection,+ accessToken,+ collectionKey,+ credentials,+ });++ const handleShare = async () => {+ if (typeof window !== "undefined") {+ const albumName = collectionTitle || "Trip";+ const shareUrl = window.location.href;+ const shareText = `${albumName}\n${shareUrl}`;++ try {+ await navigator.share({ text: shareText });+ } catch (error) {+ if (+ !error ||+ (error instanceof Error && error.name !== "AbortError")+ ) {+ void navigator.clipboard.writeText(shareText);+ setShowCopiedMessage(true);+ setTimeout(() => setShowCopiedMessage(false), 2000);+ }+ }+ }+ };++ return (+ <>+ <MobileNavContainer>+ <LogoContainer>+ <EnteLogo />+ </LogoContainer>++ <ButtonGroup>+ <MobileNavButton onClick={handleShare}>+ <ShareIcon sx={{ fontSize: "15px" }} />+ </MobileNavButton>++ {onShowFeed && (+ <MobileNavButton onClick={onShowFeed}>+ <Box+ sx={{+ width: 16,+ height: 16,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ "& svg": { width: "100%", height: "100%" },+ }}+ >+ <FeedIcon />+ </Box>+ </MobileNavButton>+ )}++ {onAddPhotos && (+ <MobileNavButton onClick={onAddPhotos}>+ <AddPhotoAlternateOutlinedIcon+ sx={{ fontSize: "16px" }}+ />+ </MobileNavButton>+ )}++ {enableDownload && (+ <MobileNavButton onClick={downloadAllFiles}>+ <FileDownloadOutlinedIcon+ sx={{ fontSize: "18px" }}+ />+ </MobileNavButton>+ )}++ <MobileSignUpButton+ onClick={+ enableJoin+ ? handleJoinAlbum+ : () => {+ window.location.href = getEnteURL();+ }+ }+ >+ {enableJoin ? t("join_album") : t("try_ente")}+ </MobileSignUpButton>+ </ButtonGroup>+ </MobileNavContainer>++ <Notification+ open={showCopiedMessage}+ onClose={() => setShowCopiedMessage(false)}+ horizontal="left"+ attributes={{+ color: "secondary",+ startIcon: <CheckIcon />,+ title: "Copied!",+ }}+ />+ </>+ );+};++const MobileNavContainer = styled(Box)({+ position: "fixed",+ top: 0,+ left: 0,+ right: 0,+ height: "60px",+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ padding: "0 16px",+ backgroundColor: "transparent",+ zIndex: 2000,+ "&::after": {+ content: '""',+ position: "absolute",+ top: 0,+ left: 0,+ right: 0,+ height: "90px",+ background:+ "linear-gradient(180deg, rgba(0, 0, 0, 0.7) 0%, transparent 100%)",+ zIndex: -1,+ pointerEvents: "none",+ },+});++const LogoContainer = styled(Box)({+ display: "flex",+ alignItems: "center",+ "& svg": { height: "20px", width: "auto" },+});++const ButtonGroup = styled(Box)({+ display: "flex",+ alignItems: "center",+ gap: "8px",+});++const MobileNavButton = styled(IconButton)({+ padding: "6px",+ backgroundColor: "rgba(255, 255, 255, 0.9)",+ borderRadius: "6px",+ color: "#000000",+ transition: "background-color 0.2s",+ backdropFilter: "blur(10px)",+ width: "32px",+ height: "32px",+ boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 1)" },+});++const MobileSignUpButton = styled(Button)({+ padding: "6px 10px",+ fontSize: "13px",+ fontWeight: "600",+ whiteSpace: "nowrap",+ backgroundColor: "rgba(255, 255, 255, 0.9)",+ borderRadius: "6px",+ color: "#000000",+ transition: "background-color 0.2s",+ backdropFilter: "blur(10px)",+ boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 1)" },+});diff --git a/web/apps/albums/vendor/photos/components/TripLayout/MobileTimelineLocation.tsx b/web/apps/albums/vendor/photos/components/TripLayout/MobileTimelineLocation.tsxnew file mode 100644index 0000000000..32e32cab91--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/MobileTimelineLocation.tsx@@ -0,0 +1,158 @@+import { Box, Typography, styled } from "@mui/material";+import { memo } from "react";+import { PhotoFan } from "./PhotoFan";+import type { JourneyPoint } from "./types";++interface MobileTimelineLocationProps {+ cluster: JourneyPoint[];+ index: number;+ journeyData: JourneyPoint[];+ onRef: (el: HTMLDivElement | null) => void;+ onPhotoClick?: (cluster: JourneyPoint[], fileId: number) => void;+}++export const MobileTimelineLocation = memo<MobileTimelineLocationProps>(+ ({ cluster, index, journeyData, onRef, onPhotoClick }) => {+ const firstPhoto = cluster[0];+ if (!firstPhoto) return null;++ const sortedData = [...journeyData].sort(+ (a, b) =>+ new Date(a.timestamp).getTime() -+ new Date(b.timestamp).getTime(),+ );+ const firstData = sortedData[0];+ if (!firstData) return null;+ const firstDate = new Date(firstData.timestamp);+ const photoDate = new Date(firstPhoto.timestamp);++ const firstDateOnly = new Date(+ firstDate.getFullYear(),+ firstDate.getMonth(),+ firstDate.getDate(),+ );+ const photoDateOnly = new Date(+ photoDate.getFullYear(),+ photoDate.getMonth(),+ photoDate.getDate(),+ );+ const diffTime = photoDateOnly.getTime() - firstDateOnly.getTime();+ const dayNumber = Math.floor(diffTime / (1000 * 60 * 60 * 24)) + 1;++ return (+ <MobileLocationContainer+ ref={onRef}+ id={`location-${index}`}+ className="timeline-location"+ >+ {/* Centered Photo Fan Container */}+ <CenteredPhotoContainer>+ <PhotoFanWrapper>+ <PhotoFan+ cluster={cluster}+ onPhotoClick={onPhotoClick}+ />++ {/* Overlay text on top of main photo */}+ <PhotoOverlay>+ <DayBadge>+ DAY {dayNumber} •{" "}+ {new Date(firstPhoto.timestamp)+ .toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ })+ .toUpperCase()}+ </DayBadge>+ <LocationTitle>+ {firstPhoto.name && firstPhoto.name.length > 17+ ? firstPhoto.name.substring(0, 14) + "..."+ : firstPhoto.name}+ </LocationTitle>+ <LocationCountry>+ {firstPhoto.country}+ </LocationCountry>+ </PhotoOverlay>+ </PhotoFanWrapper>+ </CenteredPhotoContainer>+ </MobileLocationContainer>+ );+ },+);++// Styled components+const MobileLocationContainer = styled(Box)({+ position: "relative",+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "center",+ width: "100%",+ height: "40svh",+ scrollSnapAlign: "start",+ scrollSnapStop: "always",+ padding: "0",+});++const CenteredPhotoContainer = styled(Box)({+ position: "relative",+ display: "flex",+ justifyContent: "center",+});++const PhotoFanWrapper = styled(Box)({+ position: "relative",+ width: "180px",+ height: "240px",+ transition: "transform 0.3s ease-in-out",+ cursor: "pointer",+ "&:hover": { transform: "scale(1.05)" },+});++const PhotoOverlay = styled(Box)({+ position: "absolute",+ bottom: "2px",+ left: "2px",+ right: "2px",+ zIndex: 30,+ pointerEvents: "none",+ background:+ "linear-gradient(to top, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.4) 60%, transparent 100%)",+ borderRadius: "0 0 12px 12px",+ padding: "16px",+ minHeight: "fit-content",+});++const DayBadge = styled(Box)({+ display: "inline-flex",+ alignItems: "center",+ backgroundColor: "transparent",+ border: "none",+ borderRadius: "0",+ padding: "0",+ marginBottom: "4px",+ fontSize: "10px",+ fontWeight: "600",+ color: "white",+ textTransform: "uppercase",+ letterSpacing: "0.15em",+ textShadow: "0 2px 8px rgba(0, 0, 0, 0.8)",+});++const LocationTitle = styled(Typography)(() => ({+ fontSize: "18px",+ fontWeight: "600",+ color: "white",+ margin: "0 0 2px 0",+ lineHeight: "1.2",+ textShadow: "0 2px 8px rgba(0, 0, 0, 0.5)",+ component: "h3",+}));++const LocationCountry = styled(Typography)(() => ({+ fontSize: "13px",+ color: "rgba(200, 200, 200, 0.9)",+ margin: "0",+ textShadow: "0 1px 4px rgba(0, 0, 0, 0.5)",+ component: "p",+}));diff --git a/web/apps/albums/vendor/photos/components/TripLayout/MobileTripStarted.tsx b/web/apps/albums/vendor/photos/components/TripLayout/MobileTripStarted.tsxnew file mode 100644index 0000000000..9273bb29fb--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/MobileTripStarted.tsx@@ -0,0 +1,107 @@+import { Box, styled, Typography } from "@mui/material";+import { memo } from "react";+import type { JourneyPoint } from "./types";++interface MobileTripStartedProps {+ onRef: (el: HTMLDivElement | null) => void;+ journeyData: JourneyPoint[];+}++export const MobileTripStarted = memo<MobileTripStartedProps>(+ ({ onRef, journeyData }) => {+ // Get the first photo's date+ const sortedData = [...journeyData].sort(+ (a, b) =>+ new Date(a.timestamp).getTime() -+ new Date(b.timestamp).getTime(),+ );+ const firstPhoto = sortedData[0];+ const firstPhotoDate = firstPhoto+ ? new Date(firstPhoto.timestamp).toLocaleDateString("en-US", {+ year: "numeric",+ month: "long",+ day: "numeric",+ })+ : "";++ return (+ <MobileTripStartedContainer ref={onRef}>+ <MobileTripStartedContent>+ <MobileTripStartedText>+ <TripStartedTitle>Trip started</TripStartedTitle>+ {firstPhotoDate && (+ <>+ <br />+ <TripStartedDate>+ {firstPhotoDate}+ </TripStartedDate>+ </>+ )}+ </MobileTripStartedText>+ </MobileTripStartedContent>+ <MobileTripStartedDot />+ <MobileTripStartedLine />+ </MobileTripStartedContainer>+ );+ },+);++const MobileTripStartedContainer = styled(Box)({+ position: "relative",+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "center",+ height: "40svh",+ scrollSnapAlign: "start",+ scrollSnapStop: "always",+ padding: "0",+ overflow: "visible",+});++const MobileTripStartedContent = styled(Box)({+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ marginBottom: "20px",+});++const MobileTripStartedText = styled(Typography)(({ theme }) => ({+ fontSize: "16px",+ fontWeight: "500",+ color: theme.palette.text.secondary,+ textAlign: "center",+}));++const MobileTripStartedLine = styled(Box)(({ theme }) => ({+ position: "absolute",+ left: "50%",+ bottom: "-100px",+ height: "200px",+ width: "3px",+ backgroundColor: theme.palette.grey[300],+ transform: "translateX(-1.5px)",+ zIndex: 0,+}));++const TripStartedTitle = styled("span")(({ theme }) => ({+ fontSize: "14px",+ fontWeight: 500,+ color: theme.palette.text.primary,+}));++const TripStartedDate = styled("span")(({ theme }) => ({+ fontSize: "12px",+ fontWeight: "normal",+ color: theme.palette.text.secondary,+}));++const MobileTripStartedDot = styled(Box)(({ theme }) => ({+ width: "8px",+ height: "8px",+ backgroundColor: theme.palette.grey[500],+ borderRadius: "50%",+ margin: "10px auto 0 auto",+ position: "relative",+ zIndex: 1,+}));diff --git a/web/apps/albums/vendor/photos/components/TripLayout/PhotoFan.tsx b/web/apps/albums/vendor/photos/components/TripLayout/PhotoFan.tsxnew file mode 100644index 0000000000..290f9b860b--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/PhotoFan.tsx@@ -0,0 +1,207 @@+import { Box, styled } from "@mui/material";+import { memo } from "react";+import type { JourneyPoint } from "./types";++interface PhotoFanProps {+ cluster: JourneyPoint[];+ onPhotoClick?: (cluster: JourneyPoint[], fileId: number) => void;+}++export const PhotoFan = memo<PhotoFanProps>(({ cluster, onPhotoClick }) => {+ if (cluster.length === 0) {+ return null;+ }++ return (+ <PhotoFanContainer>+ {cluster.length >= 3 && (+ <>+ {cluster[1] && (+ <PhotoFrameLeft+ onClick={() =>+ cluster[1] &&+ onPhotoClick?.(cluster, cluster[1].fileId)+ }+ >+ <BackgroundLoadingBox />+ <ImageWrapper+ sx={{ transform: "skewY(8deg) scale(1.1)" }}+ >+ {cluster[1].image &&+ cluster[1].image.trim() !== "" && (+ <img+ src={cluster[1].image}+ alt={cluster[1].name}+ style={{+ position: "absolute",+ inset: 0,+ width: "100%",+ height: "100%",+ objectFit: "cover",+ zIndex: 1,+ }}+ />+ )}+ </ImageWrapper>+ </PhotoFrameLeft>+ )}+ {cluster[2] && (+ <PhotoFrameRight+ onClick={() =>+ cluster[2] &&+ onPhotoClick?.(cluster, cluster[2].fileId)+ }+ >+ <BackgroundLoadingBox />+ <ImageWrapper+ sx={{ transform: "skewY(-8deg) scale(1.1)" }}+ >+ {cluster[2].image &&+ cluster[2].image.trim() !== "" && (+ <img+ src={cluster[2].image}+ alt={cluster[2].name}+ style={{+ position: "absolute",+ inset: 0,+ width: "100%",+ height: "100%",+ objectFit: "cover",+ zIndex: 1,+ }}+ />+ )}+ </ImageWrapper>+ </PhotoFrameRight>+ )}+ </>+ )}++ {cluster[0] && (+ <MainPhotoFrame+ onClick={() =>+ cluster[0] && onPhotoClick?.(cluster, cluster[0].fileId)+ }+ >+ {cluster[0].image && cluster[0].image.trim() !== "" ? (+ <img+ src={cluster[0].image}+ alt={cluster[0].name}+ style={{+ position: "absolute",+ inset: 0,+ width: "100%",+ height: "100%",+ objectFit: "cover",+ }}+ />+ ) : (+ <LoadingBox />+ )}++ {cluster.length === 2 && <CountBadge>+1</CountBadge>}+ {cluster.length > 3 && (+ <CountBadge>+{cluster.length - 3}</CountBadge>+ )}+ </MainPhotoFrame>+ )}+ </PhotoFanContainer>+ );+});++// Styled components+const PhotoFanContainer = styled(Box)(({ theme }) => ({+ position: "relative",+ width: "180px",+ height: "240px",+ [theme.breakpoints.up("md")]: {+ transition: "transform 0.3s ease-in-out",+ cursor: "pointer",+ "&:hover": { transform: "scale(1.05)" },+ },+}));++const PhotoFrame = styled(Box)(() => ({+ position: "absolute",+ border: "2px solid white",+ zIndex: 10,+ width: "180px",+ height: "207px",+ borderRadius: "14px",+ overflow: "hidden",+ cursor: "pointer",+}));++const PhotoFrameLeft = styled(PhotoFrame)({+ transform: "translateX(-33px) skewY(-8deg)",+ top: "16.5px",+ left: "0",+});++const PhotoFrameRight = styled(PhotoFrame)({+ transform: "translateX(33px) skewY(8deg)",+ top: "16.5px",+ left: "0",+});++const MainPhotoFrame = styled(Box)(() => ({+ position: "relative",+ width: "100%",+ height: "100%",+ border: "2px solid white",+ zIndex: 20,+ borderRadius: "14px",+ overflow: "hidden",+ cursor: "pointer",+}));++const ImageWrapper = styled(Box)({+ position: "relative",+ width: "100%",+ height: "100%",+});++const CountBadge = styled(Box)({+ position: "absolute",+ top: "6px",+ right: "6px",+ background: "white",+ color: "black",+ borderRadius: "6px",+ padding: "4px 6px",+ minHeight: "20px",+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ fontSize: "11px",+ fontWeight: "600",+ boxShadow: "0 1px 3px rgba(0,0,0,0.3)",+});++const LoadingBox = styled(Box)({+ width: "100%",+ height: "100%",+ borderRadius: "12px",+ animation: "skeleton-pulse 1.5s ease-in-out infinite",+ "@keyframes skeleton-pulse": {+ "0%": { backgroundColor: "#ffffff" },+ "50%": { backgroundColor: "#f0f0f0" },+ "100%": { backgroundColor: "#ffffff" },+ },+});++const BackgroundLoadingBox = styled(Box)({+ position: "absolute",+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ borderRadius: "12px",+ zIndex: 0,+ animation: "skeleton-pulse 1.5s ease-in-out infinite",+ "@keyframes skeleton-pulse": {+ "0%": { backgroundColor: "#ffffff" },+ "50%": { backgroundColor: "#f0f0f0" },+ "100%": { backgroundColor: "#ffffff" },+ },+});diff --git a/web/apps/albums/vendor/photos/components/TripLayout/TimelineBaseLine.tsx b/web/apps/albums/vendor/photos/components/TripLayout/TimelineBaseLine.tsxnew file mode 100644index 0000000000..9aed539515--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/TimelineBaseLine.tsx@@ -0,0 +1,52 @@+import { Box, styled } from "@mui/material";+import { memo } from "react";++interface TimelineBaseLineProps {+ locationPositions: { top: number; center: number }[];+}++export const TimelineBaseLine = memo<TimelineBaseLineProps>(+ ({ locationPositions }) => {+ const timelineContainer = document.querySelector("#timeline-container");+ if (!timelineContainer || locationPositions.length === 0) {+ return null;+ }++ const locationElements =+ timelineContainer.querySelectorAll(".timeline-location");+ if (locationElements.length === 0) {+ return null;+ }++ const lastLocation = locationElements[+ locationElements.length - 1+ ] as HTMLElement;+ const lastLocationRect = lastLocation.getBoundingClientRect();+ const heightToLastDot =+ lastLocation.offsetTop + lastLocationRect.height / 2;++ const firstLocationCenter = locationPositions[0]?.center || 0;++ return (+ <SolidLine+ sx={{+ top: `${firstLocationCenter}px`,+ height: `${heightToLastDot - firstLocationCenter}px`,+ }}+ />+ );+ },+);++// Styled components+const BaseLine = styled(Box)(() => ({+ position: "absolute",+ left: "50%",+ transform: "translateX(-1.5px)",+ width: "3px",+ zIndex: 0,+}));++const SolidLine = styled(BaseLine)(({ theme }) => ({+ backgroundColor: theme.palette.grey[300],+}));diff --git a/web/apps/albums/vendor/photos/components/TripLayout/TimelineLocation.tsx b/web/apps/albums/vendor/photos/components/TripLayout/TimelineLocation.tsxnew file mode 100644index 0000000000..371a660523--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/TimelineLocation.tsx@@ -0,0 +1,229 @@+import { Box, Typography, styled } from "@mui/material";+import { memo } from "react";+import { PhotoFan } from "./PhotoFan";+import type { JourneyPoint } from "./types";++interface TimelineLocationProps {+ cluster: JourneyPoint[];+ index: number;+ photoClusters: JourneyPoint[][];+ scrollProgress: number;+ journeyData: JourneyPoint[];+ onRef: (el: HTMLDivElement | null) => void;+ onPhotoClick?: (cluster: JourneyPoint[], fileId: number) => void;+}++// Component for timeline location item+export const TimelineLocation = memo<TimelineLocationProps>(+ ({+ cluster,+ index,+ photoClusters,+ scrollProgress,+ journeyData,+ onRef,+ onPhotoClick,+ }) => {+ const isLeft = index % 2 === 0;+ const firstPhoto = cluster[0];+ if (!firstPhoto) return null;+ const sortedData = [...journeyData].sort(+ (a, b) =>+ new Date(a.timestamp).getTime() -+ new Date(b.timestamp).getTime(),+ );+ const firstData = sortedData[0];+ if (!firstData) return null;+ const firstDate = new Date(firstData.timestamp);+ const photoDate = new Date(firstPhoto.timestamp);++ const firstDateOnly = new Date(+ firstDate.getFullYear(),+ firstDate.getMonth(),+ firstDate.getDate(),+ );+ const photoDateOnly = new Date(+ photoDate.getFullYear(),+ photoDate.getMonth(),+ photoDate.getDate(),+ );+ const diffTime = photoDateOnly.getTime() - firstDateOnly.getTime();+ const dayNumber = Math.floor(diffTime / (1000 * 60 * 60 * 24)) + 1;++ // Show green only for the active location+ const currentLocationIndex = Math.round(+ scrollProgress * Math.max(0, photoClusters.length - 1),+ );+ const isActive = index === currentLocationIndex;++ return (+ <LocationContainer+ ref={onRef}+ id={`location-${index}`}+ className="timeline-location"+ sx={{+ marginBottom:+ index === photoClusters.length - 1 ? "48px" : "96px",+ }}+ >+ <DotBackground />+ <TimelineDot isReached={isActive} />++ {isLeft ? (+ <>+ <LeftContent>+ <DayBadge>+ DAY {dayNumber} •{" "}+ {new Date(firstPhoto.timestamp)+ .toLocaleDateString("en-US", {+ month: "long",+ day: "numeric",+ })+ .toUpperCase()}+ </DayBadge>+ <LocationTitle sx={{ textAlign: "right" }}>+ {firstPhoto.name}+ </LocationTitle>+ <LocationCountry sx={{ textAlign: "right" }}>+ {firstPhoto.country}+ </LocationCountry>+ </LeftContent>+ <RightPhotoContainer+ sx={{+ paddingLeft:+ cluster.length >= 3 ? "72px" : "40px",+ }}+ >+ <PhotoFan+ cluster={cluster}+ onPhotoClick={onPhotoClick}+ />+ </RightPhotoContainer>+ </>+ ) : (+ <>+ <LeftPhotoContainer+ sx={{+ paddingRight:+ cluster.length >= 3 ? "72px" : "40px",+ }}+ >+ <PhotoFan+ cluster={cluster}+ onPhotoClick={onPhotoClick}+ />+ </LeftPhotoContainer>+ <RightContent>+ <DayBadge>+ DAY {dayNumber} •{" "}+ {new Date(firstPhoto.timestamp)+ .toLocaleDateString("en-US", {+ month: "long",+ day: "numeric",+ })+ .toUpperCase()}+ </DayBadge>+ <LocationTitle sx={{ textAlign: "left" }}>+ {firstPhoto.name}+ </LocationTitle>+ <LocationCountry sx={{ textAlign: "left" }}>+ {firstPhoto.country}+ </LocationCountry>+ </RightContent>+ </>+ )}+ </LocationContainer>+ );+ },+);++// Styled components+const LocationContainer = styled(Box)({+ position: "relative",+ display: "flex",+ alignItems: "center",+});++const DotBackground = styled(Box)(({ theme }) => ({+ position: "absolute",+ left: "50%",+ top: "50%",+ transform: "translate(-50%, -50%)",+ width: "24px",+ height: "40px",+ borderRadius: "50%",+ zIndex: 10,+ backgroundColor: theme.palette.background.paper,+}));++const TimelineDot = styled(Box, {+ shouldForwardProp: (prop) => prop !== "isReached",+})<{ isReached: boolean }>(({ theme, isReached }) => ({+ position: "absolute",+ left: "50%",+ top: "50%",+ transform: "translate(-50%, -50%)",+ borderRadius: "50%",+ border: `2px solid ${theme.palette.background.paper}`,+ zIndex: 20,+ width: "12px",+ height: "12px",+ transition: "all 0.3s",+ backgroundColor: isReached+ ? theme.palette.success.main+ : theme.palette.text.primary,+ boxShadow: isReached+ ? `0 0 0 3px ${theme.palette.success.main}30, 0 0 0 6px ${theme.palette.success.main}15`+ : "none",+}));++const ContentContainer = styled(Box)({ width: "50%", paddingTop: "58px" });++const LeftContent = styled(ContentContainer)({+ paddingRight: "32px",+ textAlign: "right",+});++const RightContent = styled(ContentContainer)({+ paddingLeft: "32px",+ textAlign: "left",+});++const PhotoContainer = styled(Box)({ width: "50%" });++const LeftPhotoContainer = styled(PhotoContainer)({+ display: "flex",+ justifyContent: "flex-end",+});++const RightPhotoContainer = styled(PhotoContainer)({});++const DayBadge = styled(Box)(({ theme }) => ({+ display: "inline-flex",+ alignItems: "center",+ border: `1px solid ${theme.palette.grey[300]}`,+ borderRadius: "8px",+ padding: "4px 12px",+ marginBottom: "10px",+ fontSize: "11px",+ fontWeight: "600",+ color: theme.palette.text.secondary,+ textTransform: "uppercase",+ letterSpacing: "0.15em",+}));++const LocationTitle = styled(Typography)(({ theme }) => ({+ fontSize: "20px",+ fontWeight: "600",+ color: theme.palette.text.primary,+ margin: "0",+ lineHeight: "1.2",+ component: "h3",+}));++const LocationCountry = styled(Typography)(({ theme }) => ({+ fontSize: "14px",+ color: theme.palette.text.secondary,+ margin: "4px 0 0 0",+ component: "p",+}));diff --git a/web/apps/albums/vendor/photos/components/TripLayout/TimelineProgressLine.tsx b/web/apps/albums/vendor/photos/components/TripLayout/TimelineProgressLine.tsxnew file mode 100644index 0000000000..9e5c40a2c2--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/TimelineProgressLine.tsx@@ -0,0 +1,14 @@+import { memo } from "react";+import type { JourneyPoint } from "./types";++interface TimelineProgressLineProps {+ locationPositions: { top: number; center: number }[];+ scrollProgress: number;+ hasUserScrolled: boolean;+ photoClusters: JourneyPoint[][];+}++export const TimelineProgressLine = memo<TimelineProgressLineProps>(() => {+ // No longer showing progressive green line - green indicators only for current location+ return null;+});diff --git a/web/apps/albums/vendor/photos/components/TripLayout/TopNavButtons.tsx b/web/apps/albums/vendor/photos/components/TripLayout/TopNavButtons.tsxnew file mode 100644index 0000000000..9e03cb274e--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/TopNavButtons.tsx@@ -0,0 +1,144 @@+import AddPhotoAlternateOutlinedIcon from "@mui/icons-material/AddPhotoAlternateOutlined";+import CheckIcon from "@mui/icons-material/Check";+import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";+import ShareIcon from "@mui/icons-material/Share";+import { Box, Button, IconButton, styled } from "@mui/material";+import { FeedIcon } from "components/Collections/CollectionHeader";+import type { PublicAlbumsCredentials } from "ente-base/http";+import type { Collection } from "ente-media/collection";+import { Notification } from "ente-new/photos/components/Notification";+import { useJoinAlbum } from "hooks/useJoinAlbum";+import { t } from "i18next";+import { useState } from "react";+import { getEnteURL } from "utils/public-album";++interface TopNavButtonsProps {+ onAddPhotos?: () => void;+ downloadAllFiles: () => void;+ enableDownload?: boolean;+ onShowFeed?: () => void;+ publicCollection?: Collection;+ accessToken?: string;+ collectionKey?: string;+ credentials?: React.RefObject<PublicAlbumsCredentials | undefined>;+}++export const TopNavButtons: React.FC<TopNavButtonsProps> = ({+ onAddPhotos,+ downloadAllFiles,+ enableDownload,+ onShowFeed,+ publicCollection,+ accessToken,+ collectionKey,+ credentials,+}) => {+ const [showCopiedMessage, setShowCopiedMessage] = useState(false);++ const enableJoin = publicCollection?.publicURLs[0]?.enableJoin;+ const { handleJoinAlbum } = useJoinAlbum({+ publicCollection,+ accessToken,+ collectionKey,+ credentials,+ });++ const handleShare = () => {+ if (typeof window !== "undefined") {+ void navigator.clipboard.writeText(window.location.href);+ setShowCopiedMessage(true);+ setTimeout(() => setShowCopiedMessage(false), 2000);+ }+ };++ return (+ <>+ <ButtonContainer>+ <NavButton onClick={handleShare}>+ <ShareIcon sx={{ fontSize: "20px" }} />+ </NavButton>++ {onShowFeed && (+ <NavButton onClick={onShowFeed}>+ <FeedIcon />+ </NavButton>+ )}++ {onAddPhotos && (+ <NavButton onClick={onAddPhotos}>+ <AddPhotoAlternateOutlinedIcon+ sx={{ fontSize: "22px" }}+ />+ </NavButton>+ )}++ {enableDownload && (+ <NavButton onClick={downloadAllFiles}>+ <FileDownloadOutlinedIcon sx={{ fontSize: "23px" }} />+ </NavButton>+ )}++ <SignUpButton+ onClick={+ enableJoin+ ? handleJoinAlbum+ : () => {+ window.location.href = getEnteURL();+ }+ }+ >+ {enableJoin ? t("join_album") : t("try_ente")}+ </SignUpButton>+ </ButtonContainer>++ <Notification+ open={showCopiedMessage}+ onClose={() => setShowCopiedMessage(false)}+ horizontal="left"+ attributes={{+ color: "secondary",+ startIcon: <CheckIcon />,+ title: "Copied!",+ }}+ />+ </>+ );+};++// Styled components+const ButtonContainer = styled(Box)({+ position: "fixed",+ top: "58px",+ right: "58px",+ display: "flex",+ gap: "8px",+ zIndex: 2000,+});++const NavButton = styled(IconButton)({+ padding: "12px",+ backgroundColor: "rgba(255, 255, 255, 0.9)",+ borderRadius: "8px",+ color: "#1f2937",+ transition: "background-color 0.2s",+ backdropFilter: "blur(10px)",+ boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",+ width: "44px",+ height: "44px",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 1)" },+});++const SignUpButton = styled(Button)({+ padding: "12px 16px",+ marginLeft: "12px",+ fontSize: "16px",+ fontWeight: "600",+ whiteSpace: "nowrap",+ backgroundColor: "rgba(255, 255, 255, 0.9)",+ borderRadius: "8px",+ color: "#1f2937",+ transition: "background-color 0.2s",+ backdropFilter: "blur(10px)",+ boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 1)" },+});diff --git a/web/apps/albums/vendor/photos/components/TripLayout/TripCover.tsx b/web/apps/albums/vendor/photos/components/TripLayout/TripCover.tsxnew file mode 100644index 0000000000..9f8d65dbe0--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/TripCover.tsx@@ -0,0 +1,156 @@+import { Box, Skeleton, styled, Typography } from "@mui/material";+import { EnteLogo } from "ente-base/components/EnteLogo";+import { memo } from "react";+import type { JourneyPoint } from "./types";++interface TripCoverProps {+ journeyData: JourneyPoint[];+ albumTitle?: string;+ coverImageUrl?: string | null;+}++export const TripCover = memo<TripCoverProps>(+ ({ journeyData, albumTitle, coverImageUrl }) => {+ const sortedData = [...journeyData].sort(+ (a, b) =>+ new Date(a.timestamp).getTime() -+ new Date(b.timestamp).getTime(),+ );+ const firstData = sortedData[0];+ const lastData = sortedData[sortedData.length - 1];+ if (!firstData || !lastData) {+ return null;+ }+ const firstDate = new Date(firstData.timestamp);+ const lastDate = new Date(lastData.timestamp);+ const diffTime = Math.abs(lastDate.getTime() - firstDate.getTime());+ const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));+ const monthYear = firstDate.toLocaleDateString("en-US", {+ month: "long",+ year: "numeric",+ });++ // Count unique locations based on unique name+country combinations+ const uniqueLocations = new Set(+ journeyData+ .filter((point) => point.name && point.country)+ .map((point) => `${point.name}, ${point.country}`),+ );+ const locationCount = uniqueLocations.size;++ return (+ <CoverContainer>+ <CoverImageContainer>+ {coverImageUrl ? (+ <>+ <img+ src={coverImageUrl}+ alt="Trip Cover"+ style={{+ position: "absolute",+ inset: 0,+ width: "100%",+ height: "100%",+ objectFit: "cover",+ }}+ />+ <GradientOverlay />+ </>+ ) : (+ <Skeleton+ variant="rectangular"+ width="100%"+ height="100%"+ sx={{ bgcolor: "#f5f5f5" }}+ />+ )}++ <LogoContainer>+ <EnteLogo height={20} />+ </LogoContainer>++ <ContentContainer>+ {coverImageUrl ? (+ <>+ <TripTitle>{albumTitle || "Trip"}</TripTitle>+ <TripSubtitle>+ {monthYear} • {diffDays} days •{" "}+ {locationCount} locations+ </TripSubtitle>+ </>+ ) : (+ <>+ <Skeleton+ variant="text"+ width="200px"+ height="40px"+ sx={{+ mb: "5px",+ bgcolor: "rgba(255,255,255,0.95)",+ }}+ />+ <Skeleton+ variant="text"+ width="270px"+ height="24px"+ sx={{ bgcolor: "rgba(255,255,255,0.7)" }}+ />+ </>+ )}+ </ContentContainer>+ </CoverImageContainer>+ </CoverContainer>+ );+ },+);++// Styled components+const CoverContainer = styled(Box)({ marginBottom: "48px" });++const CoverImageContainer = styled(Box)(({ theme }) => ({+ aspectRatio: "16/8",+ position: "relative",+ marginBottom: "12px",+ borderRadius: "24px",+ overflow: "hidden",+ backgroundColor: "#e0e0e0",+ [theme.breakpoints.down(1440)]: { aspectRatio: "16/6" },+}));++const GradientOverlay = styled(Box)({+ position: "absolute",+ inset: 0,+ background:+ "linear-gradient(to bottom, rgba(0,0,0,0.4), transparent 30%, transparent 70%, rgba(0,0,0,0.7))",+});++const LogoContainer = styled(Box)(() => ({+ position: "absolute",+ top: "20px",+ left: "20px",+ color: "white",+}));++const ContentContainer = styled(Box)({+ position: "absolute",+ bottom: 0,+ left: 0,+ right: 0,+ padding: "24px",+ color: "white",+});++const TripTitle = styled(Typography)({+ fontSize: "30px",+ fontWeight: "bold",+ marginBottom: "10px",+ lineHeight: 1.2,+ component: "h1",+});++const TripSubtitle = styled(Typography)({+ color: "rgba(255, 255, 255, 0.8)",+ fontSize: "16px",+ fontWeight: "600",+ margin: "0",+});diff --git a/web/apps/albums/vendor/photos/components/TripLayout/TripMap.tsx b/web/apps/albums/vendor/photos/components/TripLayout/TripMap.tsxnew file mode 100644index 0000000000..4279c60241--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/TripMap.tsx@@ -0,0 +1,191 @@+import { Box, styled, useMediaQuery, useTheme } from "@mui/material";+import { useEffect, useState } from "react";++import { MapEvents } from "./MapEvents";+import { createIcon, getMapCenter } from "./mapHelpers";+import type { JourneyPoint } from "./types";++interface MapComponentsType {+ MapContainer: typeof import("react-leaflet").MapContainer;+ TileLayer: typeof import("react-leaflet").TileLayer;+ Marker: typeof import("react-leaflet").Marker;+}++interface TripMapProps {+ journeyData: JourneyPoint[];+ photoClusters: JourneyPoint[][];+ hasPhotoData: boolean;+ optimalZoom: number;+ scrollProgress: number;+ setMapRef: (map: import("leaflet").Map | null) => void;+ setCurrentZoom: (zoom: number) => void;+ setTargetZoom: (zoom: number | null) => void;+ onMarkerClick: (+ clusterIndex: number,+ clusterLat: number,+ clusterLng: number,+ ) => void;+}++export const TripMap: React.FC<TripMapProps> = ({+ journeyData,+ photoClusters,+ hasPhotoData,+ optimalZoom,+ scrollProgress,+ setMapRef,+ setCurrentZoom,+ setTargetZoom,+ onMarkerClick,+}) => {+ const theme = useTheme();+ const isMobileOrTablet = useMediaQuery(theme.breakpoints.down("md")); // 960px breakpoint for mobile and tablet++ // Load react-leaflet components client-side only to prevent SSR issues+ const [mapComponents, setMapComponents] =+ useState<MapComponentsType | null>(null);++ useEffect(() => {+ void import("react-leaflet")+ .then((mod) => {+ setMapComponents({+ MapContainer: mod.MapContainer,+ TileLayer: mod.TileLayer,+ Marker: mod.Marker,+ });+ })+ .catch((error: unknown) => {+ console.error("Failed to load react-leaflet:", error);+ });+ }, []);++ // Calculate current active location index based on scroll progress (same logic as in scrollUtils)+ let currentActiveLocationIndex = -1;+ if (photoClusters.length > 0) {+ if (isMobileOrTablet) {+ // Mobile: Slower progression - stay on each location longer+ currentActiveLocationIndex = Math.floor(+ scrollProgress * (photoClusters.length - 0.5),+ );+ } else {+ // Desktop: Use original logic+ currentActiveLocationIndex = Math.round(+ scrollProgress * Math.max(0, photoClusters.length - 1),+ );+ }+ }++ // Super clusters disabled - show all clusters individually+ const visibleClustersWithIndices = photoClusters.map(+ (cluster, originalIndex) => ({ cluster, originalIndex }),+ );++ // Return loading state if map components haven't loaded yet+ if (!mapComponents) {+ return <MapContainerWrapper hasPhotoData={false} />;+ }++ const { MapContainer, TileLayer, Marker } = mapComponents;++ return (+ <MapContainerWrapper hasPhotoData={hasPhotoData}>+ {hasPhotoData ? (+ <MapContainer+ center={getMapCenter(photoClusters, journeyData)}+ zoom={+ isMobileOrTablet+ ? Math.max(1, optimalZoom - 2)+ : optimalZoom+ }+ scrollWheelZoom={true}+ zoomControl={false}+ attributionControl={!isMobileOrTablet}+ style={{ width: "100%", height: "100%" }}+ >+ <MapEvents+ setMapRef={setMapRef}+ setCurrentZoom={setCurrentZoom}+ setTargetZoom={setTargetZoom}+ />+ {/* Stadia Alidade Satellite - includes both imagery and labels */}+ <TileLayer+ attribution={+ isMobileOrTablet+ ? ""+ : '© <a href="https://stadiamaps.com/" target="_blank" rel="noopener noreferrer">Stadia Maps</a>, © <a href="https://openmaptiles.org/" target="_blank" rel="noopener noreferrer">OpenMapTiles</a> © <a href="http://openstreetmap.org" target="_blank" rel="noopener noreferrer">OpenStreetMap</a> contributors'+ }+ url="https://tiles.stadiamaps.com/tiles/alidade_satellite/{z}/{x}/{y}{r}.jpg"+ maxZoom={20}+ updateWhenZooming={true}+ keepBuffer={isMobileOrTablet ? 3 : 1}+ />++ {/* Draw visible clusters */}+ {visibleClustersWithIndices.map((item, index) => {+ const { cluster, originalIndex } = item;+ const firstPhoto = cluster[0];+ if (!firstPhoto) return null;+ const avgLat =+ cluster.reduce((sum, p) => sum + p.lat, 0) /+ cluster.length;+ const avgLng =+ cluster.reduce((sum, p) => sum + p.lng, 0) /+ cluster.length;++ // Use the preserved original index+ const originalClusterIndex = originalIndex;+ // Show green only for active locations+ const isActive =+ originalClusterIndex === currentActiveLocationIndex;++ const icon = createIcon(+ firstPhoto.image,+ isMobileOrTablet ? 30 : 55,+ "#ffffff",+ cluster.length,+ isActive,+ );++ return icon ? (+ <Marker+ key={`cluster-${index}`}+ position={[avgLat, avgLng]}+ icon={icon}+ zIndexOffset={isActive ? 1000 : 0}+ eventHandlers={{+ click: () => {+ // Calculate cluster center+ const avgLat =+ cluster.reduce(+ (sum, p) => sum + p.lat,+ 0,+ ) / cluster.length;+ const avgLng =+ cluster.reduce(+ (sum, p) => sum + p.lng,+ 0,+ ) / cluster.length;+ onMarkerClick(+ originalClusterIndex,+ avgLat,+ avgLng,+ );+ },+ }}+ />+ ) : null;+ })}+ </MapContainer>+ ) : null}+ </MapContainerWrapper>+ );+};++// Styled components+const MapContainerWrapper = styled(Box, {+ shouldForwardProp: (prop) => prop !== "hasPhotoData",+})<{ hasPhotoData: boolean }>(({ hasPhotoData }) => ({+ width: "100%",+ height: "100%",+ backgroundColor: hasPhotoData ? "transparent" : "#000000",+}));diff --git a/web/apps/albums/vendor/photos/components/TripLayout/hooks/useDataProcessing.ts b/web/apps/albums/vendor/photos/components/TripLayout/hooks/useDataProcessing.tsnew file mode 100644index 0000000000..40625e1f0f--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/hooks/useDataProcessing.ts@@ -0,0 +1,85 @@+import { type Collection } from "ente-media/collection";+import { type EnteFile } from "ente-media/file";+import { useEffect } from "react";++import type { JourneyPoint } from "../types";+import { loadCoverImage, processPhotosData } from "../utils/dataProcessing";++export interface UseDataProcessingParams {+ files: EnteFile[];+ collection?: Collection;+ journeyData: JourneyPoint[];+ thumbnailsGeneratedRef: React.RefObject<boolean>;+ filesCountRef: React.RefObject<number>;+ locationDataRef: React.RefObject<+ Map<number, { name: string; country: string }>+ >;+ setJourneyData: (+ data: JourneyPoint[] | ((prev: JourneyPoint[]) => JourneyPoint[]),+ ) => void;+ setIsInitialLoad: (loading: boolean) => void;+ setIsLoadingLocations: (loading: boolean) => void;+ setCoverImageUrl: (url: string | null) => void;+}++export const useDataProcessing = ({+ files,+ collection,+ journeyData,+ thumbnailsGeneratedRef,+ filesCountRef,+ locationDataRef,+ setJourneyData,+ setIsInitialLoad,+ setIsLoadingLocations,+ setCoverImageUrl,+}: UseDataProcessingParams) => {+ // Process photos data when files change+ useEffect(() => {+ const hasFilesCountChanged = files.length !== filesCountRef.current;+ filesCountRef.current = files.length;++ if (!hasFilesCountChanged && journeyData.length > 0) {+ return;+ }++ thumbnailsGeneratedRef.current = false;++ const { photoData, hasLocationData } = processPhotosData({+ files,+ locationDataRef,+ });++ setJourneyData(photoData);+ setIsInitialLoad(false);++ if (hasLocationData) {+ setIsLoadingLocations(true);+ }+ }, [+ files,+ journeyData.length,+ filesCountRef,+ locationDataRef,+ thumbnailsGeneratedRef,+ setJourneyData,+ setIsInitialLoad,+ setIsLoadingLocations,+ ]);++ // Load cover image after data loads+ useEffect(() => {+ const loadCover = async () => {+ const coverUrl = await loadCoverImage({+ journeyData,+ files,+ collection,+ });+ if (coverUrl) {+ setCoverImageUrl(coverUrl);+ }+ };++ void loadCover();+ }, [journeyData, files, collection, setCoverImageUrl]);+};diff --git a/web/apps/albums/vendor/photos/components/TripLayout/hooks/useFileViewer.ts b/web/apps/albums/vendor/photos/components/TripLayout/hooks/useFileViewer.tsnew file mode 100644index 0000000000..b58ff27142--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/hooks/useFileViewer.ts@@ -0,0 +1,72 @@+import { type EnteFile } from "ente-media/file";+import { fileCreationTime } from "ente-media/file-metadata";+import { useCallback, useState } from "react";+import type { JourneyPoint } from "../types";++interface UseFileViewerProps {+ files: EnteFile[];+ onSetOpenFileViewer?: (open: boolean) => void;+ onRemotePull?: () => Promise<void>;+}++export const useFileViewer = ({+ files,+ onSetOpenFileViewer,+ onRemotePull,+}: UseFileViewerProps) => {+ const [openFileViewer, setOpenFileViewer] = useState(false);+ const [currentFileIndex, setCurrentFileIndex] = useState(0);+ const [viewerFiles, setViewerFiles] = useState<EnteFile[]>([]);++ const handleOpenFileViewer = useCallback(+ (cluster: JourneyPoint[], clickedFileId: number) => {+ // Get file IDs from the cluster+ const clusterFileIds = cluster.map((point) => point.fileId);++ // Filter files to only include those from the cluster+ const clusterFiles = files.filter((file) =>+ clusterFileIds.includes(file.id),+ );++ // Sort cluster files by creation time+ const sortedClusterFiles = [...clusterFiles].sort(+ (a, b) => fileCreationTime(a) - fileCreationTime(b),+ );++ // Find the index of the clicked photo in the cluster files+ const clickedIndex = sortedClusterFiles.findIndex(+ (f) => f.id === clickedFileId,+ );++ if (clickedIndex !== -1 && sortedClusterFiles.length > 0) {+ // Batch state updates to avoid multiple re-renders+ setViewerFiles(sortedClusterFiles);+ setCurrentFileIndex(clickedIndex);+ setOpenFileViewer(true);+ onSetOpenFileViewer?.(true);+ }+ },+ [files, onSetOpenFileViewer],+ );++ const handleCloseFileViewer = useCallback(() => {+ // Batch state updates+ setOpenFileViewer(false);+ onSetOpenFileViewer?.(false);+ }, [onSetOpenFileViewer]);++ const handleTriggerRemotePull = useCallback(() => {+ return onRemotePull?.() || Promise.resolve();+ }, [onRemotePull]);++ return {+ // State+ openFileViewer,+ currentFileIndex,+ viewerFiles,+ // Handlers+ handleOpenFileViewer,+ handleCloseFileViewer,+ handleTriggerRemotePull,+ };+};diff --git a/web/apps/albums/vendor/photos/components/TripLayout/hooks/useLocationFetching.ts b/web/apps/albums/vendor/photos/components/TripLayout/hooks/useLocationFetching.tsnew file mode 100644index 0000000000..db2833e6d5--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/hooks/useLocationFetching.ts@@ -0,0 +1,90 @@+import { useEffect, useRef } from "react";++import type { JourneyPoint } from "../types";+import { fetchLocationNames } from "../utils/dataProcessing";++export interface UseLocationFetchingParams {+ photoClusters: JourneyPoint[][];+ journeyData: JourneyPoint[];+ locationDataRef: React.RefObject<+ Map<number, { name: string; country: string }>+ >;+ setJourneyData: (+ data: JourneyPoint[] | ((prev: JourneyPoint[]) => JourneyPoint[]),+ ) => void;+ setIsLoadingLocations: (loading: boolean) => void;+}++export const useLocationFetching = ({+ photoClusters,+ locationDataRef,+ setJourneyData,+ setIsLoadingLocations,+}: UseLocationFetchingParams) => {+ const processedPhotoIdsRef = useRef<Set<number>>(new Set());+ const lastFetchedClustersRef = useRef<string>("");++ // Fetch location names for clusters+ useEffect(() => {+ // Create a stable key for current clusters to prevent duplicate fetches+ const clustersKey = photoClusters+ .map((cluster) => cluster.map((p) => p.fileId).join(","))+ .join("|");++ // Skip if we already fetched for these exact clusters+ if (clustersKey === lastFetchedClustersRef.current) {+ return;+ }++ const fetchNames = async () => {+ if (photoClusters.length === 0) return;++ // Get all current photo IDs+ const currentPhotoIds = new Set(+ photoClusters.flat().map((photo) => photo.fileId),+ );++ // Check if any photos need location fetching+ const needsFetching = photoClusters.some((cluster) =>+ cluster.some(+ (photo) => !locationDataRef.current.has(photo.fileId),+ ),+ );++ if (!needsFetching) {+ setIsLoadingLocations(false);+ return;+ }++ setIsLoadingLocations(true);+ lastFetchedClustersRef.current = clustersKey;++ try {+ const { updatedPhotos } = await fetchLocationNames({+ photoClusters,+ journeyData: [],+ locationDataRef,+ });++ if (updatedPhotos.size > 0) {+ setJourneyData((prevData) =>+ prevData.map((photo) => {+ const update = updatedPhotos.get(photo.fileId);+ if (update) {+ return { ...photo, ...update };+ }+ return photo;+ }),+ );+ }++ // Update processed photos set+ processedPhotoIdsRef.current = currentPhotoIds;+ } finally {+ setIsLoadingLocations(false);+ }+ };++ void fetchNames();+ }, [photoClusters, locationDataRef, setJourneyData, setIsLoadingLocations]);+};diff --git a/web/apps/albums/vendor/photos/components/TripLayout/hooks/useScrollHandling.ts b/web/apps/albums/vendor/photos/components/TripLayout/hooks/useScrollHandling.tsnew file mode 100644index 0000000000..2b1cdff5b0--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/hooks/useScrollHandling.ts@@ -0,0 +1,170 @@+import { useCallback, useEffect, useMemo } from "react";++import type { JourneyPoint } from "../types";+import { throttle } from "../utils/geocoding";+import {+ handleMarkerClick,+ handleTimelineScroll,+ scrollTimelineToLocation,+ updateLocationPositions,+ type PositionInfo,+} from "../utils/scrollUtils";++export interface UseScrollHandlingParams {+ timelineRef: React.RefObject<HTMLDivElement | null>;+ photoClusters: JourneyPoint[][];+ locationPositions: PositionInfo[];+ mapRef: L.Map | null;+ locationRefs: React.RefObject<(HTMLDivElement | null)[]>;+ isClusterClickScrollingRef: React.RefObject<boolean>;+ clusterClickTimeoutRef: React.RefObject<NodeJS.Timeout | null>;+ previousActiveLocationRef: React.RefObject<number>;+ setLocationPositions: (positions: PositionInfo[]) => void;+ setHasUserScrolled: (scrolled: boolean) => void;+ setScrollProgress: (progress: number) => void;+ setTargetZoom: (zoom: number | null) => void;+ isMobileOrTablet: boolean;+}++export const useScrollHandling = ({+ timelineRef,+ photoClusters,+ locationPositions,+ mapRef,+ locationRefs,+ isClusterClickScrollingRef,+ clusterClickTimeoutRef,+ previousActiveLocationRef,+ setLocationPositions,+ setHasUserScrolled,+ setScrollProgress,+ setTargetZoom,+ isMobileOrTablet,+}: UseScrollHandlingParams) => {+ // Update location positions callback+ const updatePositions = useCallback(() => {+ updateLocationPositions({+ locationRefs: locationRefs.current,+ setLocationPositions,+ });+ }, [locationRefs, setLocationPositions]);++ // Timeline scroll handler+ const timelineScrollHandler = useCallback(() => {+ handleTimelineScroll({+ timelineRef,+ photoClusters,+ locationPositions,+ mapRef,+ isClusterClickScrollingRef,+ setHasUserScrolled,+ setScrollProgress,+ previousActiveLocationRef,+ isMobileOrTablet,+ setTargetZoom,+ });+ }, [+ timelineRef,+ photoClusters,+ locationPositions,+ mapRef,+ isClusterClickScrollingRef,+ setHasUserScrolled,+ setScrollProgress,+ previousActiveLocationRef,+ isMobileOrTablet,+ setTargetZoom,+ ]);++ // Throttled scroll handler+ const throttledTimelineScroll = useMemo(+ () => throttle(timelineScrollHandler, 16),+ [timelineScrollHandler],+ );++ // Timeline scroll to location function+ const scrollToLocation = useCallback(+ (locationIndex: number) => {+ scrollTimelineToLocation({+ timelineRef,+ locationIndex,+ photoClusters,+ locationPositions,+ isMobileOrTablet,+ });+ },+ [timelineRef, photoClusters, locationPositions, isMobileOrTablet],+ );++ // Marker click handler+ const markerClickHandler = useCallback(+ (clusterIndex: number, clusterLat: number, clusterLng: number) => {+ handleMarkerClick({+ clusterIndex,+ clusterLat,+ clusterLng,+ photoClusters,+ mapRef,+ isClusterClickScrollingRef,+ clusterClickTimeoutRef,+ setScrollProgress,+ setHasUserScrolled,+ scrollTimelineToLocation: scrollToLocation,+ isMobileOrTablet,+ setTargetZoom,+ previousActiveLocationRef,+ });+ },+ [+ photoClusters,+ mapRef,+ isClusterClickScrollingRef,+ clusterClickTimeoutRef,+ setScrollProgress,+ setHasUserScrolled,+ scrollToLocation,+ isMobileOrTablet,+ setTargetZoom,+ previousActiveLocationRef,+ ],+ );++ // Update positions when locations render+ useEffect(() => {+ if (+ locationRefs.current.length === photoClusters.length &&+ photoClusters.length > 0+ ) {+ const timer = setTimeout(updatePositions, 100);+ return () => clearTimeout(timer);+ }+ return undefined;+ }, [photoClusters, updatePositions, locationRefs]);++ // Add scroll event listener+ useEffect(() => {+ const timelineContainer = timelineRef.current;+ if (!timelineContainer) return;++ timelineContainer.addEventListener("scroll", throttledTimelineScroll);++ return () => {+ timelineContainer.removeEventListener(+ "scroll",+ throttledTimelineScroll,+ );+ };+ }, [throttledTimelineScroll, timelineRef]);++ // Cleanup timeout on unmount+ useEffect(() => {+ return () => {+ if (clusterClickTimeoutRef.current) {+ clearTimeout(clusterClickTimeoutRef.current);+ clusterClickTimeoutRef.current = null;+ }+ };+ }, [clusterClickTimeoutRef]);++ return { updatePositions, scrollToLocation, markerClickHandler };+};diff --git a/web/apps/albums/vendor/photos/components/TripLayout/hooks/useThumbnailGeneration.ts b/web/apps/albums/vendor/photos/components/TripLayout/hooks/useThumbnailGeneration.tsnew file mode 100644index 0000000000..d999859dd9--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/hooks/useThumbnailGeneration.ts@@ -0,0 +1,74 @@+import { type EnteFile } from "ente-media/file";+import { useEffect, useRef } from "react";++import type { JourneyPoint } from "../types";+import { generateNeededThumbnails } from "../utils/dataProcessing";++export interface UseThumbnailGenerationParams {+ photoClusters: JourneyPoint[][];+ journeyData: JourneyPoint[];+ files: EnteFile[];+ thumbnailsGeneratedRef: React.RefObject<boolean>;+ setJourneyData: (+ data: JourneyPoint[] | ((prev: JourneyPoint[]) => JourneyPoint[]),+ ) => void;+}++export const useThumbnailGeneration = ({+ photoClusters,+ files,+ thumbnailsGeneratedRef,+ setJourneyData,+}: UseThumbnailGenerationParams) => {+ const processedPhotoIdsRef = useRef<Set<number>>(new Set());++ // Generate thumbnails for needed photos with progressive loading+ useEffect(() => {+ const generateThumbs = async () => {+ if (photoClusters.length === 0) return;++ // Get all current photo IDs+ const currentPhotoIds = new Set(+ photoClusters.flat().map((photo) => photo.fileId),+ );++ // Check if we have photos that need thumbnails+ const photosNeedingThumbnails = photoClusters+ .flat()+ .filter(+ (photo) =>+ !photo.image &&+ (!processedPhotoIdsRef.current.has(photo.fileId) ||+ !thumbnailsGeneratedRef.current),+ );++ if (photosNeedingThumbnails.length === 0) return;++ const { thumbnailUpdates } = await generateNeededThumbnails({+ photoClusters,+ files,+ });++ if (thumbnailUpdates.size > 0) {+ setJourneyData((prevData) =>+ prevData.map((photo) => {+ const thumbnailUrl = thumbnailUpdates.get(photo.fileId);+ if (thumbnailUrl && !photo.image) {+ return { ...photo, image: thumbnailUrl };+ }+ return photo;+ }),+ );+ }++ // Update processed photos set and mark as generated+ processedPhotoIdsRef.current = new Set([+ ...processedPhotoIdsRef.current,+ ...currentPhotoIds,+ ]);+ thumbnailsGeneratedRef.current = true;+ };++ void generateThumbs();+ }, [photoClusters, files, thumbnailsGeneratedRef, setJourneyData]);+};diff --git a/web/apps/albums/vendor/photos/components/TripLayout/index.tsx b/web/apps/albums/vendor/photos/components/TripLayout/index.tsxnew file mode 100644index 0000000000..cee4133053--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/index.tsx@@ -0,0 +1,822 @@+import { Box, styled, useMediaQuery, useTheme } from "@mui/material";+import { ActiveDownloadStatusNotifications } from "components/ActiveDownloadStatusNotifications";+import { useModalVisibility } from "ente-base/components/utils/modal";+import type { PublicAlbumsCredentials } from "ente-base/http";+import { useSaveGroupsActions } from "ente-gallery/components/utils/save-groups";+import {+ FileViewer,+ type FileViewerInitialSidebar,+} from "ente-gallery/components/viewer/FileViewer";+import {+ PublicFeedSidebar,+ type PublicFeedItemClickInfo,+} from "ente-gallery/components/viewer/PublicFeedSidebar";+import { downloadAndSaveCollectionFiles } from "ente-gallery/services/save";+import { type Collection } from "ente-media/collection";+import { type EnteFile } from "ente-media/file";+import { useJoinAlbum } from "hooks/useJoinAlbum";+import { useEffect, useRef, useState } from "react";++// Import extracted components+import { MobileCover } from "./MobileCover";+import { MobileNavBar } from "./MobileNavBar";+import { MobileTimelineLocation } from "./MobileTimelineLocation";+import { MobileTripStarted } from "./MobileTripStarted";+import { TimelineBaseLine } from "./TimelineBaseLine";+import { TimelineLocation } from "./TimelineLocation";+import { TimelineProgressLine } from "./TimelineProgressLine";+import { TopNavButtons } from "./TopNavButtons";+import { TripCover } from "./TripCover";++// Import hooks+import { useDataProcessing } from "./hooks/useDataProcessing";+import { useFileViewer } from "./hooks/useFileViewer";+import { useLocationFetching } from "./hooks/useLocationFetching";+import { useScrollHandling } from "./hooks/useScrollHandling";+import { useThumbnailGeneration } from "./hooks/useThumbnailGeneration";++// Import types and utils+import type { JourneyPoint } from "./types";+import type { PositionInfo } from "./utils/scrollUtils";++interface TripLayoutProps {+ files: EnteFile[];+ collection?: Collection;+ albumTitle?: string;+ user?: { id: number; email: string; token: string; [key: string]: unknown }; // User object for FileViewer+ // FileViewer related props (optional, can be added as needed)+ enableDownload?: boolean;+ onSetOpenFileViewer?: (open: boolean) => void;+ onRemotePull?: () => Promise<void>;+ onAddPhotos?: () => void; // Callback for add photos button+ // Join album props+ accessToken?: string;+ collectionKey?: string;+ credentials?: React.RefObject<PublicAlbumsCredentials | undefined>;+ /**+ * `true` if comments/reactions are enabled on the public link.+ * When `false`, the feed button will be hidden.+ */+ enableComment?: boolean;+ /**+ * `true` if the "Join album" option is enabled for this public link.+ * When `false`, the "Join album and like/comment" buttons will be hidden.+ */+ enableJoin?: boolean;+}++export const TripLayout: React.FC<TripLayoutProps> = ({+ files,+ collection,+ albumTitle,+ user,+ enableDownload,+ onSetOpenFileViewer,+ onRemotePull,+ onAddPhotos,+ accessToken,+ collectionKey,+ credentials,+ enableComment = true,+ enableJoin = true,+}) => {+ // Extract collection info if available+ const collectionTitle = collection?.name || albumTitle || "Trip";++ // Use media query for mobile/tablet detection (up to 960px)+ const theme = useTheme();+ const isMobileOrTablet = useMediaQuery(theme.breakpoints.down("md")); // 960px breakpoint for mobile and tablet++ // Save groups hook for download progress tracking+ const { onAddSaveGroup } = useSaveGroupsActions();+ const { show: showPublicFeed, props: publicFeedVisibilityProps } =+ useModalVisibility();++ // Navigation state for feed item clicks+ const [initialSidebar, setInitialSidebar] = useState<+ FileViewerInitialSidebar | undefined+ >(undefined);+ const [highlightCommentID, setHighlightCommentID] = useState<+ string | undefined+ >(undefined);++ // File viewer hook+ const {+ openFileViewer,+ currentFileIndex,+ viewerFiles,+ handleOpenFileViewer,+ handleCloseFileViewer,+ handleTriggerRemotePull,+ } = useFileViewer({ files, onSetOpenFileViewer, onRemotePull });++ // Join album hook for file viewer's public like modal+ const { handleJoinAlbum } = useJoinAlbum({+ publicCollection: collection,+ accessToken,+ collectionKey,+ credentials,+ });++ /**+ * Handle clicks on feed items to navigate to the file and open sidebar.+ */+ const handleFeedItemClick = (info: PublicFeedItemClickInfo) => {+ // Find the file in the journey data to get its cluster+ const journeyPoint = journeyData.find(+ (point) => point.fileId === info.fileID,+ );+ if (!journeyPoint) return;++ // Find the cluster that contains this file+ const cluster = photoClusters.find((c) =>+ c.some((p) => p.fileId === info.fileID),+ );+ if (!cluster) return;++ // Close the feed sidebar+ publicFeedVisibilityProps.onClose();++ // Determine which sidebar to open+ const sidebar: FileViewerInitialSidebar =+ info.type === "liked_photo" || info.type === "liked_video"+ ? "likes"+ : "comments";++ // Set navigation state and open file viewer+ setInitialSidebar(sidebar);+ setHighlightCommentID(info.commentID);+ handleOpenFileViewer(cluster, info.fileID);+ };++ /**+ * Handle file viewer close to clear navigation state.+ */+ const handleCloseFileViewerWithCleanup = () => {+ setInitialSidebar(undefined);+ setHighlightCommentID(undefined);+ handleCloseFileViewer();+ };++ // Download all files functionality+ const downloadAllFiles = () => {+ if (!collection) return;+ void downloadAndSaveCollectionFiles(+ collectionTitle,+ collection.id,+ files,+ undefined,+ onAddSaveGroup,+ );+ };++ const [journeyData, setJourneyData] = useState<JourneyPoint[]>([]);+ const [coverImageUrl, setCoverImageUrl] = useState<string | null>(null);+ const [isClient, setIsClient] = useState(false);+ const [isLoadingLocations, setIsLoadingLocations] = useState(false);+ const [isInitialLoad, setIsInitialLoad] = useState(true);+ const [currentZoom, setCurrentZoom] = useState(7); // Default zoom, will be updated by MapEvents and optimalZoom+ const [mapRef, setMapRef] = useState<import("leaflet").Map | null>(null);+ const [, setTargetZoom] = useState<number | null>(null); // Only setter is used by child components+ const [scrollProgress, setScrollProgress] = useState(0); // 0 to 1 representing scroll progress+ const [hasUserScrolled, setHasUserScrolled] = useState(false); // Track if user has actually scrolled+ const [showMobileCover, setShowMobileCover] = useState(true); // Track mobile cover state+ const [locationPositions, setLocationPositions] = useState<PositionInfo[]>(+ [],+ );+ const timelineRef = useRef<HTMLDivElement>(null);+ const locationRefs = useRef<(HTMLDivElement | null)[]>([]);+ const tripStartedRef = useRef<HTMLDivElement | null>(null);+ const isClusterClickScrollingRef = useRef(false); // Use ref for immediate updates+ const clusterClickTimeoutRef = useRef<NodeJS.Timeout | null>(null); // Timeout for cluster clicks+ const thumbnailsGeneratedRef = useRef(false); // Track if thumbnails have been generated+ const locationDataRef = useRef<+ Map<number, { name: string; country: string }>+ >(new Map()); // Track location data to prevent resets+ const filesCountRef = useRef<number>(0); // Track files count to detect real changes+ const previousActiveLocationRef = useRef<number>(-1); // Track previous active location for discrete panning++ const [photoClusters, setPhotoClusters] = useState<JourneyPoint[][]>([]);+ const [optimalZoom, setOptimalZoom] = useState(7);+ const [TripMapComponent, setTripMapComponent] =+ useState<React.ComponentType<{+ journeyData: JourneyPoint[];+ photoClusters: JourneyPoint[][];+ hasPhotoData: boolean;+ optimalZoom: number;+ scrollProgress: number;+ setMapRef: (map: import("leaflet").Map | null) => void;+ setCurrentZoom: (zoom: number) => void;+ setTargetZoom: (zoom: number | null) => void;+ onMarkerClick: (+ clusterIndex: number,+ clusterLat: number,+ clusterLng: number,+ ) => void;+ }> | null>(null);++ // Load client-side components and calculations+ useEffect(() => {+ if (isClient) {+ // Load TripMap component+ void import("./TripMap").then(({ TripMap }) => {+ setTripMapComponent(() => TripMap);+ });++ // Load mapHelpers and calculate clusters if we have data+ if (journeyData.length > 0) {+ void import("./mapHelpers").then(+ ({ clusterPhotosByProximity, calculateOptimalZoom }) => {+ const clusters = clusterPhotosByProximity(journeyData);++ // Sort clusters by their earliest timestamp to maintain chronological order+ const sortedClusters = clusters.sort((a, b) => {+ const earliestA = Math.min(+ ...a.map((p) =>+ new Date(p.timestamp).getTime(),+ ),+ );+ const earliestB = Math.min(+ ...b.map((p) =>+ new Date(p.timestamp).getTime(),+ ),+ );+ return earliestA - earliestB;+ });++ const optimalZoomLevel = calculateOptimalZoom();++ setPhotoClusters(sortedClusters);+ setOptimalZoom(optimalZoomLevel);+ },+ );+ }+ }+ }, [isClient, journeyData, isMobileOrTablet]);++ // Update currentZoom when optimalZoom changes and there's no mapRef yet+ useEffect(() => {+ if (!mapRef && optimalZoom !== currentZoom) {+ setCurrentZoom(optimalZoom);+ }+ }, [optimalZoom, mapRef, currentZoom]);++ // Set client-side rendering flag+ useEffect(() => {+ setIsClient(true);+ }, []);++ // Use extracted data processing hooks+ useDataProcessing({+ files,+ collection,+ journeyData,+ thumbnailsGeneratedRef,+ filesCountRef,+ locationDataRef,+ setJourneyData,+ setIsInitialLoad,+ setIsLoadingLocations,+ setCoverImageUrl,+ });++ useLocationFetching({+ photoClusters,+ journeyData,+ locationDataRef,+ setJourneyData,+ setIsLoadingLocations,+ });++ useThumbnailGeneration({+ photoClusters,+ journeyData,+ files,+ thumbnailsGeneratedRef,+ setJourneyData,+ });++ // Use extracted scroll handling hooks+ const { markerClickHandler } = useScrollHandling({+ timelineRef,+ photoClusters,+ locationPositions,+ mapRef,+ locationRefs,+ isClusterClickScrollingRef,+ clusterClickTimeoutRef,+ previousActiveLocationRef,+ setLocationPositions,+ isMobileOrTablet,+ setHasUserScrolled: (scrolled: boolean) => {+ setHasUserScrolled(scrolled);+ if (+ isMobileOrTablet &&+ tripStartedRef.current &&+ timelineRef.current+ ) {+ const timelineContainer = timelineRef.current;+ const tripStartedElement = tripStartedRef.current;+ const tripStartedRect =+ tripStartedElement.getBoundingClientRect();+ const timelineRect = timelineContainer.getBoundingClientRect();++ // Show/hide cover based on trip started position+ const threshold = timelineRect.top + timelineRect.height * 0.3;+ if (tripStartedRect.bottom < threshold) {+ setShowMobileCover(false);+ } else {+ setShowMobileCover(true);+ }+ }+ },+ setScrollProgress,+ setTargetZoom,+ });++ // Only wait for client-side rendering (needed for maps), but show layout immediately+ // Let individual components handle their own loading states+ if (!isClient) {+ return null; // SSR compatibility+ }++ // Show black background if no photo data yet+ const hasPhotoData = journeyData.length > 0;++ return (+ <TripLayoutContainer>+ {!openFileViewer &&+ (isMobileOrTablet ? (+ <MobileNavBar+ onAddPhotos={onAddPhotos}+ downloadAllFiles={downloadAllFiles}+ enableDownload={enableDownload}+ onShowFeed={enableComment ? showPublicFeed : undefined}+ collectionTitle={collectionTitle}+ publicCollection={collection}+ accessToken={accessToken}+ collectionKey={collectionKey}+ credentials={credentials}+ />+ ) : (+ <TopNavButtons+ onAddPhotos={onAddPhotos}+ downloadAllFiles={downloadAllFiles}+ enableDownload={enableDownload}+ onShowFeed={enableComment ? showPublicFeed : undefined}+ publicCollection={collection}+ accessToken={accessToken}+ collectionKey={collectionKey}+ credentials={credentials}+ />+ ))}+ {/* Mobile Layout */}+ {isMobileOrTablet ? (+ <MobileContainer>+ {/* Map takes 60% of height */}+ <MobileMapContainer>+ {TripMapComponent && (+ <TripMapComponent+ journeyData={journeyData}+ photoClusters={photoClusters}+ hasPhotoData={hasPhotoData}+ optimalZoom={optimalZoom}+ scrollProgress={scrollProgress}+ setMapRef={setMapRef}+ setCurrentZoom={setCurrentZoom}+ setTargetZoom={setTargetZoom}+ onMarkerClick={markerClickHandler}+ />+ )}+ {/* Cover overlay */}+ {!isInitialLoad && journeyData.length > 0 && (+ <MobileCoverOverlay show={showMobileCover}>+ <MobileCover+ journeyData={journeyData}+ albumTitle={collectionTitle}+ coverImageUrl={coverImageUrl}+ />+ </MobileCoverOverlay>+ )}+ </MobileMapContainer>++ {/* Timeline takes 40% of height */}+ <MobileTimelineContainer ref={timelineRef}>+ <MobileTimelineContent>+ {isInitialLoad ? (+ <MobileLoadingContainer>+ <LoadingSpinner />+ </MobileLoadingContainer>+ ) : journeyData.length > 0 ? (+ <div>+ {isLoadingLocations ? (+ <LocationsLoadingContainer>+ <LoadingSpinner />+ </LocationsLoadingContainer>+ ) : (+ <>+ <MobileTripStarted+ onRef={(el) => {+ tripStartedRef.current = el;+ }}+ journeyData={journeyData}+ />++ <TimelineContainer id="timeline-container">+ <MobileTimelineBaseLine+ photoClusters={+ photoClusters+ }+ />++ {photoClusters.map(+ (cluster, index) => (+ <MobileTimelineLocation+ key={index}+ cluster={cluster}+ index={index}+ journeyData={+ journeyData+ }+ onRef={(el) => {+ locationRefs.current[+ index+ ] = el;+ }}+ onPhotoClick={+ handleOpenFileViewer+ }+ />+ ),+ )}+ </TimelineContainer>+ </>+ )}+ </div>+ ) : (+ <NoPhotosContainer>+ No photos found with location information.+ </NoPhotosContainer>+ )}+ </MobileTimelineContent>+ </MobileTimelineContainer>+ </MobileContainer>+ ) : (+ <>+ {/* Desktop Layout - Left Sidebar - Floating Timeline */}+ <TimelineSidebar ref={timelineRef}>+ <TimelineContent>+ {isInitialLoad ? (+ <LoadingCoverPlaceholder>+ <LoadingCoverImage>+ <CoverGradientOverlay />+ <CoverPlaceholderContent>+ <PlaceholderTextBox+ sx={{+ height: "30px",+ width: "200px",+ mb: "2px",+ }}+ />+ <PlaceholderTextBox+ sx={{+ height: "16px",+ width: "120px",+ margin: 0,+ }}+ />+ </CoverPlaceholderContent>+ </LoadingCoverImage>+ <LoadingSpinnerContainer>+ <LoadingSpinner />+ </LoadingSpinnerContainer>+ </LoadingCoverPlaceholder>+ ) : journeyData.length > 0 ? (+ <div>+ <TripCover+ journeyData={journeyData}+ albumTitle={collectionTitle}+ coverImageUrl={coverImageUrl}+ />++ {isLoadingLocations ? (+ <LocationsLoadingContainer>+ <LoadingSpinner />+ </LocationsLoadingContainer>+ ) : (+ <>+ <TimelineContainer id="timeline-container">+ <TimelineBaseLine+ locationPositions={+ locationPositions+ }+ />++ <TimelineProgressLine+ locationPositions={+ locationPositions+ }+ scrollProgress={+ scrollProgress+ }+ hasUserScrolled={+ hasUserScrolled+ }+ photoClusters={+ photoClusters+ }+ />++ {photoClusters.map(+ (cluster, index) => (+ <TimelineLocation+ key={index}+ cluster={cluster}+ index={index}+ photoClusters={+ photoClusters+ }+ scrollProgress={+ scrollProgress+ }+ journeyData={+ journeyData+ }+ onRef={(el) => {+ locationRefs.current[+ index+ ] = el;+ }}+ onPhotoClick={+ handleOpenFileViewer+ }+ />+ ),+ )}+ </TimelineContainer>+ </>+ )}+ </div>+ ) : (+ <NoPhotosContainer>+ No photos found with location information.+ </NoPhotosContainer>+ )}+ </TimelineContent>+ </TimelineSidebar>++ {/* Desktop Map Container */}+ {TripMapComponent && (+ <TripMapComponent+ journeyData={journeyData}+ photoClusters={photoClusters}+ hasPhotoData={hasPhotoData}+ optimalZoom={optimalZoom}+ scrollProgress={scrollProgress}+ setMapRef={setMapRef}+ setCurrentZoom={setCurrentZoom}+ setTargetZoom={setTargetZoom}+ onMarkerClick={markerClickHandler}+ />+ )}+ </>+ )}++ {/* FileViewer for photo gallery */}+ <FileViewer+ open={openFileViewer}+ onClose={handleCloseFileViewerWithCleanup}+ initialIndex={currentFileIndex}+ initialSidebar={initialSidebar}+ highlightCommentID={highlightCommentID}+ files={viewerFiles}+ user={user}+ disableDownload={!enableDownload}+ onTriggerRemotePull={handleTriggerRemotePull}+ onRemoteFilesPull={handleTriggerRemotePull}+ onVisualFeedback={() => {+ // No-op: Trip viewer is read-only and doesn't need visual feedback+ }}+ publicAlbumsCredentials={credentials?.current}+ collectionKey={collectionKey}+ onJoinAlbum={handleJoinAlbum}+ enableComment={enableComment}+ enableJoin={enableJoin}+ />++ {/* Download progress notifications */}+ <ActiveDownloadStatusNotifications fullWidthOnMobile />++ {/* Public feed sidebar */}+ {collection && credentials?.current && collectionKey && (+ <PublicFeedSidebar+ {...publicFeedVisibilityProps}+ files={files}+ credentials={credentials.current}+ collectionKey={collectionKey}+ onItemClick={handleFeedItemClick}+ />+ )}+ </TripLayoutContainer>+ );+};++// Styled components+const TripLayoutContainer = styled(Box)({+ position: "relative",+ width: "100%",+ height: "100%",+});++const TimelineSidebar = styled(Box)(({ theme }) => ({+ position: "absolute",+ left: "16px",+ top: "16px",+ bottom: "16px",+ width: "680px",+ overflow: "auto",+ boxShadow: theme.shadows[10],+ backgroundColor: theme.palette.background.paper,+ zIndex: 1000,+ borderRadius: "48px",+ "&::-webkit-scrollbar": { width: "8px" },+ "&::-webkit-scrollbar-track": {+ background: "transparent",+ borderRadius: "48px",+ },+ "&::-webkit-scrollbar-thumb": {+ background: theme.palette.divider,+ borderRadius: "48px",+ "&:hover": { background: theme.palette.text.disabled },+ },+ scrollbarWidth: "thin",+ scrollbarColor: `${theme.palette.divider} transparent`,+ [theme.breakpoints.up(1920)]: { width: "960px" },+}));++const TimelineContent = styled(Box)({+ padding: "32px",+ height: "100%",+ display: "flex",+ flexDirection: "column",+});++const LoadingCoverPlaceholder = styled(Box)({ marginBottom: "96px" });++const LoadingCoverImage = styled(Box)(({ theme }) => ({+ aspectRatio: "16/8",+ position: "relative",+ marginBottom: "12px",+ borderRadius: "24px",+ overflow: "hidden",+ backgroundColor: theme.palette.grey[200],+ animation: "pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",+ "@keyframes pulse": { "0%, 100%": { opacity: 1 }, "50%": { opacity: 0.5 } },+}));++const CoverGradientOverlay = styled(Box)({+ position: "absolute",+ bottom: 0,+ left: 0,+ right: 0,+ height: "128px",+ background: "linear-gradient(to top, rgba(0,0,0,0.3), transparent)",+});++const CoverPlaceholderContent = styled(Box)({+ position: "absolute",+ bottom: 0,+ left: 0,+ right: 0,+ padding: "24px",+ color: "rgba(255, 255, 255, 0.7)",+});++const PlaceholderTextBox = styled(Box)({+ backgroundColor: "rgba(255, 255, 255, 0.2)",+ borderRadius: "4px",+});++const LoadingSpinnerContainer = styled(Box)({+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ padding: "60px 20px",+ minHeight: "200px",+});++const LoadingSpinner = styled(Box)(({ theme }) => ({+ animation: "spin 1s linear infinite",+ borderRadius: "50%",+ height: "40px",+ width: "40px",+ borderTop: `3px solid ${theme.palette.success.main}`,+ borderRight: "3px solid transparent",+ borderBottom: `3px solid ${theme.palette.success.main}`,+ borderLeft: "3px solid transparent",+ "@keyframes spin": {+ from: { transform: "rotate(0deg)" },+ to: { transform: "rotate(360deg)" },+ },+}));++const LocationsLoadingContainer = styled(Box)({+ position: "relative",+ marginTop: "64px",+ marginBottom: "200px",+ textAlign: "center",+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+});++const TimelineContainer = styled(Box)({ position: "relative" });++const NoPhotosContainer = styled(Box)(({ theme }) => ({+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ textAlign: "center",+ width: "100%",+ flex: 1,+ padding: "40px 20px",+ color: theme.palette.text.secondary,+ fontSize: "16px",+}));++// Mobile specific styled components+const MobileContainer = styled(Box)({+ display: "flex",+ flexDirection: "column",+ height: "100svh",+ width: "100%",+});++const MobileMapContainer = styled(Box)({+ height: "calc(60svh + 20px)",+ position: "relative",+ overflow: "hidden",+});++const MobileTimelineContainer = styled(Box)(({ theme }) => ({+ height: "40svh",+ marginTop: "-20px",+ overflow: "auto",+ backgroundColor: theme.palette.background.paper,+ boxShadow: `0 -4px 20px rgba(0, 0, 0, 0.1)`,+ scrollSnapType: "y mandatory",+ borderTopLeftRadius: "24px",+ borderTopRightRadius: "24px",+ zIndex: 1001,+ "&::-webkit-scrollbar": { width: "6px" },+ "&::-webkit-scrollbar-track": { background: "transparent" },+ "&::-webkit-scrollbar-thumb": {+ background: theme.palette.divider,+ borderRadius: "20px",+ "&:hover": { background: theme.palette.text.disabled },+ },+ scrollbarWidth: "thin",+ scrollbarColor: `${theme.palette.divider} transparent`,+}));++const MobileCoverOverlay = styled(Box, {+ shouldForwardProp: (prop) => prop !== "show",+})<{ show: boolean }>(({ show }) => ({+ position: "absolute",+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ zIndex: 1000,+ opacity: show ? 1 : 0,+ transition: "opacity 0.5s ease-in-out",+ pointerEvents: show ? "auto" : "none",+}));++const MobileTimelineContent = styled(Box)({+ padding: "0",+ height: "100%",+ display: "flex",+ flexDirection: "column",+});++const MobileLoadingContainer = styled(Box)({+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ height: "100%",+ width: "100%",+});++const MobileTimelineBaseLine = styled(Box, {+ shouldForwardProp: (prop) => prop !== "photoClusters",+})<{ photoClusters: JourneyPoint[][] }>(({ theme, photoClusters }) => ({+ position: "absolute",+ left: "50%",+ top: "-15svh",+ height: `${(photoClusters.length - 1) * 40 + 35}svh`,+ width: "3px",+ backgroundColor: theme.palette.grey[300],+ transform: "translateX(-1.5px)",+ zIndex: 0,+}));diff --git a/web/apps/albums/vendor/photos/components/TripLayout/mapHelpers.ts b/web/apps/albums/vendor/photos/components/TripLayout/mapHelpers.tsnew file mode 100644index 0000000000..9ef10b15be--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/mapHelpers.ts@@ -0,0 +1,311 @@+import { haveWindow } from "ente-base/env";+import type { JourneyPoint } from "./types";+import { iconCache } from "./utils/geocoding";++// Mobile/tablet detection using media query breakpoint+const isMobileDevice = () => {+ if (typeof window === "undefined") return false;+ // Use 960px breakpoint to match Material-UI's "md" breakpoint for mobile and tablet+ return window.innerWidth < 960;+};++// Conditionally import leaflet only in browser environment+const getLeaflet = () => {+ if (haveWindow()) {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ return require("leaflet") as typeof import("leaflet");+ }+ return null;+};++// Calculate distance between two points using Haversine formula (returns distance in km)+export const calculateDistance = (+ lat1: number,+ lng1: number,+ lat2: number,+ lng2: number,+): number => {+ const R = 6371; // Radius of Earth in kilometers+ const dLat = (lat2 - lat1) * (Math.PI / 180);+ const dLng = (lng2 - lng1) * (Math.PI / 180);+ const a =+ Math.sin(dLat / 2) * Math.sin(dLat / 2) ++ Math.cos(lat1 * (Math.PI / 180)) *+ Math.cos(lat2 * (Math.PI / 180)) *+ Math.sin(dLng / 2) *+ Math.sin(dLng / 2);+ const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));+ return R * c;+};++// Geographic clustering with responsive distance thresholds and day separation+export const clusterPhotosByProximity = (photos: JourneyPoint[]) => {+ if (photos.length === 0) return [];++ // 5km clustering distance (roughly 0.05 degrees)+ const distanceThreshold = 0.05; // About 5km in degrees++ // First, group photos by day+ const photosByDay = new Map<string, JourneyPoint[]>();+ photos.forEach((photo) => {+ const date = new Date(photo.timestamp);+ const dayKey = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;++ if (!photosByDay.has(dayKey)) {+ photosByDay.set(dayKey, []);+ }+ photosByDay.get(dayKey)!.push(photo);+ });++ // Then cluster within each day+ const allClusters: JourneyPoint[][] = [];++ photosByDay.forEach((dayPhotos) => {+ const visited = new Set<number>();++ dayPhotos.forEach((photo, i) => {+ if (visited.has(i)) return;++ const cluster = [photo];+ visited.add(i);++ dayPhotos.forEach((otherPhoto, j) => {+ if (i === j || visited.has(j)) return;++ const distance = Math.sqrt(+ Math.pow(photo.lat - otherPhoto.lat, 2) ++ Math.pow(photo.lng - otherPhoto.lng, 2),+ );++ if (distance < distanceThreshold) {+ cluster.push(otherPhoto);+ visited.add(j);+ }+ });++ allClusters.push(cluster);+ });+ });++ return allClusters;+};++// Return fixed zoom level of 10 for consistent positioning+export const calculateOptimalZoom = (): number => {+ // Return fixed zoom of 10 as per new requirements+ return 10;+};++// Function to create icon with specific image and progress styling+export const createIcon = (+ imageSrc: string,+ size = 40,+ borderColor = "#ffffff",+ _clusterCount?: number,+ isReached = false,+): import("leaflet").DivIcon | null => {+ const leaflet = getLeaflet();+ if (typeof window === "undefined" || !leaflet) {+ // Fallback icon for SSR+ return null;+ }++ const pinSize = size + 16; // Make it square and bigger+ const triangleHeight = size <= 30 ? 7 : 10; // Smaller triangle for mobile+ const pinHeight = pinSize + triangleHeight + 2; // Add space for triangle+ const hasImage = imageSrc && imageSrc.trim() !== "";++ // Adjust border radius for smaller mobile markers+ const outerBorderRadius = size <= 30 ? 14 : 16;+ const innerBorderRadius = size <= 30 ? 10 : 12;++ // Create cache key based on all parameters including border radius and triangle size+ const cacheKey = `icon_${imageSrc}_${size}_${borderColor}_${isReached}_${outerBorderRadius}_${innerBorderRadius}_${triangleHeight}`;++ const cachedIcon = iconCache.get(cacheKey);+ if (cachedIcon) {+ return cachedIcon;+ }++ const icon = leaflet.divIcon({+ html: `+ <div class="photo-pin${isReached ? " reached" : ""}" style="+ width: ${pinSize}px;+ height: ${pinHeight}px;+ position: relative;+ cursor: pointer;+ transition: all 0.3s ease;+ ">+ <!-- Main rounded rectangle container -->+ <div style="+ width: ${pinSize}px;+ height: ${pinSize}px;+ border-radius: ${outerBorderRadius}px;+ background: ${isReached ? "#22c55e" : "white"};+ border: 2px solid ${isReached ? "#22c55e" : borderColor};+ padding: 4px;+ position: relative;+ overflow: hidden;+ transition: background-color 0.3s ease, border-color 0.3s ease;+ "+ onmouseover="this.style.background='#22c55e'; this.style.borderColor='#22c55e'; this.nextElementSibling.style.borderTopColor='#22c55e';"+ onmouseout="this.style.background='${isReached ? "#22c55e" : "white"}'; this.style.borderColor='${isReached ? "#22c55e" : "#ffffff"}'; this.nextElementSibling.style.borderTopColor='${isReached ? "#22c55e" : "white"}';"+ >+ ${+ hasImage+ ? `+ <!-- Image inside the rounded rectangle -->+ <img+ src="${imageSrc}"+ style="+ width: 100%;+ height: 100%;+ object-fit: cover;+ border-radius: ${innerBorderRadius}px;+ "+ alt="Location"+ />+ `+ : `+ <!-- Loading skeleton when no image -->+ <div style="+ width: 100%;+ height: 100%;+ border-radius: ${innerBorderRadius}px;+ animation: skeleton-pulse 1.5s ease-in-out infinite;+ "></div>+ <style>+ @keyframes skeleton-pulse {+ 0% { background-color: #ffffff; }+ 50% { background-color: #f0f0f0; }+ 100% { background-color: #ffffff; }+ }+ </style>+ `+ }+ </div>++ <!-- Triangle at the bottom -->+ <div style="+ position: absolute;+ bottom: 2px;+ left: 50%;+ transform: translateX(-50%);+ width: 0;+ height: 0;+ border-left: ${triangleHeight}px solid transparent;+ border-right: ${triangleHeight}px solid transparent;+ border-top: ${triangleHeight}px solid ${isReached ? "#22c55e" : "white"};+ transition: border-top-color 0.3s ease;+ "></div>+ </div>+ `,+ className: "custom-pin-marker",+ iconSize: [pinSize, pinHeight],+ iconAnchor: [pinSize / 2, pinHeight],+ popupAnchor: [0, -pinHeight],+ });++ // Cache the icon+ iconCache.set(cacheKey, icon);+ return icon;+};++// Calculate map center with first location positioned at 20% from right edge+export const getMapCenter = (+ photoClusters: JourneyPoint[][],+ journeyData: JourneyPoint[],+): [number, number] => {+ // If no clusters yet, check journey data+ if (photoClusters.length === 0) {+ const firstPoint = journeyData[0];+ if (!firstPoint) return [0, 0]; // Fallback, but map won't render anyway+ return [firstPoint.lat, firstPoint.lng];+ }++ // Start at first cluster center+ const firstCluster = photoClusters[0];+ if (!firstCluster || firstCluster.length === 0) return [0, 0]; // Fallback, but map won't render anyway++ const firstLat =+ firstCluster.reduce((sum, p) => sum + p.lat, 0) / firstCluster.length;+ const firstLng =+ firstCluster.reduce((sum, p) => sum + p.lng, 0) / firstCluster.length;++ // Position first location at 20% from right edge (80% from left)+ // At zoom level 10, each pixel represents approximately 152.87 meters+ // On mobile, timeline is at bottom so full width is available; on desktop, timeline takes up 50% of screen width+ // We want the first location to be at 20% from right of the visible map area+ // This means shifting map center left so marker appears more to the right++ const isMobile = isMobileDevice();+ const timelineWidthRatio = isMobile ? 0.0 : 0.5; // Mobile: full width, Desktop: timeline takes up 50% of screen++ // At zoom 10, approximately 0.35 degrees per 1000px at equator+ // For positioning, we need to shift the longitude to place marker at desired position+ const degreesPerPixelAtZoom10 = 0.35 / 1000; // rough approximation+ const basePixelsToShift =+ (window.innerWidth || 1400) * (1 - timelineWidthRatio);+ const pixelsToShiftFor20Percent = isMobile+ ? basePixelsToShift * 0.6 // Mobile: less aggressive positioning (60% instead of 300%)+ : basePixelsToShift * 3.0; // Desktop: 300% of visible map width to shift map left+ const lngShift = pixelsToShiftFor20Percent * degreesPerPixelAtZoom10;++ const adjustedLng = firstLng - lngShift;++ return [firstLat, adjustedLng];+};++// Calculate position for a location to be at 20% from right edge of visible map+export const getLocationPosition = (+ lat: number,+ lng: number,+): [number, number] => {+ // Position location at 20% from right edge (80% from left) of visible map area+ // On mobile, the timeline is at the bottom, not the side, so full width is available for map+ const isMobile = isMobileDevice();+ const timelineWidthRatio = isMobile ? 0.0 : 0.5; // Mobile: full width, Desktop: timeline takes up 50% of screen+ const degreesPerPixelAtZoom10 = 0.35 / 1000; // rough approximation at zoom 10++ // Calculate shift to position marker at 20% from right edge of visible map+ // Need to shift map center left so the marker appears more to the right+ // On mobile, use less aggressive positioning since we have full width+ const basePixelsToShift =+ (window.innerWidth || 1400) * (1 - timelineWidthRatio);+ const pixelsToShiftFor20Percent = isMobile+ ? basePixelsToShift * 0.6 // Mobile: less aggressive positioning (60% instead of 300%)+ : basePixelsToShift * 3.0; // Desktop: 300% of visible map width to shift map left+ const lngShift = pixelsToShiftFor20Percent * degreesPerPixelAtZoom10;++ return [lat, lng - lngShift];+};++// Calculate position for a location to be at 20% from right edge at a specific zoom level+export const getLocationPositionAtZoom = (+ lat: number,+ lng: number,+ zoom: number,+): [number, number] => {+ // Position location at 20% from right edge (80% from left) of visible map area+ // On mobile, the timeline is at the bottom, not the side, so full width is available for map+ const isMobile = isMobileDevice();+ const timelineWidthRatio = isMobile ? 0.0 : 0.5; // Mobile: full width, Desktop: timeline takes up 50% of screen++ // Scale the positioning offset based on zoom level+ // At higher zoom levels, we need less offset since we're more zoomed in+ const baseDegreesPerPixelAtZoom10 = 0.35 / 1000;+ const zoomScaleFactor = Math.pow(2, 10 - zoom); // Scale relative to zoom 10+ const degreesPerPixelAtCurrentZoom =+ baseDegreesPerPixelAtZoom10 * zoomScaleFactor;++ // Calculate shift to position marker at 20% from right edge of visible map+ // On mobile, use less aggressive positioning since we have full width+ const basePixelsToShift =+ (window.innerWidth || 1400) * (1 - timelineWidthRatio);+ const pixelsToShiftFor20Percent = isMobile+ ? basePixelsToShift * 0.6 // Mobile: less aggressive positioning (60% instead of 300%)+ : basePixelsToShift * 3.0; // Desktop: 300% of visible map width to shift map left+ const lngShift = pixelsToShiftFor20Percent * degreesPerPixelAtCurrentZoom;++ return [lat, lng - lngShift];+};diff --git a/web/apps/albums/vendor/photos/components/TripLayout/types.ts b/web/apps/albums/vendor/photos/components/TripLayout/types.tsnew file mode 100644index 0000000000..b1a482a1c8--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/types.ts@@ -0,0 +1,9 @@+export interface JourneyPoint {+ lat: number;+ lng: number;+ name: string;+ country: string;+ timestamp: string;+ image: string;+ fileId: number;+}diff --git a/web/apps/albums/vendor/photos/components/TripLayout/utils/dataProcessing.ts b/web/apps/albums/vendor/photos/components/TripLayout/utils/dataProcessing.tsnew file mode 100644index 0000000000..bbf09c4197--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/utils/dataProcessing.ts@@ -0,0 +1,273 @@+import { downloadManager } from "ente-gallery/services/download";+import { type EnteFile } from "ente-media/file";+import {+ fileCreationTime,+ fileFileName,+ fileLocation,+} from "ente-media/file-metadata";+import React from "react";++import type { JourneyPoint } from "../types";+import { getLocationName } from "./geocoding";++export interface ProcessPhotosDataParams {+ files: EnteFile[];+ locationDataRef: React.RefObject<+ Map<number, { name: string; country: string }>+ >;+}++export interface ProcessPhotosDataResult {+ photoData: JourneyPoint[];+ hasLocationData: boolean;+}++export const processPhotosData = ({+ files,+ locationDataRef,+}: ProcessPhotosDataParams): ProcessPhotosDataResult => {+ const photoData: JourneyPoint[] = [];++ if (files.length === 0) {+ return { photoData, hasLocationData: false };+ }++ for (const file of files) {+ try {+ const location = fileLocation(file);++ if (location) {+ const cachedLocation = locationDataRef.current.get(file.id);+ const finalName = cachedLocation?.name || fileFileName(file);+ const finalCountry = cachedLocation?.country || "Unknown";++ photoData.push({+ lat: location.latitude,+ lng: location.longitude,+ name: finalName,+ country: finalCountry,+ timestamp: new Date(+ fileCreationTime(file) / 1000,+ ).toISOString(),+ image: "",+ fileId: file.id,+ });+ }+ } catch {+ // Silently ignore processing errors for individual files+ }+ }++ photoData.sort(+ (a, b) =>+ new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),+ );++ return { photoData, hasLocationData: photoData.length > 0 };+};++export interface FetchLocationNamesParams {+ photoClusters: JourneyPoint[][];+ journeyData: JourneyPoint[];+ locationDataRef: React.RefObject<+ Map<number, { name: string; country: string }>+ >;+}++export interface FetchLocationNamesResult {+ updatedPhotos: Map<number, { name: string; country: string }>;+}++export const fetchLocationNames = async ({+ photoClusters,+ locationDataRef,+}: FetchLocationNamesParams): Promise<FetchLocationNamesResult> => {+ const updatedPhotos = new Map<number, { name: string; country: string }>();++ if (photoClusters.length === 0) {+ return { updatedPhotos };+ }++ // Create all geocoding promises at once for parallel execution+ const geocodingPromises = photoClusters.map(async (cluster) => {+ if (cluster.length === 0) return null;++ const representativePhoto = cluster[0];+ if (!representativePhoto) return null;++ try {+ const locationInfo = await getLocationName(+ representativePhoto.lat,+ representativePhoto.lng,+ );+ return { cluster, locationInfo };+ } catch {+ // Return null on error, will be filtered out+ return null;+ }+ });++ // Execute all geocoding requests in parallel+ const results = await Promise.all(geocodingPromises);++ // Process results and update maps+ results.forEach((result) => {+ if (!result) return; // Skip failed requests++ const { cluster, locationInfo } = result;+ cluster.forEach((photo) => {+ updatedPhotos.set(photo.fileId, {+ name: locationInfo.place,+ country: locationInfo.country,+ });+ locationDataRef.current.set(photo.fileId, {+ name: locationInfo.place,+ country: locationInfo.country,+ });+ });+ });++ return { updatedPhotos };+};++export interface GenerateThumbnailsParams {+ photoClusters: JourneyPoint[][];+ files: EnteFile[];+}++export interface GenerateThumbnailsResult {+ thumbnailUpdates: Map<number, string>;+}++export const generateNeededThumbnails = async ({+ photoClusters,+ files,+}: GenerateThumbnailsParams): Promise<GenerateThumbnailsResult> => {+ const thumbnailUpdates = new Map<number, string>();++ if (photoClusters.length === 0) {+ return { thumbnailUpdates };+ }++ const filesById = new Map(files.map((file) => [file.id, file]));+ const includedIds = new Set<number>();++ const addIfUnique = (group: EnteFile[], fileId: number) => {+ const file = filesById.get(fileId);+ if (!file) return;+ if (includedIds.has(file.id)) return;+ includedIds.add(file.id);+ group.push(file);+ };++ // Define priority groups with specific file collections+ const priorityGroups: EnteFile[][] = [];++ // Priority 1: Cover image (handled separately in loadCoverImage, skip here)++ // Priority 2: First 3 locations photosfans (first 3 photos from each)+ const firstLocationsFiles: EnteFile[] = [];+ photoClusters.slice(0, 3).forEach((cluster) => {+ cluster.slice(0, 3).forEach((photo) => {+ addIfUnique(firstLocationsFiles, photo.fileId);+ });+ });+ if (firstLocationsFiles.length > 0) {+ priorityGroups.push(firstLocationsFiles);+ }++ // Priority 3: Map marker photos (first photo from each cluster for markers)+ const mapMarkerFiles: EnteFile[] = [];+ photoClusters.forEach((cluster) => {+ if (cluster.length > 0 && cluster[0]) {+ const firstPhoto = cluster[0];+ addIfUnique(mapMarkerFiles, firstPhoto.fileId);+ }+ });+ if (mapMarkerFiles.length > 0) {+ priorityGroups.push(mapMarkerFiles);+ }++ // Priority 4: Rest of locations photosfans (remaining locations, first 3 from each)+ const remainingLocationFiles: EnteFile[] = [];+ photoClusters.slice(3).forEach((cluster) => {+ cluster.slice(0, 3).forEach((photo) => {+ addIfUnique(remainingLocationFiles, photo.fileId);+ });+ });+ if (remainingLocationFiles.length > 0) {+ priorityGroups.push(remainingLocationFiles);+ }++ // Process priority groups sequentially with delays+ for (let groupIndex = 0; groupIndex < priorityGroups.length; groupIndex++) {+ const group = priorityGroups[groupIndex];+ if (!group) continue;++ // Process files in parallel within each priority group+ const groupPromises = group.map(async (file) => {+ try {+ const thumbnailUrl =+ await downloadManager.renderableThumbnailURL(file);+ if (thumbnailUrl) {+ thumbnailUpdates.set(file.id, thumbnailUrl);+ }+ } catch {+ // Silently ignore thumbnail generation errors+ }+ });++ await Promise.all(groupPromises);++ // Add small delay between priority groups to allow UI updates+ if (groupIndex < priorityGroups.length - 1) {+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ }++ return { thumbnailUpdates };+};++export interface LoadCoverImageParams {+ journeyData: JourneyPoint[];+ files: EnteFile[];+ collection?: { pubMagicMetadata?: { data: { coverID?: number } } };+}++export const loadCoverImage = async ({+ journeyData,+ files,+ collection,+}: LoadCoverImageParams): Promise<string | null> => {+ if (journeyData.length === 0) return null;++ let coverFile: EnteFile | undefined;++ // Priority 1: Use explicit cover ID if set+ const coverID = collection?.pubMagicMetadata?.data.coverID;+ if (coverID) {+ coverFile = files.find((f) => f.id === coverID);+ }++ // Priority 2: Use first chronological photo as cover (highest priority)+ if (!coverFile) {+ const firstPhoto = journeyData[0];+ if (!firstPhoto) return null;+ coverFile = files.find((f) => f.id === firstPhoto.fileId);+ }++ if (!coverFile) return null;++ try {+ // Load cover image at highest quality first (highest priority)+ const sourceURLs =+ await downloadManager.renderableSourceURLs(coverFile);+ if (sourceURLs.type === "image") {+ return sourceURLs.imageURL;+ }+ } catch {+ // Keep using thumbnail if high quality fails+ }++ return null;+};diff --git a/web/apps/albums/vendor/photos/components/TripLayout/utils/geocoding.ts b/web/apps/albums/vendor/photos/components/TripLayout/utils/geocoding.tsnew file mode 100644index 0000000000..557fe80e0a--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/utils/geocoding.ts@@ -0,0 +1,100 @@+interface StadiaMapsGeocodingResponse {+ features?: {+ properties?: {+ locality?: string;+ neighbourhood?: string;+ county?: string;+ region?: string;+ name?: string;+ country?: string;+ [key: string]: unknown;+ };+ [key: string]: unknown;+ }[];+ [key: string]: unknown;+}++export interface LocationInfo {+ place: string;+ country: string;+}++// Icon cache to avoid recreating identical icons+export const iconCache = new Map<string, import("leaflet").DivIcon>();++// Throttle function for performance optimization+export const throttle = <T extends (...args: unknown[]) => void>(+ func: T,+ delay: number,+): ((...args: Parameters<T>) => void) => {+ let timeoutId: NodeJS.Timeout | null = null;+ let lastExecTime = 0;++ return (...args: Parameters<T>) => {+ const currentTime = Date.now();++ if (currentTime - lastExecTime > delay) {+ func(...args);+ lastExecTime = currentTime;+ } else {+ if (timeoutId) clearTimeout(timeoutId);+ timeoutId = setTimeout(+ () => {+ func(...args);+ lastExecTime = Date.now();+ },+ delay - (currentTime - lastExecTime),+ );+ }+ };+};++// Reverse geocoding function using Stadia Maps+export const getLocationName = async (+ lat: number,+ lng: number,+): Promise<LocationInfo> => {+ try {+ // Round coordinates to 2 decimal place for better geocoding+ const roundedLat = Math.round(lat * 100) / 100;+ const roundedLng = Math.round(lng * 100) / 100;++ const response = await fetch(+ `https://api.stadiamaps.com/geocoding/v1/reverse?point.lat=${roundedLat}&point.lon=${roundedLng}`,+ );++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ const data = (await response.json()) as StadiaMapsGeocodingResponse;++ // Extract location name from the response+ const feature = data.features?.[0];+ let result: LocationInfo;++ if (feature?.properties) {+ const props = feature.properties;++ // Build location name with city and state/region for better context+ const city = props.locality || props.neighbourhood;++ // Get location name+ const locationName =+ city || props.county || props.region || props.name || "Unknown";++ // Get country info+ const country = props.country || "Unknown";++ result = { place: locationName, country };+ } else {+ // Fallback if no location found+ result = { place: "Unknown", country: "Unknown" };+ }++ return result;+ } catch {+ // Fallback on error+ return { place: "Unknown", country: "Unknown" };+ }+};diff --git a/web/apps/albums/vendor/photos/components/TripLayout/utils/scrollUtils.ts b/web/apps/albums/vendor/photos/components/TripLayout/utils/scrollUtils.tsnew file mode 100644index 0000000000..2f31dff511--- /dev/null+++ b/web/apps/albums/vendor/photos/components/TripLayout/utils/scrollUtils.ts@@ -0,0 +1,345 @@+import { startTransition } from "react";++import { calculateDistance, getLocationPosition } from "../mapHelpers";+import type { JourneyPoint } from "../types";++export interface PositionInfo {+ top: number;+ center: number;+}++export interface UpdateLocationPositionsParams {+ locationRefs: (HTMLDivElement | null)[];+ setLocationPositions: (positions: PositionInfo[]) => void;+}++export const updateLocationPositions = ({+ locationRefs,+ setLocationPositions,+}: UpdateLocationPositionsParams) => {+ if (locationRefs.length === 0) return;++ const positions = locationRefs.map((ref) => {+ if (!ref) return { top: 0, center: 0 };+ const rect = ref.getBoundingClientRect();+ const top = ref.offsetTop;+ const center = top + rect.height / 2;+ return { top, center };+ });++ startTransition(() => {+ setLocationPositions(positions);+ });+};++export interface HandleTimelineScrollParams {+ timelineRef: React.RefObject<HTMLDivElement | null>;+ photoClusters: JourneyPoint[][];+ locationPositions: PositionInfo[];+ mapRef: import("leaflet").Map | null;+ isClusterClickScrollingRef: React.RefObject<boolean>;+ setHasUserScrolled: (scrolled: boolean) => void;+ setScrollProgress: (progress: number) => void;+ previousActiveLocationRef: React.RefObject<number>;+ isMobileOrTablet: boolean;+ setTargetZoom: (zoom: number | null) => void;+}++export const handleTimelineScroll = ({+ timelineRef,+ photoClusters,+ locationPositions,+ mapRef,+ isClusterClickScrollingRef,+ setHasUserScrolled,+ setScrollProgress,+ previousActiveLocationRef,+ isMobileOrTablet,+ setTargetZoom,+}: HandleTimelineScrollParams) => {+ if (+ !timelineRef.current ||+ photoClusters.length === 0 ||+ locationPositions.length === 0+ )+ return;++ const timelineContainer = timelineRef.current;+ const scrollHeight = timelineContainer.scrollHeight;+ const clientHeight = timelineContainer.clientHeight;+ const scrollTop = timelineContainer.scrollTop;++ // Calculate scroll progress (0 to 1)+ const isAtBottom = scrollTop + clientHeight >= scrollHeight - 10;+ let progress = 0;+ if (isAtBottom) {+ progress = 1;+ } else {+ const maxScrollableDistance = scrollHeight - clientHeight;+ if (maxScrollableDistance > 0) {+ progress = scrollTop / maxScrollableDistance;+ } else {+ progress = 0;+ }+ }+ const clampedProgress = Math.min(1, Math.max(0, progress));++ if (isClusterClickScrollingRef.current) {+ return;+ }++ setHasUserScrolled(true);+ startTransition(() => {+ setScrollProgress(clampedProgress);+ });++ // Calculate current active location index based on scroll progress+ let currentActiveLocationIndex = -1; // Start with no location selected+ if (photoClusters.length > 0) {+ if (isMobileOrTablet) {+ // Mobile: Slower progression - stay on each location longer+ currentActiveLocationIndex = Math.floor(+ clampedProgress * (photoClusters.length - 0.5),+ );+ } else {+ // Desktop: Use original logic+ currentActiveLocationIndex = Math.round(+ clampedProgress * Math.max(0, photoClusters.length - 1),+ );+ }+ }+ const previousActiveLocationIndex = previousActiveLocationRef.current;++ // Only pan map when active location changes (discrete panning)+ if (+ mapRef?.getContainer() &&+ currentActiveLocationIndex !== previousActiveLocationIndex+ ) {+ previousActiveLocationRef.current = currentActiveLocationIndex;++ // Skip panning if no location is selected (mobile default view)+ if (currentActiveLocationIndex === -1) return;++ const clusterCenters = photoClusters.map((cluster) => {+ const avgLat =+ cluster.reduce((sum, p) => sum + p.lat, 0) / cluster.length;+ const avgLng =+ cluster.reduce((sum, p) => sum + p.lng, 0) / cluster.length;+ return { lat: avgLat, lng: avgLng };+ });++ const targetCluster = clusterCenters[currentActiveLocationIndex];+ if (!targetCluster) return;++ // Position active location at 20% from right edge+ const [positionedLat, positionedLng] = getLocationPosition(+ targetCluster.lat,+ targetCluster.lng,+ );++ // Check if this is a distant location (>500km from previous)+ let isDistantLocation = false;+ if (+ previousActiveLocationIndex !== -1 &&+ previousActiveLocationIndex !== currentActiveLocationIndex+ ) {+ const previousCluster = clusterCenters[previousActiveLocationIndex];+ if (previousCluster) {+ const distance = calculateDistance(+ previousCluster.lat,+ previousCluster.lng,+ targetCluster.lat,+ targetCluster.lng,+ );+ isDistantLocation = distance > 500; // 500km threshold+ }+ }++ const targetZoom = isMobileOrTablet ? 8 : 10; // Touch device-aware zoom level++ try {+ // Super cluster logic disabled - simple zoom transitions+ if (isDistantLocation) {+ // For distant locations not in super cluster: zoom out → pan → zoom in+ const intermediateZoom = isMobileOrTablet ? 2 : 4;++ // Use event listener for smoother animation chaining with pause+ const onZoomEnd = () => {+ mapRef.off("zoomend", onZoomEnd);+ // Small pause to let user see the zoomed out view+ setTimeout(() => {+ setTargetZoom(targetZoom);+ mapRef.flyTo(+ [positionedLat, positionedLng],+ targetZoom,+ {+ animate: true,+ duration: 1.2,+ easeLinearity: 0.2,+ },+ );+ }, 150);+ };++ mapRef.once("zoomend", onZoomEnd);+ setTargetZoom(intermediateZoom);+ mapRef.flyTo([positionedLat, positionedLng], intermediateZoom, {+ animate: true,+ duration: 1.2,+ easeLinearity: 0.2,+ });+ } else {+ // For nearby locations not in super cluster: simple pan to target location+ const currentMapZoom = mapRef.getZoom();+ if (Math.abs(currentMapZoom - targetZoom) > 0.5) {+ mapRef.flyTo([positionedLat, positionedLng], targetZoom, {+ animate: true,+ duration: 0.8,+ easeLinearity: 0.3,+ });+ } else {+ mapRef.panTo([positionedLat, positionedLng], {+ animate: true,+ duration: 0.8,+ easeLinearity: 0.3,+ });+ }+ }+ } catch (error) {+ console.warn("Map operation failed:", error);+ }+ }+};++export interface ScrollTimelineToLocationParams {+ timelineRef: React.RefObject<HTMLDivElement | null>;+ locationIndex: number;+ photoClusters: JourneyPoint[][];+ locationPositions: PositionInfo[];+ isMobileOrTablet: boolean;+}++export const scrollTimelineToLocation = ({+ timelineRef,+ locationIndex,+ photoClusters,+ locationPositions,+ isMobileOrTablet,+}: ScrollTimelineToLocationParams) => {+ if (+ !timelineRef.current ||+ locationIndex < 0 ||+ locationIndex >= photoClusters.length ||+ locationPositions.length === 0+ )+ return;++ const timelineContainer = timelineRef.current;+ const scrollHeight = timelineContainer.scrollHeight;+ const clientHeight = timelineContainer.clientHeight;+ const maxScrollableDistance = scrollHeight - clientHeight;++ // Calculate target progress using the same formula as scroll progress calculation+ let targetProgress;+ if (isMobileOrTablet) {+ // Mobile: Use inverse of the slower progression formula+ // If active index = Math.floor(progress * (length - 0.5))+ // Then progress = (index + 0.5) / (length - 0.5) for accurate inverse+ targetProgress =+ (locationIndex + 0.5) / Math.max(1, photoClusters.length - 0.5);+ } else {+ // Desktop: Use original formula+ targetProgress = locationIndex / Math.max(1, photoClusters.length - 1);+ }++ // Clamp progress to valid range+ targetProgress = Math.min(1, Math.max(0, targetProgress));+ const targetScrollTop = targetProgress * maxScrollableDistance;++ timelineContainer.scrollTo({+ top: Math.max(0, Math.min(targetScrollTop, maxScrollableDistance)),+ behavior: "smooth",+ });+};++export interface HandleMarkerClickParams {+ clusterIndex: number;+ clusterLat: number;+ clusterLng: number;+ photoClusters: JourneyPoint[][];+ mapRef: import("leaflet").Map | null;+ isClusterClickScrollingRef: React.RefObject<boolean>;+ clusterClickTimeoutRef: React.RefObject<NodeJS.Timeout | null>;+ setScrollProgress: (progress: number) => void;+ setHasUserScrolled: (scrolled: boolean) => void;+ scrollTimelineToLocation: (locationIndex: number) => void;+ isMobileOrTablet: boolean;+ setTargetZoom: (zoom: number | null) => void;+ previousActiveLocationRef: React.RefObject<number>;+}++export const handleMarkerClick = ({+ clusterIndex,+ clusterLat,+ clusterLng,+ photoClusters,+ mapRef,+ isClusterClickScrollingRef,+ clusterClickTimeoutRef,+ setScrollProgress,+ setHasUserScrolled,+ scrollTimelineToLocation,+ isMobileOrTablet,+ setTargetZoom,+ previousActiveLocationRef,+}: HandleMarkerClickParams) => {+ const targetProgress = clusterIndex / Math.max(1, photoClusters.length - 1);++ if (clusterClickTimeoutRef.current) {+ clearTimeout(clusterClickTimeoutRef.current);+ }++ isClusterClickScrollingRef.current = true;+ setScrollProgress(targetProgress);+ setHasUserScrolled(true);++ // Update the previous active location to the target cluster+ previousActiveLocationRef.current = clusterIndex;++ if (mapRef?.getContainer()) {+ try {+ // Super cluster logic disabled - simple fly to target with standard zoom+ const [positionedLat, positionedLng] = getLocationPosition(+ clusterLat,+ clusterLng,+ );+ const targetZoomLevel = isMobileOrTablet ? 8 : 10;+ // Set target zoom before animation+ setTargetZoom(targetZoomLevel);++ // Clear target zoom after animation completes+ const onMoveEnd = () => {+ mapRef.off("moveend", onMoveEnd);+ setTargetZoom(null);+ };+ mapRef.once("moveend", onMoveEnd);++ mapRef.flyTo([positionedLat, positionedLng], targetZoomLevel, {+ animate: true,+ duration: 1.0,+ easeLinearity: 0.3,+ });+ } catch (error) {+ console.warn("Map operation failed:", error);+ }+ }++ setTimeout(() => {+ scrollTimelineToLocation(clusterIndex);+ }, 50);++ clusterClickTimeoutRef.current = setTimeout(() => {+ isClusterClickScrollingRef.current = false;+ clusterClickTimeoutRef.current = null;+ }, 1500);+};diff --git a/web/apps/albums/vendor/photos/components/Upload.tsx b/web/apps/albums/vendor/photos/components/Upload.tsxnew file mode 100644index 0000000000..e23395aa00--- /dev/null+++ b/web/apps/albums/vendor/photos/components/Upload.tsx@@ -0,0 +1,1433 @@+// TODO: Audit this file+// TODO: Too many null assertions in this file. The types need reworking.+/* eslint-disable react-hooks/exhaustive-deps */+/* eslint-disable @typescript-eslint/no-misused-promises */+/* eslint-disable @typescript-eslint/no-floating-promises */+import ChevronRightIcon from "@mui/icons-material/ChevronRight";+import DiscFullIcon from "@mui/icons-material/DiscFull";+import GoogleIcon from "@mui/icons-material/Google";+import ImageOutlinedIcon from "@mui/icons-material/ImageOutlined";+import PermMediaOutlinedIcon from "@mui/icons-material/PermMediaOutlined";+import {+ Box,+ CircularProgress,+ Dialog,+ DialogTitle,+ Link,+ Stack,+ styled,+ Typography,+ type DialogProps,+} from "@mui/material";+import type { LocalUser } from "ente-accounts/services/user";+import { isDesktop } from "ente-base/app";+import { SpacedRow } from "ente-base/components/containers";+import { DialogCloseIconButton } from "ente-base/components/mui/DialogCloseIconButton";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { RowButton } from "ente-base/components/RowButton";+import { SingleInputDialog } from "ente-base/components/SingleInputDialog";+import { useIsTouchscreen } from "ente-base/components/utils/hooks";+import {+ useModalVisibility,+ type ModalVisibilityProps,+} from "ente-base/components/utils/modal";+import { useBaseContext } from "ente-base/context";+import { basename, dirname, joinPath } from "ente-base/file-name";+import type { PublicAlbumsCredentials } from "ente-base/http";+import log from "ente-base/log";+import type { CollectionMapping, Electron, ZipItem } from "ente-base/types/ipc";+import { type UploadTypeSelectorIntent } from "ente-gallery/components/Upload";+import { useFileInput } from "ente-gallery/components/utils/use-file-input";+import {+ groupItemsBasedOnParentFolder,+ uploadPathPrefix,+ type FileAndPath,+ type UploadItem,+ type UploadItemAndPath,+ type UploadPhase,+} from "ente-gallery/services/upload";+import type { ParsedMetadataJSON } from "ente-gallery/services/upload/metadata-json";+import {+ sessionExpiredErrorMessage,+ storageLimitExceededErrorMessage,+ subscriptionExpiredErrorMessage,+} from "ente-gallery/services/upload/upload-service";+import { CollectionSubType, type Collection } from "ente-media/collection";+import type { EnteFile } from "ente-media/file";+import { UploaderNameInput } from "ente-new/albums/components/UploaderNameInput";+import {+ savedPublicCollectionUploaderName,+ savePublicCollectionUploaderName,+} from "ente-new/albums/services/public-albums-fdb";+import { CollectionMappingChoice } from "ente-new/photos/components/CollectionMappingChoice";+import type { CollectionSelectorAttributes } from "ente-new/photos/components/CollectionSelector";+import type { RemotePullOpts } from "ente-new/photos/components/gallery";+import { downloadAppDialogAttributes } from "ente-new/photos/components/utils/download";+import { suppressAutoLockOnBlurForTrustedPrompt } from "ente-new/photos/services/app-lock";+import {+ createAlbum,+ createHiddenAlbum,+ isHiddenCollection,+ savedAllCollections,+ savedHiddenCollections,+ savedNormalCollections,+} from "ente-new/photos/services/collection";+import { redirectToCustomerPortal } from "ente-new/photos/services/user-details";+import { usePhotosAppContext } from "ente-new/photos/types/context";+import { firstNonEmpty } from "ente-utils/array";+import { t } from "i18next";+import React, { useCallback, useEffect, useRef, useState } from "react";+import type {+ InProgressUpload,+ SegregatedFinishedUploads,+ UploadCounter,+ UploadFileNames,+ UploadItemWithCollection,+} from "services/upload-manager";+import { uploadManager } from "services/upload-manager";+import watcher from "services/watch";+import { hasReliableCanvasReadback } from "utils/upload/canvas-integrity";+import { CanvasReadbackBlockedDialog } from "./CanvasReadbackBlockedDialog";+import { UploadProgress } from "./UploadProgress";++interface UploadProps {+ /**+ * The logged in user, if any.+ *+ * This is only expected to be present when we're running it the context of+ * the photos app, where there is a logged in user. When used by the public+ * albums app, this prop can be omitted.+ */+ user?: LocalUser;+ /**+ * The {@link PublicAlbumsCredentials} to use, if any.+ *+ * These are expected to be set if we are in the context of the public+ * albums app, and should be undefined when we're in the photos app context.+ */+ publicAlbumsCredentials?: PublicAlbumsCredentials;+ isFirstUpload?: boolean;+ uploadTypeSelectorView: boolean;+ dragAndDropFiles: File[];+ uploadCollection?: Collection;+ uploadTypeSelectorIntent: UploadTypeSelectorIntent;+ activeCollection?: Collection;+ closeUploadTypeSelector: () => void;+ setLoading: (loading: boolean) => void;+ setShouldDisableDropzone: (value: boolean) => void;+ showCollectionSelector?: () => void;+ /**+ * Called when the uploader (or the file watcher) wants to perform a full+ * remote pull.+ *+ * See also {@link onRemoteFilesPull}.+ */+ onRemotePull: (opts?: RemotePullOpts) => Promise<void>;+ /**+ * Called when an action in the uploader requires us to first pull the+ * latest files and collections from remote.+ *+ * See: [Note: Full remote pull vs files pull]+ *+ * Specifically, this is used prior to creating a new album, to obtain+ * (potential) existing albums from remote so that they can be matched by+ * name if needed.+ *+ * This functionality is not needed during uploads to a public album, so+ * this property is optional; the public albums code need not provide it.+ */+ onRemoteFilesPull?: () => Promise<void>;+ /**+ * Show the collection selector with the given {@link attributes}.+ */+ onOpenCollectionSelector?: (+ attributes: CollectionSelectorAttributes,+ ) => void;+ /**+ * Close the collection selector if it is open.+ */+ onCloseCollectionSelector?: () => void;+ /**+ * Callback invoked when a file is uploaded.+ *+ * @param file The newly uploaded file.+ */+ onUploadFile: (file: EnteFile) => void;+ /**+ * Called when the plan selection modal should be shown.+ *+ * It is optional because {@link Upload} is also used by the public albums+ * app, where the scenario requiring this will not arise.+ */+ onShowPlanSelector?: () => void;+ /**+ * Called when the upload failed because the user's session has expired, and+ * the Upload component wants to prompt the user to log in again.+ */+ onShowSessionExpiredDialog: () => void;+ /**+ * If true, the upload is being initiated from the hidden albums section.+ *+ * When set, the collection selector will only show hidden albums, and any+ * new albums created will be hidden albums.+ */+ isInHiddenSection?: boolean;+}++type UploadType = "files" | "folders" | "zips";++/**+ * Top level component that houses the infrastructure for handling uploads.+ */+export const Upload: React.FC<UploadProps> = ({+ user,+ publicAlbumsCredentials,+ isFirstUpload,+ dragAndDropFiles,+ onRemotePull,+ onRemoteFilesPull,+ onOpenCollectionSelector,+ onCloseCollectionSelector,+ onUploadFile,+ onShowPlanSelector,+ onShowSessionExpiredDialog,+ ...props+}) => {+ const { showMiniDialog, onGenericError } = useBaseContext();+ const { showNotification, watchFolderView } = usePhotosAppContext();++ const [uploadProgressView, setUploadProgressView] = useState(false);+ const [+ showCanvasReadbackBlockedDialog,+ setShowCanvasReadbackBlockedDialog,+ ] = useState(false);+ const [uploadPhase, setUploadPhase] = useState<UploadPhase>("preparing");+ const [uploadFileNames, setUploadFileNames] = useState<UploadFileNames>();+ const [uploadCounter, setUploadCounter] = useState<UploadCounter>({+ finished: 0,+ total: 0,+ });+ const [inProgressUploads, setInProgressUploads] = useState(+ new Array<InProgressUpload>(),+ );+ const [finishedUploads, setFinishedUploads] =+ useState<SegregatedFinishedUploads>(new Map());+ const [percentComplete, setPercentComplete] = useState(0);+ const [hasLivePhotos, setHasLivePhotos] = useState(false);+ const [prefilledNewAlbumName, setPrefilledNewAlbumName] = useState("");+ const [uploaderName, setUploaderName] = useState("");++ const [openCollectionMappingChoice, setOpenCollectionMappingChoice] =+ useState(false);+ const [importSuggestion, setImportSuggestion] = useState<ImportSuggestion>(+ defaultImportSuggestion,+ );+ const {+ show: showNewAlbumNameInput,+ props: newAlbumNameInputVisibilityProps,+ } = useModalVisibility();+ const {+ show: showUploaderNameInput,+ props: uploaderNameInputVisibilityProps,+ } = useModalVisibility();++ /**+ * {@link File}s that the user drag-dropped or selected for uploads (web).+ *+ * This is the only type of selection that is possible when we're running in+ * the browser.+ */+ const [webFiles, setWebFiles] = useState<File[]>([]);+ /**+ * {@link File}s that the user drag-dropped or selected for uploads,+ * augmented with their paths (desktop).+ *+ * These siblings of {@link webFiles} come into play when we are running in+ * the context of our desktop app.+ */+ const [desktopFiles, setDesktopFiles] = useState<FileAndPath[]>([]);+ /**+ * Paths of file to upload that we've received over the IPC bridge from the+ * code running in the Node.js layer of our desktop app.+ *+ * Unlike {@link filesWithPaths} which are still user initiated,+ * {@link desktopFilePaths} can be set via programmatic action. For example,+ * if the user has setup a folder watch, and a new file is added on their+ * local file system in one of the watched folders, then the relevant path+ * of the new file would get added to {@link desktopFilePaths}.+ */+ const [desktopFilePaths, setDesktopFilePaths] = useState<string[]>([]);+ /**+ * (zip file path, entry within zip file) tuples for zip files that the user+ * is trying to upload.+ *+ * These are only set when we are running in the context of our desktop app.+ * They may be set either on a user action (when the user selects or+ * drag-drops zip files) or programmatically (when the app is trying to+ * resume pending uploads from a previous session).+ */+ const [desktopZipItems, setDesktopZipItems] = useState<ZipItem[]>([]);++ /**+ * Consolidated and cleaned list obtained from {@link webFiles},+ * {@link desktopFiles}, {@link desktopFilePaths} and+ * {@link desktopZipItems}.+ *+ * Augment each {@link UploadItem} with its "path" (relative path or name in+ * the case of {@link webFiles}, absolute path in the case of+ * {@link desktopFiles}, {@link desktopFilePaths}, and the path within the+ * zip file for {@link desktopZipItems}).+ *+ * See the documentation of {@link UploadItem} for more details.+ */+ const uploadItemsAndPaths = useRef<UploadItemAndPath[]>([]);++ /**+ * If true, then the next upload we'll be processing was initiated by our+ * desktop app.+ */+ const isPendingDesktopUpload = useRef(false);++ /**+ * If set, this will be the name of the collection that our desktop app+ * wishes for us to upload into.+ */+ const pendingDesktopUploadCollectionName = useRef<string | undefined>(+ undefined,+ );++ /**+ * This is set to thue user's choice when the user chooses one of the+ * predefined type to upload from the upload type selector dialog+ */+ const selectedUploadType = useRef<UploadType | undefined>(undefined);++ const currentUploadPromise = useRef<Promise<void> | undefined>(undefined);+ const uploadRunning = useRef(false);+ const isDragAndDrop = useRef(false);++ /**+ * `true` if we've activated one hidden {@link Inputs} that allow the user+ * to select items, and haven't heard back from the browser as to the+ * selection (or cancellation).+ *+ * [Note: Showing an activity indicator during upload item selection]+ *+ * When selecting a large number of items (100K+), the browser can take+ * significant time (10s+) before it hands back control to us. The+ * {@link isInputPending} state tracks this intermediate state, and we use+ * it to show an activity indicator to let that the user know that their+ * selection is still being processed.+ */+ const [isInputPending, setIsInputPending] = useState(false);++ /**+ * Files that were selected by the user in the last activation of one of the+ * hidden {@link Inputs}.+ */+ const [selectedInputFiles, setSelectedInputFiles] = useState<File[]>([]);++ const handleInputSelect = useCallback((files: File[]) => {+ setIsInputPending(false);+ setSelectedInputFiles(files);+ }, []);++ const handleInputCancel = useCallback(() => {+ setIsInputPending(false);+ }, []);++ const {+ getInputProps: getFileSelectorInputProps,+ openSelector: openFileSelector,+ } = useFileInput({+ directory: false,+ onSelect: handleInputSelect,+ onCancel: handleInputCancel,+ });++ const {+ getInputProps: getFolderSelectorInputProps,+ openSelector: openFolderSelector,+ } = useFileInput({+ directory: true,+ onSelect: handleInputSelect,+ onCancel: handleInputCancel,+ });++ const {+ getInputProps: getZipFileSelectorInputProps,+ openSelector: openZipFileSelector,+ } = useFileInput({+ directory: false,+ accept: ".zip",+ onSelect: handleInputSelect,+ onCancel: handleInputCancel,+ });++ const electron = globalThis.electron;++ const closeUploadProgress = () => setUploadProgressView(false);++ const handleCollectionMappingChoiceClose = () => {+ setOpenCollectionMappingChoice(false);+ uploadRunning.current = false;+ };++ const handleCollectionSelectorCancel = () => {+ uploadRunning.current = false;+ };++ const handleUploaderNameInputClose = () => {+ uploaderNameInputVisibilityProps.onClose();+ uploadRunning.current = false;+ };++ useEffect(() => {+ uploadManager.init(+ {+ setPercentComplete,+ setUploadCounter,+ setInProgressUploads,+ setFinishedUploads,+ setUploadPhase,+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ // @ts-ignore+ setUploadFilenames: setUploadFileNames,+ setHasLivePhotos,+ setUploadProgressView,+ },+ onUploadFile,+ publicAlbumsCredentials,+ );++ if (uploadManager.isUploadRunning()) {+ setUploadProgressView(true);+ }++ if (electron) {+ const upload = (collectionName: string, filePaths: string[]) => {+ isPendingDesktopUpload.current = true;+ pendingDesktopUploadCollectionName.current = collectionName;+ setDesktopFilePaths(filePaths);+ };++ watcher.init(upload, () => void onRemotePull());++ electron.pendingUploads().then((pending) => {+ if (!pending) return;++ const { collectionName, filePaths, zipItems } = pending;++ log.info(+ `Resuming pending of upload of ${filePaths.length + zipItems.length} items${collectionName ? " to collection " + collectionName : ""}`,+ );+ isPendingDesktopUpload.current = true;+ pendingDesktopUploadCollectionName.current = collectionName;+ setDesktopFilePaths(filePaths);+ setDesktopZipItems(zipItems);+ });+ }+ }, [publicAlbumsCredentials]);++ // Handle selected files when user selects files for upload through the open+ // file / open folder selection dialog, or drag-and-drops them.+ useEffect(() => {+ if (watchFolderView) {+ // if watch folder dialog is open don't catch the dropped file+ // as they are folder being dropped for watching+ return;+ }++ let files: File[];+ isDragAndDrop.current = false;++ switch (selectedUploadType.current) {+ case "files":+ case "folders":+ case "zips":+ files = selectedInputFiles;+ break;++ default:+ isDragAndDrop.current = true;+ files = dragAndDropFiles;+ break;+ }++ if (electron) {+ desktopFilesAndZipItems(electron, files).then(+ ({ fileAndPaths, zipItems }) => {+ setDesktopFiles(fileAndPaths);+ setDesktopZipItems(zipItems);+ },+ );+ } else {+ setWebFiles(files);+ }+ }, [selectedInputFiles, dragAndDropFiles]);++ // Trigger an upload when any of the dependencies change.+ useEffect(() => {+ // About the paths:+ //+ // - These are not necessarily the full paths. In particular, when+ // running on the browser they'll be the relative paths (at best) or+ // just the file-name otherwise.+ //+ // - All the paths use POSIX separators. See inline comments.+ //+ // - For zips we concatenate the path of the zip to the path within the+ // zip for the purpose of computing the nesting.+ const allItemAndPaths = [+ // Relative path (using POSIX separators) or the file's name.+ webFiles.map((f) => [f, pathLikeForWebFile(f)]),+ // The paths we get from the desktop app all eventually come either+ // from electron.selectDirectory or electron.pathForFile, both of+ // which return POSIX paths.+ desktopFiles.map((fp) => [fp, fp.path]),+ desktopFilePaths.map((p) => [p, p]),+ // Concatenate the path of the item within the zip to path of the+ // zip. This won't affect the upload: this path is only used for+ // computation of the "parent" folder, and this concatenation best+ // reflects the nesting.+ //+ // Re POSIXness: The first path, that of the zip file itself, is+ // POSIX like the other paths we get over the IPC boundary. And the+ // second path, ze[1], the entry name, uses POSIX separators because+ // that is what the ZIP format uses.+ desktopZipItems.map((ze) => [ze, joinPath(dirname(ze[0]), ze[1])]),+ ].flat() as UploadItemAndPath[];++ if (allItemAndPaths.length == 0) return;++ if (uploadManager.isUploadRunning()) {+ if (watcher.isUploadRunning()) {+ log.info("Pausing watch folder sync to prioritize user upload");+ watcher.pauseRunningSync();+ } else {+ log.info(+ "Ignoring new upload request when upload is already running",+ );+ return;+ }+ }++ if (!electron && !hasReliableCanvasReadback()) {+ log.warn("Canvas readback integrity check failed; blocking upload");+ setWebFiles([]);+ selectedUploadType.current = undefined;+ setShowCanvasReadbackBlockedDialog(true);+ return;+ }++ uploadRunning.current = true;+ props.closeUploadTypeSelector();+ props.setLoading(true);++ setWebFiles([]);+ setDesktopFiles([]);+ setDesktopFilePaths([]);+ setDesktopZipItems([]);++ // Filter out files whose names begins with a ".".+ const prunedItemAndPaths = allItemAndPaths.filter(+ ([, p]) => !basename(p).startsWith("."),+ );++ uploadItemsAndPaths.current = prunedItemAndPaths;+ if (uploadItemsAndPaths.current.length == 0) {+ props.setLoading(false);+ return;+ }++ const importSuggestion = deriveImportSuggestion(+ selectedUploadType.current,+ prunedItemAndPaths.map(([, p]) => p),+ );+ setImportSuggestion(importSuggestion);++ log.debug(() => ["Upload request", uploadItemsAndPaths.current]);+ log.debug(() => ["Import suggestion", importSuggestion]);++ const _selectedUploadType = selectedUploadType.current;+ selectedUploadType.current = undefined;+ props.setLoading(false);++ (async () => {+ if (publicAlbumsCredentials) {+ setUploaderName(+ (await savedPublicCollectionUploaderName(+ publicAlbumsCredentials.accessToken,+ )) ?? "",+ );+ showUploaderNameInput();+ return;+ }++ if (isPendingDesktopUpload.current) {+ isPendingDesktopUpload.current = false;+ if (pendingDesktopUploadCollectionName.current) {+ // Include hidden collections so watch folder syncs add+ // files to existing hidden albums instead of creating new+ // visible ones+ uploadFilesToNewCollections(+ "root",+ pendingDesktopUploadCollectionName.current,+ true,+ );+ pendingDesktopUploadCollectionName.current = undefined;+ } else {+ uploadFilesToNewCollections("parent", undefined, true);+ }+ return;+ }++ if (electron && _selectedUploadType == "zips") {+ uploadFilesToNewCollections("parent");+ return;+ }++ if (isFirstUpload && !importSuggestion.rootFolderName) {+ importSuggestion.rootFolderName = t(+ "autogenerated_first_album_name",+ );+ }++ if (isDragAndDrop.current) {+ isDragAndDrop.current = false;+ if (+ props.activeCollection &&+ props.activeCollection.owner.id == user?.id+ ) {+ uploadFilesToExistingCollection(props.activeCollection);+ return;+ }+ }++ // eslint-disable-next-line @typescript-eslint/no-empty-function+ let showNextModal = () => {};+ if (importSuggestion.hasNestedFolders) {+ showNextModal = () => setOpenCollectionMappingChoice(true);+ } else {+ showNextModal = () => {+ setPrefilledNewAlbumName(importSuggestion.rootFolderName);+ showNewAlbumNameInput();+ };+ }++ onOpenCollectionSelector?.({+ action: "upload",+ activeCollectionID: props.activeCollection?.id,+ showHiddenCollections: props.isInHiddenSection,+ onSelectCollection: uploadFilesToExistingCollection,+ onCreateCollection: showNextModal,+ onCancel: handleCollectionSelectorCancel,+ });+ })();+ }, [+ publicAlbumsCredentials,+ webFiles,+ desktopFiles,+ desktopFilePaths,+ desktopZipItems,+ ]);++ const preCollectionCreationAction = () => {+ onCloseCollectionSelector?.();+ props.setShouldDisableDropzone(uploadManager.isUploadInProgress());+ setUploadPhase("preparing");+ setUploadProgressView(true);+ };++ const uploadFilesToExistingCollection = async (+ collection: Collection,+ uploaderName?: string,+ ) => {+ preCollectionCreationAction();+ const uploadItemsWithCollection = uploadItemsAndPaths.current.map(+ ([uploadItem, path], index) => ({+ uploadItem,+ pathPrefix: uploadPathPrefix(path),+ localID: index,+ collectionID: collection.id,+ }),+ );+ await waitInQueueAndUploadFiles(+ uploadItemsWithCollection,+ [collection],+ uploaderName,+ );+ uploadItemsAndPaths.current = [];+ };++ const uploadFilesToNewCollections = async (+ mapping: CollectionMapping,+ collectionName?: string,+ includeHiddenCollections?: boolean,+ createHidden?: boolean,+ ) => {+ preCollectionCreationAction();+ let uploadItemsWithCollection: UploadItemWithCollection[] = [];+ let collectionNameToUploadItems = new Map<+ string,+ UploadItemAndPath[]+ >();+ if (mapping == "root") {+ collectionNameToUploadItems.set(+ // Un-enforced convention is that collectionName is always set+ // when mapping is "root". TODO: Reflect this in types.+ collectionName!,+ uploadItemsAndPaths.current,+ );+ } else {+ collectionNameToUploadItems = groupItemsBasedOnParentFolder(+ uploadItemsAndPaths.current,+ collectionName,+ );+ }+ const collections: Collection[] = [];+ try {+ await onRemoteFilesPull!();+ // When uploading to hidden section (createHidden), only search+ // hidden collections. When syncing from watch folders+ // (includeHiddenCollections), search all collections so files go+ // to existing albums regardless of visibility. Otherwise, search+ // only normal (visible) collections.+ const existingCollections = createHidden+ ? await savedHiddenCollections()+ : includeHiddenCollections+ ? await savedAllCollections()+ : await savedNormalCollections();+ let index = 0;+ for (const [+ collectionName,+ uploadItems,+ ] of collectionNameToUploadItems) {+ const collection = await matchExistingOrCreateAlbum(+ collectionName,+ user!,+ existingCollections,+ createHidden,+ );+ collections.push(collection);+ uploadItemsWithCollection = [+ ...uploadItemsWithCollection,+ ...uploadItems.map(([uploadItem, path]) => ({+ localID: index++,+ pathPrefix: uploadPathPrefix(path),+ collectionID: collection.id,+ uploadItem,+ })),+ ];+ }+ } catch (e) {+ closeUploadProgress();+ onGenericError(e);+ return;+ }+ await waitInQueueAndUploadFiles(uploadItemsWithCollection, collections);+ uploadItemsAndPaths.current = [];+ };++ const waitInQueueAndUploadFiles = async (+ uploadItemsWithCollection: UploadItemWithCollection[],+ collections: Collection[],+ uploaderName?: string,+ ) => {+ const currentPromise = currentUploadPromise.current;+ currentUploadPromise.current = (async () => {+ if (currentPromise) await currentPromise;+ return uploadFiles(+ uploadItemsWithCollection,+ collections,+ uploaderName,+ );+ })();+ await currentUploadPromise.current;+ };++ const preUploadAction = async (+ parsedMetadataJSONMap?: Map<string, ParsedMetadataJSON>,+ ) => {+ uploadManager.prepareForNewUpload(parsedMetadataJSONMap);+ setUploadProgressView(true);+ await onRemotePull({ silent: true });+ };++ function postUploadAction() {+ props.setShouldDisableDropzone(false);+ uploadRunning.current = false;+ void onRemotePull();+ }++ const uploadFiles = async (+ uploadItemsWithCollection: UploadItemWithCollection[],+ collections: Collection[],+ uploaderName?: string,+ ) => {+ try {+ preUploadAction();+ if (+ electron &&+ !isPendingDesktopUpload.current &&+ !watcher.isUploadRunning()+ ) {+ setPendingUploads(+ electron,+ collections,+ uploadItemsWithCollection+ .map(({ uploadItem }) => uploadItem)+ .filter((x) => x !== undefined),+ );+ }+ const wereFilesProcessed = await uploadManager.uploadItems(+ uploadItemsWithCollection,+ collections,+ uploaderName,+ );+ if (!wereFilesProcessed) closeUploadProgress();+ if (isDesktop) {+ if (watcher.isUploadRunning()) {+ await watcher.allFileUploadsDone(uploadItemsWithCollection);+ } else if (watcher.isSyncPaused()) {+ // Resume folder watch after the user upload that+ // interrupted it is done.+ watcher.resumePausedSync();+ }+ }+ } catch (e) {+ log.error("Failed to upload files", e);+ closeUploadProgress();+ notifyUser(e);+ } finally {+ postUploadAction();+ }+ };++ const retryFailed = async () => {+ try {+ log.info("Retrying failed uploads");+ const { items, collections, parsedMetadataJSONMap } =+ uploadManager.failedItemState();+ const uploaderName = uploadManager.getUploaderName();+ await preUploadAction(parsedMetadataJSONMap);+ await uploadManager.uploadItems(items, collections, uploaderName);+ } catch (e) {+ log.error("Retrying failed uploads failed", e);+ closeUploadProgress();+ notifyUser(e);+ } finally {+ postUploadAction();+ }+ };++ const notifyUser = (e: unknown) => {+ switch (e instanceof Error && e.message) {+ case sessionExpiredErrorMessage:+ onShowSessionExpiredDialog();+ break;+ case subscriptionExpiredErrorMessage:+ showNotification({+ color: "critical",+ captionFirst: true,+ caption: t("subscription_expired"),+ title: t("renew_now"),+ onClick: redirectToCustomerPortal,+ });+ break;+ case storageLimitExceededErrorMessage:+ showNotification({+ color: "critical",+ captionFirst: true,+ caption: t("storage_quota_exceeded"),+ title: t("upgrade_now"),+ onClick: onShowPlanSelector,+ startIcon: <DiscFullIcon />,+ });+ break;+ default:+ showNotification({+ color: "critical",+ title: t("generic_error_retry"),+ });+ }+ };++ const uploadToSingleNewCollection = (collectionName: string) => {+ uploadFilesToNewCollections(+ "root",+ collectionName,+ undefined,+ props.isInHiddenSection,+ );+ };++ const cancelUploads = () => {+ uploadManager.cancelRunningUpload();+ };++ const handleUploadTypeSelect = (type: UploadType) => {+ selectedUploadType.current = type;+ // Opening native file/folder pickers can blur the app window on+ // desktop; suppress blur-triggered app lock for this trusted flow.+ if (electron) {+ suppressAutoLockOnBlurForTrustedPrompt();+ }+ setIsInputPending(true);+ switch (type) {+ case "files":+ openFileSelector();+ break;+ case "folders":+ openFolderSelector();+ break;+ case "zips":+ if (electron) {+ openZipFileSelector();+ } else {+ showMiniDialog(downloadAppDialogAttributes());+ }+ break;+ }+ };++ const handlePublicUpload = (uploaderName: string) => {+ savePublicCollectionUploaderName(+ publicAlbumsCredentials!.accessToken,+ uploaderName,+ );++ // Do not keep the uploader name input dialog open while the upload is+ // progressing (the upload progress indicator will take out now).+ void uploadFilesToExistingCollection(+ props.uploadCollection!,+ uploaderName,+ );+ };++ const handleCollectionMappingSelect = (mapping: CollectionMapping) =>+ uploadFilesToNewCollections(+ mapping,+ importSuggestion.rootFolderName ||+ t("autogenerated_default_album_name"),+ undefined,+ props.isInHiddenSection,+ );++ return (+ <>+ <Inputs+ {...{+ getFileSelectorInputProps,+ getFolderSelectorInputProps,+ getZipFileSelectorInputProps,+ }}+ />+ <CollectionMappingChoice+ open={openCollectionMappingChoice}+ onClose={handleCollectionMappingChoiceClose}+ onSelect={handleCollectionMappingSelect}+ />+ <UploadTypeSelector+ open={props.uploadTypeSelectorView}+ onClose={props.closeUploadTypeSelector}+ publicAlbumsCredentials={publicAlbumsCredentials}+ intent={props.uploadTypeSelectorIntent}+ pendingUploadType={+ isInputPending ? selectedUploadType.current : undefined+ }+ onSelect={handleUploadTypeSelect}+ />+ <UploadProgress+ open={uploadProgressView}+ onClose={closeUploadProgress}+ percentComplete={percentComplete}+ uploadFileNames={uploadFileNames!}+ uploadCounter={uploadCounter}+ uploadPhase={uploadPhase}+ inProgressUploads={inProgressUploads}+ hasLivePhotos={hasLivePhotos}+ retryFailed={retryFailed}+ finishedUploads={finishedUploads}+ cancelUploads={cancelUploads}+ />+ <CanvasReadbackBlockedDialog+ open={showCanvasReadbackBlockedDialog}+ onClose={() => setShowCanvasReadbackBlockedDialog(false)}+ />+ <SingleInputDialog+ {...newAlbumNameInputVisibilityProps}+ title={t("new_album")}+ label={t("album_name")}+ initialValue={prefilledNewAlbumName}+ submitButtonTitle={t("create")}+ onSubmit={uploadToSingleNewCollection}+ />+ <UploaderNameInput+ open={uploaderNameInputVisibilityProps.open}+ onClose={handleUploaderNameInputClose}+ uploaderName={uploaderName}+ uploadFileCount={uploadItemsAndPaths.current.length}+ onSubmit={handlePublicUpload}+ />+ </>+ );+};++type GetInputProps = () => React.HTMLAttributes<HTMLInputElement>;++interface InputsProps {+ getFileSelectorInputProps: GetInputProps;+ getFolderSelectorInputProps: GetInputProps;+ getZipFileSelectorInputProps: GetInputProps;+}++/**+ * Create a bunch of HTML inputs elements, one each for the given props.+ *+ * These hidden input element serve as the way for us to show various file /+ * folder Selector dialogs and handle drag and drop inputs.+ */+const Inputs: React.FC<InputsProps> = ({+ getFileSelectorInputProps,+ getFolderSelectorInputProps,+ getZipFileSelectorInputProps,+}) => (+ <>+ <input {...getFileSelectorInputProps()} />+ <input {...getFolderSelectorInputProps()} />+ <input {...getZipFileSelectorInputProps()} />+ </>+);++const desktopFilesAndZipItems = async (electron: Electron, files: File[]) => {+ const fileAndPaths: FileAndPath[] = [];+ let zipItems: ZipItem[] = [];++ for (const file of files) {+ const path = electron.pathForFile(file);+ if (file.name.endsWith(".zip")) {+ zipItems = zipItems.concat(await electron.listZipItems(path));+ } else {+ fileAndPaths.push({ file, path });+ }+ }++ return { fileAndPaths, zipItems };+};++/**+ * Return the relative path or name of a File object selected or+ * drag-and-dropped on the web.+ *+ * There are three cases here:+ *+ * 1. If the user selects individual file(s), then the returned File objects+ * will only have a `name`.+ *+ * 2. If the user selects directory(ies), then the returned File objects will+ * have a `webkitRelativePath`. For more details, see [Note:+ * webkitRelativePath]. In particular, these will POSIX separators.+ *+ * 3. If the user drags-and-drops, then the react-dropzone library that we use+ * will internally convert `webkitRelativePath` to `path`, but otherwise it+ * behaves same as case 2.+ * https://github.com/react-dropzone/file-selector/blob/master/src/file.ts#L1214+ */+const pathLikeForWebFile = (file: File): string =>+ firstNonEmpty([+ // We need to check first, since path is not a property of+ // the standard File objects.+ "path" in file && typeof file.path == "string" ? file.path : undefined,+ file.webkitRelativePath,+ file.name,+ ])!;++/**+ * This is used to prompt the user the make upload strategy choice.+ *+ * This is derived from the items that the user selected.+ */+interface ImportSuggestion {+ rootFolderName: string;+ hasNestedFolders: boolean;+}++const defaultImportSuggestion: ImportSuggestion = {+ rootFolderName: "",+ hasNestedFolders: false,+};++const deriveImportSuggestion = (+ uploadType: UploadType | undefined,+ paths: string[],+): ImportSuggestion => {+ if (isDesktop && uploadType == "files") {+ return defaultImportSuggestion;+ }++ const separatorCounts = new Map(+ paths.map((s) => [s, s.match(/\//g)?.length ?? 0]),+ );+ const separatorCount = (s: string) => separatorCounts.get(s)!;+ paths.sort((path1, path2) => separatorCount(path1) - separatorCount(path2));+ const firstPath = paths[0]!;+ const lastPath = paths[paths.length - 1]!;++ const L = firstPath.length;+ let i = 0;+ const firstFileFolder = firstPath.substring(0, firstPath.lastIndexOf("/"));+ const lastFileFolder = lastPath.substring(0, lastPath.lastIndexOf("/"));++ while (i < L && firstPath.charAt(i) === lastPath.charAt(i)) i++;+ let commonPathPrefix = firstPath.substring(0, i);++ if (commonPathPrefix) {+ commonPathPrefix = commonPathPrefix.substring(+ 0,+ commonPathPrefix.lastIndexOf("/"),+ );+ if (commonPathPrefix) {+ commonPathPrefix = commonPathPrefix.substring(+ commonPathPrefix.lastIndexOf("/") + 1,+ );+ }+ }++ return {+ rootFolderName: commonPathPrefix || "",+ hasNestedFolders: firstFileFolder !== lastFileFolder,+ };+};++const matchExistingOrCreateAlbum = async (+ albumName: string,+ user: LocalUser,+ existingCollections: Collection[],+ createHidden?: boolean,+) => {+ for (const collection of existingCollections) {+ // When creating a hidden album, only match hidden collections.+ // This prevents hidden uploads from going to visible albums.+ if (createHidden && !isHiddenCollection(collection)) continue;++ if (+ // Name matches+ collection.name == albumName &&+ // Valid types+ (collection.type == "album" ||+ collection.type == "folder" ||+ collection.type == "uncategorized") &&+ // Not a quicklink+ collection.magicMetadata?.data.subType !=+ CollectionSubType.quicklink &&+ // Owned by user+ collection.owner.id == user.id+ ) {+ log.info(+ `Found existing album ${albumName} with id ${collection.id}`,+ );+ return collection;+ }+ }++ const collection = createHidden+ ? await createHiddenAlbum(albumName)+ : await createAlbum(albumName);+ log.info(`Created new album ${albumName} with id ${collection.id}`);+ return collection;+};++const setPendingUploads = async (+ electron: Electron,+ collections: Collection[],+ uploadItems: UploadItem[],+) => {+ let collectionName: string | undefined;+ /* collection being one suggest one of two things+ 1. Either the user has upload to a single existing collection+ 2. Created a new single collection to upload to+ may have had multiple folder, but chose to upload+ to one album+ hence saving the collection name when upload collection count is 1+ helps the info of user choosing this options+ and on next upload we can directly start uploading to this collection+ */+ if (collections.length == 1) {+ collectionName = collections[0]!.name;+ }++ const filePaths: string[] = [];+ const zipItems: ZipItem[] = [];+ for (const item of uploadItems) {+ if (item instanceof File) {+ throw new Error("Unexpected web file for a desktop pending upload");+ } else if (typeof item == "string") {+ filePaths.push(item);+ } else if (Array.isArray(item)) {+ zipItems.push(item);+ } else {+ filePaths.push(item.path);+ }+ }++ await electron.setPendingUploads({ collectionName, filePaths, zipItems });+};++type UploadTypeSelectorProps = ModalVisibilityProps & {+ /**+ * The particular context / scenario in which this upload is occurring.+ */+ intent: UploadTypeSelectorIntent;+ /**+ * If we're waiting on the user to select items using a previously activated+ * file input, then this will be set to the type of that input.+ */+ pendingUploadType: UploadType | undefined;+ /**+ * Called when the user selects one of the options.+ */+ onSelect: (type: UploadType) => void;+} & Pick<UploadProps, "publicAlbumsCredentials">;++/**+ * Request the user to specify which type of file / folder / zip it is that they+ * wish to upload.+ *+ * This selector (and the "Upload" button) is functionally redundant, the user+ * can just drag and drop any of these into the app to directly initiate the+ * upload. But having an explicit easy to reach button is also necessary for new+ * users, or for cases where drag-and-drop might not be appropriate.+ */+const UploadTypeSelector: React.FC<UploadTypeSelectorProps> = ({+ open,+ onClose,+ publicAlbumsCredentials,+ intent,+ pendingUploadType,+ onSelect,+}) => {+ // Directly show the file selector for the public albums app on likely+ // mobile devices.+ const directlyShowUploadFiles = useIsTouchscreen();++ useEffect(() => {+ if (open && directlyShowUploadFiles && publicAlbumsCredentials) {+ onSelect("files");+ onClose();+ }+ }, [open, publicAlbumsCredentials]);++ const handleClose: DialogProps["onClose"] = () => {+ // Disable backdrop clicks and esc keypresses if a selection is pending+ // processing so that the user doesn't inadvertently close the dialog.+ if (pendingUploadType) return;+ onClose();+ };++ return (+ <Dialog+ open={open}+ onClose={handleClose}+ fullWidth+ slotProps={{+ paper: {+ sx: (theme) => ({+ maxWidth: "375px",+ p: 1,+ borderRadius: "28px",+ boxShadow: "none",+ border: "1px solid",+ borderColor: "stroke.faint",+ [theme.breakpoints.down(360)]: { p: 0 },+ }),+ },+ }}+ sx={{+ "& .MuiBackdrop-root": {+ backgroundColor: "rgba(0, 0, 0, 0.5)",+ },+ }}+ >+ <UploadOptions+ {...{ intent, pendingUploadType, onSelect, onClose }}+ />+ </Dialog>+ );+};++type UploadOptionsProps = Pick<+ UploadTypeSelectorProps,+ "onClose" | "intent" | "pendingUploadType" | "onSelect"+>;++const UploadOptions: React.FC<UploadOptionsProps> = ({+ intent,+ pendingUploadType,+ onSelect,+ onClose,+}) => {+ // [Note: Dialog state remains preserved on reopening]+ //+ // Keep dialog content specific state here, in a separate component, so that+ // this state is not tied to the lifetime of the dialog.+ //+ // If we don't do this, then a MUI dialog retains whatever it was doing when+ // it was last closed. Sometimes that is desirable, but sometimes not, and+ // in the latter cases moving the instance specific state to a child works.++ const [showTakeoutOptions, setShowTakeoutOptions] = useState(false);++ const handleTakeoutClose = () => setShowTakeoutOptions(false);++ const handleSelect = (option: UploadType) => {+ switch (option) {+ case "files":+ onSelect("files");+ break;+ case "folders":+ onSelect("folders");+ break;+ case "zips":+ if (!showTakeoutOptions) {+ setShowTakeoutOptions(true);+ } else {+ onSelect("zips");+ }+ break;+ }+ };++ return showTakeoutOptions ? (+ <TakeoutOptions onSelect={handleSelect} onClose={handleTakeoutClose} />+ ) : (+ <DefaultOptions+ {...{ intent, pendingUploadType, onClose }}+ onSelect={handleSelect}+ />+ );+};++const DefaultOptions: React.FC<UploadOptionsProps> = ({+ intent,+ pendingUploadType,+ onClose,+ onSelect,+}) => {+ return (+ <>+ <SpacedRow>+ <DialogTitle variant="h5">+ {intent == "collect"+ ? t("select_photos")+ : intent == "import"+ ? t("import")+ : t("upload")}+ </DialogTitle>+ <DialogCloseIconButton {...{ onClose }} />+ </SpacedRow>+ <Box sx={{ p: "12px", pt: "16px" }}>+ <RoundedButtonStack>+ {intent != "import" && (+ <RowButton+ startIcon={<ImageOutlinedIcon />}+ endIcon={+ pendingUploadType == "files" ? (+ <PendingIndicator />+ ) : (+ <ChevronRightIcon />+ )+ }+ label={t("file")}+ onClick={() => onSelect("files")}+ />+ )}+ <RowButton+ startIcon={<PermMediaOutlinedIcon />}+ endIcon={+ pendingUploadType == "folders" ? (+ <PendingIndicator />+ ) : (+ <ChevronRightIcon />+ )+ }+ label={t("folder")}+ onClick={() => onSelect("folders")}+ />+ {intent != "collect" && (+ <RowButton+ startIcon={<GoogleIcon />}+ endIcon={<ChevronRightIcon />}+ label={t("google_takeout")}+ onClick={() => onSelect("zips")}+ />+ )}+ </RoundedButtonStack>+ <Typography+ sx={{+ color: "text.muted",+ p: "12px",+ pt: "24px",+ textAlign: "center",+ }}+ >+ {t("drag_and_drop_hint")}+ </Typography>+ </Box>+ </>+ );+};++const PendingIndicator = () => (+ <CircularProgress size={18} sx={{ color: "stroke.muted" }} />+);++const TakeoutOptions: React.FC<+ Pick<UploadOptionsProps, "onSelect" | "onClose">+> = ({ onSelect, onClose }) => (+ <>+ <SpacedRow>+ <DialogTitle variant="h5">{t("google_takeout")}</DialogTitle>+ <DialogCloseIconButton {...{ onClose }} />+ </SpacedRow>+ <Stack sx={{ padding: "18px 12px 20px 12px", gap: "16px" }}>+ <Stack sx={{ gap: "8px", "& button": { borderRadius: "16px" } }}>+ <FocusVisibleButton+ color="accent"+ fullWidth+ onClick={() => onSelect("folders")}+ >+ {t("select_folder")}+ </FocusVisibleButton>+ <FocusVisibleButton+ color="secondary"+ fullWidth+ onClick={() => onSelect("zips")}+ >+ {t("select_zips")}+ </FocusVisibleButton>+ <Link+ href="https://ente.io/help/photos/migration/from-google-photos/"+ target="_blank"+ rel="noopener"+ >+ <FocusVisibleButton color="secondary" fullWidth>+ {t("faq")}+ </FocusVisibleButton>+ </Link>+ </Stack>+ <Typography variant="small" sx={{ color: "text.muted" }}>+ {t("takeout_hint")}+ </Typography>+ </Stack>+ </>+);++const RoundedButtonStack = styled("div")`+ display: flex;+ flex-direction: column;+ gap: 4px;+ & > button {+ border-radius: 16px;+ }+`;diff --git a/web/apps/albums/vendor/photos/components/UploadProgress.tsx b/web/apps/albums/vendor/photos/components/UploadProgress.tsxnew file mode 100644index 0000000000..18254e5f76--- /dev/null+++ b/web/apps/albums/vendor/photos/components/UploadProgress.tsx@@ -0,0 +1,701 @@+// TODO: Audit this file+/* eslint-disable @typescript-eslint/no-unsafe-argument */+import CloseIcon from "@mui/icons-material/Close";+import ExpandMoreIcon from "@mui/icons-material/ExpandMore";+import UnfoldLessIcon from "@mui/icons-material/UnfoldLess";+import UnfoldMoreIcon from "@mui/icons-material/UnfoldMore";+import {+ Accordion,+ AccordionDetails,+ AccordionSummary,+ Box,+ Button,+ Dialog,+ DialogActions,+ DialogContent,+ DialogTitle,+ Divider,+ LinearProgress,+ Paper,+ Snackbar,+ Stack,+ styled,+ Tooltip,+ Typography,+ type AccordionProps,+ type DialogProps,+} from "@mui/material";+import { SpacedRow } from "ente-base/components/containers";+import { FilledIconButton } from "ente-base/components/mui";+import { useBaseContext } from "ente-base/context";+import { formattedListJoin } from "ente-base/i18n";+import { type UploadPhase } from "ente-gallery/services/upload";+import { t } from "i18next";+import memoize from "memoize-one";+import React, {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useState,+ type ReactElement,+} from "react";+import { Trans } from "react-i18next";+import {+ areEqual,+ FixedSizeList as List,+ type ListChildComponentProps,+ type ListItemKeySelector,+} from "react-window";+import type {+ FinishedUploadType,+ InProgressUpload,+ SegregatedFinishedUploads,+ UploadCounter,+ UploadFileNames,+} from "services/upload-manager";++interface UploadProgressProps {+ open: boolean;+ onClose: () => void;+ uploadCounter: UploadCounter;+ uploadPhase: UploadPhase;+ percentComplete: number;+ retryFailed: () => void;+ inProgressUploads: InProgressUpload[];+ uploadFileNames: UploadFileNames;+ finishedUploads: SegregatedFinishedUploads;+ hasLivePhotos: boolean;+ cancelUploads: () => void;+}++export const UploadProgress: React.FC<UploadProgressProps> = ({+ open,+ onClose,+ uploadCounter,+ uploadPhase,+ percentComplete,+ retryFailed,+ uploadFileNames,+ hasLivePhotos,+ inProgressUploads,+ finishedUploads,+ cancelUploads,+}) => {+ const { showMiniDialog } = useBaseContext();++ const [expanded, setExpanded] = useState(false);++ useEffect(() => {+ if (open) setExpanded(false);+ }, [open]);++ const handleClose = useCallback(() => {+ if (uploadPhase == "done") {+ onClose();+ } else {+ showMiniDialog({+ title: t("stop_uploads_title"),+ message: t("stop_uploads_message"),+ continue: {+ text: t("yes_stop_uploads"),+ color: "critical",+ action: cancelUploads,+ },+ cancel: t("no"),+ });+ }+ }, [uploadPhase, onClose, cancelUploads, showMiniDialog]);++ if (!open) {+ return <></>;+ }++ return (+ <UploadProgressContext.Provider+ value={{+ open,+ onClose: handleClose,+ uploadCounter,+ uploadPhase,+ percentComplete,+ retryFailed,+ inProgressUploads,+ uploadFileNames,+ finishedUploads,+ hasLivePhotos,+ expanded,+ setExpanded,+ }}+ >+ {expanded ? <UploadProgressDialog /> : <MinimizedUploadProgress />}+ </UploadProgressContext.Provider>+ );+};++/**+ * A context internal to the components of this file.+ */+interface UploadProgressContextT {+ open: boolean;+ onClose: () => void;+ uploadCounter: UploadCounter;+ uploadPhase: UploadPhase;+ percentComplete: number;+ retryFailed: () => void;+ inProgressUploads: InProgressUpload[];+ uploadFileNames: UploadFileNames;+ finishedUploads: SegregatedFinishedUploads;+ hasLivePhotos: boolean;+ expanded: boolean;+ setExpanded: React.Dispatch<React.SetStateAction<boolean>>;+}++const UploadProgressContext = createContext<UploadProgressContextT | undefined>(+ undefined,+);++/**+ * Convenience hook to obtain the non-null asserted+ * {@link UploadProgressContext}.+ *+ * The non-null assertion is reasonable since we provide it to the tree always+ * in an invariant that is local to this file (and thus has less chance of being+ * invalid in the future).+ */+const useUploadProgressContext = () => useContext(UploadProgressContext)!;++const MinimizedUploadProgress: React.FC = () => (+ <Snackbar open anchorOrigin={{ horizontal: "right", vertical: "bottom" }}>+ <Paper sx={{ width: "min(360px, 100svw)" }}>+ <UploadProgressHeader />+ </Paper>+ </Snackbar>+);++const UploadProgressHeader: React.FC = () => (+ <>+ <UploadProgressTitle />+ <UploadProgressBar />+ </>+);++const UploadProgressTitle: React.FC = () => {+ const { setExpanded, onClose, expanded } = useUploadProgressContext();+ const toggleExpanded = () => setExpanded((expanded) => !expanded);++ return (+ <DialogTitle>+ <SpacedRow>+ <Box>+ <Typography variant="h3">{t("file_upload")}</Typography>+ <UploadProgressSubtitleText />+ </Box>+ <Stack direction="row" sx={{ gap: 1 }}>+ <FilledIconButton onClick={toggleExpanded}>+ {expanded ? <UnfoldLessIcon /> : <UnfoldMoreIcon />}+ </FilledIconButton>+ <FilledIconButton onClick={onClose}>+ <CloseIcon />+ </FilledIconButton>+ </Stack>+ </SpacedRow>+ </DialogTitle>+ );+};++const UploadProgressSubtitleText: React.FC = () => {+ const { uploadPhase, uploadCounter, finishedUploads } =+ useUploadProgressContext();++ return (+ <Typography+ variant="body"+ sx={{+ fontWeight: "regular",+ color: "text.muted",+ marginTop: "4px",+ }}+ >+ {subtitleText(uploadPhase, uploadCounter, finishedUploads)}+ </Typography>+ );+};++const subtitleText = (+ uploadPhase: UploadPhase,+ uploadCounter: UploadCounter,+ finishedUploads: SegregatedFinishedUploads | null | undefined,+) => {+ switch (uploadPhase) {+ case "preparing":+ return t("preparing");+ case "readingMetadata":+ return t("upload_reading_metadata_files");+ case "uploading":+ return t("processed_counts", {+ count: uploadCounter.finished,+ total: uploadCounter.total,+ });+ case "cancelling":+ return t("upload_cancelling");+ case "done": {+ const count = uploadedFileCount(finishedUploads);+ const notCount = notUploadedFileCount(finishedUploads);+ const items: string[] = [];+ if (count) items.push(t("upload_done", { count }));+ if (notCount) items.push(t("upload_skipped", { count: notCount }));+ if (!items.length) {+ return t("upload_done", { count });+ } else {+ return formattedListJoin(items);+ }+ }+ }+};++const uploadedFileCount = (+ finishedUploads: SegregatedFinishedUploads | null | undefined,+) => {+ if (!finishedUploads) return 0;++ let c = 0;+ c += finishedUploads.get("uploaded")?.length ?? 0;+ c += finishedUploads.get("uploadedWithStaticThumbnail")?.length ?? 0;++ return c;+};++const notUploadedFileCount = (+ finishedUploads: SegregatedFinishedUploads | null | undefined,+) => {+ if (!finishedUploads) return 0;++ let c = 0;+ c += finishedUploads.get("alreadyUploaded")?.length ?? 0;+ c += finishedUploads.get("blocked")?.length ?? 0;+ c += finishedUploads.get("failed")?.length ?? 0;+ c += finishedUploads.get("largerThanAvailableStorage")?.length ?? 0;+ c += finishedUploads.get("tooLarge")?.length ?? 0;+ c += finishedUploads.get("unsupported")?.length ?? 0;+ c += finishedUploads.get("zeroSize")?.length ?? 0;+ return c;+};++const UploadProgressBar: React.FC = () => {+ const { uploadPhase, percentComplete } = useUploadProgressContext();++ return (+ <Box>+ {(uploadPhase == "readingMetadata" ||+ uploadPhase == "uploading") && (+ <>+ <LinearProgress+ sx={{ height: "2px", backgroundColor: "transparent" }}+ variant="determinate"+ value={percentComplete}+ />+ <Divider />+ </>+ )}+ </Box>+ );+};++function UploadProgressDialog() {+ const { open, onClose, uploadPhase, finishedUploads } =+ useUploadProgressContext();++ const [hasUnUploadedFiles, setHasUnUploadedFiles] = useState(false);++ useEffect(() => {+ setHasUnUploadedFiles(notUploadedFileCount(finishedUploads) > 0);+ }, [finishedUploads]);++ const handleClose: DialogProps["onClose"] = (_, reason) => {+ if (reason != "backdropClick") onClose();+ };++ return (+ <Dialog open={open} onClose={handleClose} maxWidth="xs" fullWidth>+ <UploadProgressHeader />+ {(uploadPhase == "uploading" || uploadPhase == "done") && (+ <DialogContent sx={{ "&&&": { px: 0 } }}>+ {uploadPhase == "uploading" && <InProgressSection />}+ <ResultSection+ resultType="uploaded"+ sectionTitle={t("successful_uploads")}+ />+ <ResultSection+ resultType="uploadedWithStaticThumbnail"+ sectionTitle={t("thumbnail_generation_failed")}+ sectionInfo={t("thumbnail_generation_failed_hint")}+ />+ {uploadPhase == "done" && hasUnUploadedFiles && (+ <NotUploadSectionHeader>+ {t("file_not_uploaded_list")}+ </NotUploadSectionHeader>+ )}+ <ResultSection+ resultType="blocked"+ sectionTitle={t("blocked_uploads")}+ sectionInfo={<Trans i18nKey={"blocked_uploads_hint"} />}+ />+ <ResultSection+ resultType="failed"+ sectionTitle={t("failed_uploads")}+ sectionInfo={+ uploadPhase == "done"+ ? undefined+ : t("failed_uploads_hint")+ }+ />+ <ResultSection+ resultType="alreadyUploaded"+ sectionTitle={t("ignored_uploads")}+ sectionInfo={t("ignored_uploads_hint")}+ />+ <ResultSection+ resultType="largerThanAvailableStorage"+ sectionTitle={t("insufficient_storage")}+ sectionInfo={t("insufficient_storage_hint")}+ />+ <ResultSection+ resultType="unsupported"+ sectionTitle={t("unsupported_files")}+ sectionInfo={t("unsupported_files_hint")}+ />+ <ResultSection+ resultType="zeroSize"+ sectionTitle={t("zero_size_files")}+ sectionInfo={t("zero_size_files_hint")}+ />+ <ResultSection+ resultType="tooLarge"+ sectionTitle={t("large_files")}+ sectionInfo={t("large_files_hint")}+ />+ </DialogContent>+ )}+ {uploadPhase == "done" && <DoneFooter />}+ </Dialog>+ );+}++const InProgressSection: React.FC = () => {+ const { inProgressUploads, hasLivePhotos, uploadFileNames, uploadPhase } =+ useUploadProgressContext();++ const fileList = inProgressUploads;++ // @ts-expect-error Need to add types+ const renderListItem = ({ localFileID, progress }) => {+ return (+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ <InProgressItemContainer key={localFileID}>+ <InProgressFileName>+ {uploadFileNames.get(localFileID)}+ </InProgressFileName>+ {uploadPhase == "uploading" && (+ <InProgressPercent>{`${progress}%`}</InProgressPercent>+ )}+ </InProgressItemContainer>+ );+ };++ // @ts-expect-error Need to add types+ const getItemTitle = ({ localFileID, progress }) => {+ return `${uploadFileNames.get(localFileID)} - ${progress}%`;+ };++ // @ts-expect-error Need to add types+ const generateItemKey = ({ localFileID, progress }) => {+ return `${localFileID}-${progress}`;+ };++ return (+ <SectionAccordion>+ <SectionAccordionSummary expandIcon={<ExpandMoreIcon />}>+ <TitleText+ title={t("uploads_in_progress")}+ count={inProgressUploads.length}+ />+ </SectionAccordionSummary>+ <SectionAccordionDetails>+ {hasLivePhotos && (+ <SectionInfo>{t("live_photos_detected")}</SectionInfo>+ )}+ <ItemList+ items={fileList}+ generateItemKey={generateItemKey}+ getItemTitle={getItemTitle}+ renderListItem={renderListItem}+ maxHeight={160}+ itemSize={35}+ />+ </SectionAccordionDetails>+ </SectionAccordion>+ );+};++const InProgressItemContainer = styled("div")(({ theme }) => ({+ width: "100%",+ display: "flex",+ alignItems: "center",+ gap: theme.spacing(1.5),+}));++const InProgressFileName = styled("span")({+ flex: 1,+ minWidth: 0,+ overflow: "hidden",+ whiteSpace: "nowrap",+ textOverflow: "ellipsis",+});++const InProgressPercent = styled("span")(({ theme }) => ({+ flexShrink: 0,+ color: theme.vars.palette.text.muted,+ fontVariantNumeric: "tabular-nums",+}));++const SectionAccordion = styled((props: AccordionProps) => (+ <Accordion disableGutters elevation={0} square {...props} />+))(({ theme }) => ({+ borderTop: `1px solid ${theme.vars.palette.divider}`,+ "&:before": { display: "none" },+ "&:last-child": { borderBottom: `1px solid ${theme.vars.palette.divider}` },+}));++const SectionAccordionSummary = styled(AccordionSummary)(({ theme }) => ({+ backgroundColor: theme.vars.palette.fill.fainter,+ // AccordionSummary is a button, and for a reasons to do with MUI internal+ // that I didn't explore further, the user agent default font family is+ // getting applied in this case.+ fontFamily: "inherit",+}));++const SectionAccordionDetails = styled(AccordionDetails)(({ theme }) => ({+ padding: theme.spacing(2),+}));++const SectionInfo: React.FC<React.PropsWithChildren> = ({ children }) => (+ <Typography variant="small" sx={{ color: "text.muted", mb: 1 }}>+ {children}+ </Typography>+);++const NotUploadSectionHeader = styled("div")(+ ({ theme }) => `+ text-align: center;+ color: ${theme.vars.palette.critical.main};+ border-bottom: 1px solid ${theme.vars.palette.critical.main};+ margin:${theme.spacing(3, 2, 1)}+`,+);++interface ResultSectionProps {+ resultType: FinishedUploadType;+ sectionTitle: string;+ sectionInfo?: React.ReactNode;+}++const ResultSection: React.FC<ResultSectionProps> = ({+ resultType,+ sectionTitle,+ sectionInfo,+}) => {+ const { finishedUploads, uploadFileNames } = useUploadProgressContext();++ const fileList = finishedUploads.get(resultType);++ if (!fileList?.length) {+ return <></>;+ }++ // @ts-expect-error Need to add types+ const renderListItem = (fileID) => {+ return (+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ <ResultItemContainer key={fileID}>+ {uploadFileNames.get(fileID)}+ </ResultItemContainer>+ );+ };++ // @ts-expect-error Need to add types+ const getItemTitle = (fileID) => {+ return uploadFileNames.get(fileID)!;+ };++ // @ts-expect-error Need to add types+ const generateItemKey = (fileID) => {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return+ return fileID;+ };++ return (+ <SectionAccordion>+ <SectionAccordionSummary expandIcon={<ExpandMoreIcon />}>+ <TitleText title={sectionTitle} count={fileList.length} />+ </SectionAccordionSummary>+ <SectionAccordionDetails>+ {sectionInfo && <SectionInfo>{sectionInfo}</SectionInfo>}+ <ItemList+ items={fileList}+ generateItemKey={generateItemKey}+ getItemTitle={getItemTitle}+ renderListItem={renderListItem}+ maxHeight={160}+ itemSize={35}+ />+ </SectionAccordionDetails>+ </SectionAccordion>+ );+};++const ResultItemContainer = styled("div")`+ position: relative;+ top: 5px;+ display: inline-block;+ max-width: 394px;+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+`;++interface TitleTextProps {+ title: string;+ count: number | undefined;+}++const TitleText: React.FC<TitleTextProps> = ({ title, count }) => (+ <Stack+ direction="row"+ // Need to reset the font weight since it gets reset by the+ // AccordionSummary (see SectionAccordionSummary).+ sx={{ gap: 1, fontWeight: "regular", alignItems: "baseline" }}+ >+ <Typography>{title}</Typography>+ <Typography variant="small" sx={{ color: "text.faint" }}>+ {"•"}+ </Typography>+ <Typography variant="small" sx={{ color: "text.faint" }}>+ {count ?? 0}+ </Typography>+ </Stack>+);++interface ItemListProps<T> {+ items: T[];+ generateItemKey: (item: T) => string | number;+ getItemTitle: (item: T) => string;+ renderListItem: (item: T) => React.JSX.Element;+ maxHeight?: number;+ itemSize?: number;+}++interface ItemData<T> {+ renderListItem: (item: T) => React.JSX.Element;+ getItemTitle: (item: T) => string;+ items: T[];+}++const createItemData: <T>(+ renderListItem: (item: T) => React.JSX.Element,+ getItemTitle: (item: T) => string,+ items: T[],+) => ItemData<T> = memoize((renderListItem, getItemTitle, items) => ({+ // TODO+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ renderListItem,+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ getItemTitle,+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ items,+}));++// TODO: Too many non-null assertions++// @ts-expect-error "TODO: Understand and fix the type error here"+const Row: <T>({+ index,+ style,+ data,+}: ListChildComponentProps<ItemData<T>>) => ReactElement = React.memo(+ ({ index, style, data }) => {+ const { renderListItem, items, getItemTitle } = data;+ return (+ <Tooltip+ slotProps={{+ // Reduce the vertical offset of the tooltip "popper" from+ // the element on which the tooltip appears.+ popper: {+ modifiers: [+ { name: "offset", options: { offset: [0, -14] } },+ ],+ },+ }}+ title={getItemTitle(items[index]!)}+ placement="bottom-start"+ enterDelay={300}+ enterNextDelay={100}+ >+ <div style={style}>{renderListItem(items[index]!)}</div>+ </Tooltip>+ );+ },+ areEqual,+);++function ItemList<T>(props: ItemListProps<T>) {+ const itemData = createItemData(+ props.renderListItem,+ props.getItemTitle,+ props.items,+ );++ const getItemKey: ListItemKeySelector<ItemData<T>> = (index, data) => {+ const { items } = data;+ return props.generateItemKey(items[index]!);+ };++ return (+ <Box sx={{ pl: 2 }}>+ <List+ itemData={itemData}+ height={Math.min(+ props.itemSize! * props.items.length,+ props.maxHeight!,+ )}+ width={"100%"}+ itemSize={props.itemSize!}+ itemCount={props.items.length}+ itemKey={getItemKey}+ >+ {Row}+ </List>+ </Box>+ );+}++const DoneFooter: React.FC = () => {+ const { uploadPhase, finishedUploads, retryFailed, onClose } =+ useUploadProgressContext();++ return (+ <DialogActions>+ {uploadPhase == "done" &&+ ((finishedUploads.get("failed")?.length ?? 0) > 0 ||+ (finishedUploads.get("blocked")?.length ?? 0) > 0 ? (+ <Button fullWidth onClick={retryFailed}>+ {t("retry_failed_uploads")}+ </Button>+ ) : (+ <Button fullWidth onClick={onClose}>+ {t("close")}+ </Button>+ ))}+ </DialogActions>+ );+};diff --git a/web/apps/albums/vendor/photos/components/utils/hooks-app.ts b/web/apps/albums/vendor/photos/components/utils/hooks-app.tsnew file mode 100644index 0000000000..966be39c1d--- /dev/null+++ b/web/apps/albums/vendor/photos/components/utils/hooks-app.ts@@ -0,0 +1,30 @@+import { type NotificationAttributes } from "ente-new/photos/components/Notification";+import { useCallback, useState } from "react";++/**+ * A React hook for simplifying the provisioning of a {@link showMiniDialog}+ * function to inject in app contexts, and of the other props that are needed to+ * be passed to the {@link AttributedMiniDialog}.+ */+export const useNotification = () => {+ const [attributes, setAttributes] = useState<+ NotificationAttributes | undefined+ >(undefined);++ const [open, setOpen] = useState(false);++ const showNotification = useCallback(+ (attributes: NotificationAttributes) => {+ setAttributes(attributes);+ setOpen(true);+ },+ [],+ );++ const handleClose = useCallback(() => setOpen(false), []);++ return {+ showNotification,+ notificationProps: { open, onClose: handleClose, attributes },+ };+};diff --git a/web/apps/albums/vendor/photos/hooks/useJoinAlbum.ts b/web/apps/albums/vendor/photos/hooks/useJoinAlbum.tsnew file mode 100644index 0000000000..36d9291816--- /dev/null+++ b/web/apps/albums/vendor/photos/hooks/useJoinAlbum.ts@@ -0,0 +1,146 @@+import type { PublicAlbumsCredentials } from "ente-base/http";+import { albumsAppOrigin, photosAppOrigin } from "ente-base/origins";+import type { Collection } from "ente-media/collection";++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?: React.RefObject<PublicAlbumsCredentials | undefined>;+}++export interface UseJoinAlbumReturn {+ /** Handler for join album action */+ handleJoinAlbum: () => void;+}++/**+ * Build the web app redirect URL for joining an album.+ */+const buildWebRedirectURL = (+ accessToken: string,+ collectionId: number,+ currentHash: string,+ jwtToken?: string,+): string => {+ const webAppURL = photosAppOrigin();+ const hashSuffix = jwtToken ? `&jwt=${encodeURIComponent(jwtToken)}` : "";+ return `${webAppURL}/?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,+ currentHash: string,+ jwtToken?: string,+): void => {+ // Redirect to web app with joinAlbum parameter+ // The URL contains all necessary context (token, collectionId, JWT, hash) which will be+ // stored on web.ente.io after the domain transition+ const redirectURL = buildWebRedirectURL(+ accessToken,+ collectionId,+ currentHash,+ jwtToken,+ );+ 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>,+ timeoutMs = 2500,+): (() => void) => {+ let appOpened = false;++ // Track visibility changes - app opening will hide the page+ const onVisibilityChange = () => {+ if (document.visibilityState === "hidden") {+ appOpened = true;+ }+ };++ // Track page hide - more reliable on some Android browsers+ const onPageHide = () => {+ appOpened = true;+ };++ document.addEventListener("visibilitychange", onVisibilityChange);+ window.addEventListener("pagehide", onPageHide);++ // Try to open the app using the deep link+ // Use assign() instead of href for better compatibility with iOS Safari/PWAs+ window.location.assign(deepLinkURL);++ // Set a timeout to check if the app opened+ const timeoutId = setTimeout(() => {+ if (!appOpened) {+ void fallbackFn();+ }+ cleanup();+ }, timeoutMs);++ const cleanup = () => {+ clearTimeout(timeoutId);+ document.removeEventListener("visibilitychange", onVisibilityChange);+ window.removeEventListener("pagehide", onPageHide);+ };++ // Return cleanup function+ return cleanup;+};++/**+ * 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,+ collectionKey,+ credentials,+}: UseJoinAlbumProps): UseJoinAlbumReturn => {+ const handleJoinAlbum = () => {+ if (!publicCollection || !accessToken || !collectionKey) {+ return;+ }++ // Get the original hash directly from the current URL+ const currentHash = window.location.hash.slice(1);+ const jwtToken = credentials?.current?.accessTokenJWT;+ const collectionId = publicCollection.id;++ // Create fallback function for mobile deep linking+ const fallbackToWeb = () => {+ handleWebFallback(accessToken, collectionId, currentHash, jwtToken);+ };++ // Check if on Android and try deep link with custom scheme with action=join parameter.+ // Skip deep linking on iOS - custom URL schemes show an error+ // dialog when the app isn't installed. On iOS Safari, if the photos app+ // is installed, a banner already appears at the top prompting to open in app.+ if (navigator.userAgent.includes("Android")) {+ const albumsHost = new URL(albumsAppOrigin()).host;+ const deepLinkURL = `ente://${albumsHost}/?action=join&t=${encodeURIComponent(accessToken)}#${currentHash}`;++ tryDeepLinkWithFallback(deepLinkURL, fallbackToWeb);+ } else {+ // Desktop and iOS: use the standard web flow directly+ handleWebFallback(accessToken, collectionId, currentHash, jwtToken);+ }+ };++ return { handleJoinAlbum };+};diff --git a/web/apps/albums/vendor/photos/services/upload-manager.ts b/web/apps/albums/vendor/photos/services/upload-manager.tsnew file mode 100644index 0000000000..76ba4f5c86--- /dev/null+++ b/web/apps/albums/vendor/photos/services/upload-manager.ts@@ -0,0 +1,790 @@+// TODO: Audit this file+// TODO: Too many null assertions in this file. The types need reworking.+import { ensureLocalUser } from "ente-accounts/services/user";+import { isDesktop } from "ente-base/app";+import { createComlinkCryptoWorker } from "ente-base/crypto";+import { type CryptoWorker } from "ente-base/crypto/worker";+import { lowercaseExtension, nameAndExtension } from "ente-base/file-name";+import type { PublicAlbumsCredentials } from "ente-base/http";+import log from "ente-base/log";+import { ComlinkWorker } from "ente-base/worker/comlink-worker";+import {+ markUploadedAndObtainProcessableItem,+ shouldDisableCFUploadProxy,+ type ClusteredUploadItem,+ type UploadPhase,+ type UploadResult,+ type UploadableUploadItem,+} from "ente-gallery/services/upload";+import {+ metadataJSONMapKeyForJSON,+ tryParseTakeoutMetadataJSON,+ type ParsedMetadataJSON,+} from "ente-gallery/services/upload/metadata-json";+import UploadService, {+ areLivePhotoAssets,+ isUploadCancelledError,+ upload,+ uploadCancelledErrorMessage,+ uploadItemFileName,+ type PotentialLivePhotoAsset,+ type UploadAsset,+} from "ente-gallery/services/upload/upload-service";+import { processVideoNewUpload } from "ente-gallery/services/video";+import type { Collection } from "ente-media/collection";+import { type EnteFile } from "ente-media/file";+import {+ fileCreationTime,+ type ParsedMetadata,+} from "ente-media/file-metadata";+import { FileType } from "ente-media/file-type";+import { potentialFileTypeFromExtension } from "ente-media/live-photo";+import { savedPublicCollectionFiles } from "ente-new/albums/services/public-albums-fdb";+import { computeNormalCollectionFilesFromSaved } from "ente-new/photos/services/file";+import { indexNewUpload } from "ente-new/photos/services/ml";+import { wait } from "ente-utils/promise";+import watcher from "services/watch";++export type FileID = number;++export type PercentageUploaded = number;+/* localID => fileName */+export type UploadFileNames = Map<FileID, string>;++export interface UploadCounter {+ finished: number;+ total: number;+}++export interface InProgressUpload {+ localFileID: FileID;+ progress: PercentageUploaded;+}++/**+ * A variant of {@link UploadResult}'s {@link type} values used when segregating+ * finished uploads in the UI. "addedSymlink" is treated as "uploaded",+ * everything else remains as it were.+ */+export type FinishedUploadType = Exclude<UploadResult["type"], "addedSymlink">;++export type InProgressUploads = Map<FileID, PercentageUploaded>;++export type FinishedUploads = Map<FileID, FinishedUploadType>;++export type SegregatedFinishedUploads = Map<FinishedUploadType, FileID[]>;++export interface ProgressUpdater {+ setPercentComplete: React.Dispatch<React.SetStateAction<number>>;+ setUploadCounter: React.Dispatch<React.SetStateAction<UploadCounter>>;+ setUploadPhase: (phase: UploadPhase) => void;+ setInProgressUploads: React.Dispatch<+ React.SetStateAction<InProgressUpload[]>+ >;+ setFinishedUploads: React.Dispatch<+ React.SetStateAction<SegregatedFinishedUploads>+ >;+ setUploadFilenames: React.Dispatch<React.SetStateAction<UploadFileNames>>;+ setHasLivePhotos: React.Dispatch<React.SetStateAction<boolean>>;+ setUploadProgressView: React.Dispatch<React.SetStateAction<boolean>>;+}++/** The number of uploads to process in parallel. */+const maxConcurrentUploads = 4;++export type UploadItemWithCollection = UploadAsset & {+ localID: number;+ collectionID: number;+};++class UIService {+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ // @ts-ignore+ private progressUpdater: ProgressUpdater;++ // UPLOAD LEVEL STATES+ private uploadPhase: UploadPhase = "preparing";+ private filenames = new Map<number, string>();+ private hasLivePhoto = false;+ private uploadProgressView = false;++ // STAGE LEVEL STATES+ private perFileProgress = 0;+ private filesUploadedCount = 0;+ private totalFilesCount = 0;+ private inProgressUploads: InProgressUploads = new Map();+ private finishedUploads: FinishedUploads = new Map();++ init(progressUpdater: ProgressUpdater) {+ this.progressUpdater = progressUpdater;+ this.progressUpdater.setUploadPhase(this.uploadPhase);+ this.progressUpdater.setUploadFilenames(this.filenames);+ this.progressUpdater.setHasLivePhotos(this.hasLivePhoto);+ this.progressUpdater.setUploadProgressView(this.uploadProgressView);+ this.progressUpdater.setUploadCounter({+ finished: this.filesUploadedCount,+ total: this.totalFilesCount,+ });+ this.progressUpdater.setInProgressUploads(+ convertInProgressUploadsToList(this.inProgressUploads),+ );+ this.progressUpdater.setFinishedUploads(+ groupByResult(this.finishedUploads),+ );+ }++ reset(count = 0) {+ this.setTotalFileCount(count);+ this.filesUploadedCount = 0;+ this.inProgressUploads = new Map<number, number>();+ this.finishedUploads = new Map<number, FinishedUploadType>();+ this.updateProgressBarUI();+ }++ setTotalFileCount(count: number) {+ this.totalFilesCount = count;+ if (count > 0) {+ this.perFileProgress = 100 / this.totalFilesCount;+ } else {+ this.perFileProgress = 0;+ }+ }++ setFileProgress(key: number, progress: number) {+ this.inProgressUploads.set(key, progress);+ this.updateProgressBarUI();+ }++ setUploadPhase(phase: UploadPhase) {+ this.uploadPhase = phase;+ this.progressUpdater.setUploadPhase(phase);+ }++ setFiles(files: { localID: number; fileName: string }[]) {+ const filenames = new Map(files.map((f) => [f.localID, f.fileName]));+ this.filenames = filenames;+ this.progressUpdater.setUploadFilenames(filenames);+ }++ setHasLivePhoto(hasLivePhoto: boolean) {+ this.hasLivePhoto = hasLivePhoto;+ this.progressUpdater.setHasLivePhotos(hasLivePhoto);+ }++ setUploadProgressView(uploadProgressView: boolean) {+ this.uploadProgressView = uploadProgressView;+ this.progressUpdater.setUploadProgressView(uploadProgressView);+ }++ increaseFileUploaded() {+ this.filesUploadedCount++;+ this.updateProgressBarUI();+ }++ moveFileToResultList(key: number, type: FinishedUploadType) {+ this.finishedUploads.set(key, type);+ this.inProgressUploads.delete(key);+ this.updateProgressBarUI();+ }++ hasFilesInResultList() {+ return this.finishedUploads.size > 0;+ }++ private updateProgressBarUI() {+ const {+ setPercentComplete,+ setUploadCounter,+ setInProgressUploads,+ setFinishedUploads,+ } = this.progressUpdater;+ setUploadCounter({+ finished: this.filesUploadedCount,+ total: this.totalFilesCount,+ });+ let percentComplete =+ this.perFileProgress *+ (this.finishedUploads.size || this.filesUploadedCount);++ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ for (const [_, progress] of this.inProgressUploads) {+ // filter negative indicator values during percentComplete calculation+ if (progress < 0) {+ continue;+ }+ percentComplete += (this.perFileProgress * progress) / 100;+ }++ setPercentComplete(percentComplete);+ setInProgressUploads(+ convertInProgressUploadsToList(this.inProgressUploads),+ );+ setFinishedUploads(groupByResult(this.finishedUploads));+ }++ /**+ * Update the upload progress shown in the UI to {@link percentage} for the+ * file with the given {@link fileLocalID}.+ *+ * @param percentage The upload completion percentage. It should be a value+ * between 0 and 100 (inclusive).+ */+ updateUploadProgress(fileLocalID: number, percentage: number) {+ this.inProgressUploads.set(fileLocalID, Math.round(percentage));+ this.updateProgressBarUI();+ }+}++function convertInProgressUploadsToList(inProgressUploads: InProgressUploads) {+ return [...inProgressUploads.entries()].map(+ ([localFileID, progress]) =>+ ({ localFileID, progress }) as InProgressUpload,+ );+}++const groupByResult = (finishedUploads: FinishedUploads) => {+ const groups: SegregatedFinishedUploads = new Map();+ for (const [localID, result] of finishedUploads) {+ if (!groups.has(result)) groups.set(result, []);+ groups.get(result)!.push(localID);+ }+ return groups;+};++class UploadManager {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ private comlinkCryptoWorkers: ComlinkWorker<typeof CryptoWorker>[] =+ new Array(maxConcurrentUploads);+ private parsedMetadataJSONMap = new Map<string, ParsedMetadataJSON>();+ private itemsToBeUploaded: ClusteredUploadItem[] = [];+ private failedItems: ClusteredUploadItem[] = [];+ private existingFiles: EnteFile[] = [];+ private onUploadFile: ((file: EnteFile) => void) | undefined;+ private collections = new Map<number, Collection>();+ private uploadInProgress = false;+ private publicAlbumsCredentials: PublicAlbumsCredentials | undefined;+ private uploaderName: string | undefined;+ /**+ * When `true`, then the next call to {@link abortIfCancelled} will throw.+ *+ * See: [Note: Upload cancellation].+ */+ private shouldUploadBeCancelled = false;++ private uiService = new UIService();++ public init(+ progressUpdater: ProgressUpdater,+ onUploadFile: (file: EnteFile) => void,+ publicAlbumsCredentials: PublicAlbumsCredentials | undefined,+ ) {+ this.uiService.init(progressUpdater);+ UploadService.init(publicAlbumsCredentials);+ this.onUploadFile = onUploadFile;+ this.publicAlbumsCredentials = publicAlbumsCredentials;+ }++ logout() {+ // TODO: Consolidate state in one place instead of spreading it.+ UploadService.logout();+ }++ public isUploadRunning() {+ return this.uploadInProgress;+ }++ public prepareForNewUpload(+ parsedMetadataJSONMap?: Map<string, ParsedMetadataJSON>,+ ) {+ this.itemsToBeUploaded = [];+ this.failedItems = [];+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ this.parsedMetadataJSONMap = parsedMetadataJSONMap ?? new Map();+ this.uploaderName = undefined;+ this.shouldUploadBeCancelled = false;++ this.uiService.reset();+ this.uiService.setUploadPhase("preparing");+ }++ showUploadProgressDialog() {+ this.uiService.setUploadProgressView(true);+ }++ /**+ * Upload files+ *+ * This method waits for all the files to get uploaded (successfully or+ * unsuccessfully) before returning.+ *+ * It is an error to call this method when there is already an in-progress+ * upload.+ *+ * @param itemsWithCollection The items to upload, each paired with the id+ * of the collection that they should be uploaded into.+ *+ * @param collections The collections to which the files are being uploaded.+ *+ * These are not all the user's collections - these are just the collections+ * mentioned by one or more {@link itemsWithCollection}.+ *+ * @returns `true` if at least one file was processed+ */+ public async uploadItems(+ itemsWithCollection: UploadItemWithCollection[],+ collections: Collection[],+ uploaderName?: string,+ ) {+ if (this.uploadInProgress)+ throw new Error("Cannot run multiple uploads at once");++ log.info(`Uploading ${itemsWithCollection.length} files`);+ this.uploadInProgress = true;+ this.uploaderName = uploaderName;++ const logInterval = setInterval(logAboutMemoryPressureIfNeeded, 1000);++ try {+ await this.updateExistingFilesAndCollections(collections);++ const namedItems = itemsWithCollection.map(+ makeUploadItemWithCollectionIDAndName,+ );++ this.uiService.setFiles(namedItems);++ const [metadataItems, mediaItems] =+ splitMetadataAndMediaItems(namedItems);++ if (metadataItems.length) {+ this.uiService.setUploadPhase("readingMetadata");+ await this.parseMetadataJSONFiles(metadataItems);+ }++ if (mediaItems.length) {+ const clusteredMediaItems = await clusterLivePhotos(+ mediaItems,+ this.parsedMetadataJSONMap,+ );++ this.abortIfCancelled();++ // Live photos might've been clustered together, reset the list+ // of files to reflect that.+ this.uiService.setFiles(clusteredMediaItems);++ this.uiService.setHasLivePhoto(+ mediaItems.length != clusteredMediaItems.length,+ );++ await this.uploadMediaItems(clusteredMediaItems);+ }+ } catch (e) {+ if (!isUploadCancelledError(e)) {+ log.error("Upload failed", e);+ throw e;+ }+ } finally {+ this.uiService.setUploadPhase("done");+ void globalThis.electron?.clearPendingUploads();+ for (let i = 0; i < maxConcurrentUploads; i++) {+ this.comlinkCryptoWorkers[i]?.terminate();+ }+ this.uploadInProgress = false;+ clearInterval(logInterval);+ }++ return this.uiService.hasFilesInResultList();+ }++ /**+ * Upload a single file to the given collection.+ *+ * @param file A web {@link File} object representing the file to upload.+ *+ * @param collection The {@link Collection} in which the file should be+ * added.+ *+ * @param sourceEnteFile The {@link EnteFile} from which the file being+ * uploaded has been derived. This is used to extract and reassociated+ * relevant metadata to the newly uploaded file.+ */+ public async uploadFile(+ file: File,+ collection: Collection,+ sourceEnteFile: EnteFile,+ ) {+ const timestamp = fileCreationTime(sourceEnteFile);+ const dateTime = sourceEnteFile.pubMagicMetadata?.data.dateTime;+ const offset = sourceEnteFile.pubMagicMetadata?.data.offsetTime;++ const creationDate: ParsedMetadata["creationDate"] = dateTime+ ? { timestamp, dateTime, offset }+ : undefined;++ // Fallback to the timestamp if a creationDate could not be constructed.+ const creationTime = creationDate ? undefined : timestamp;++ const item = {+ uploadItem: file,+ pathPrefix: undefined,+ localID: 1,+ collectionID: collection.id,+ externalParsedMetadata: { creationDate, creationTime },+ };++ return this.uploadItems([item], [collection]);+ }++ private abortIfCancelled = () => {+ if (this.shouldUploadBeCancelled) {+ throw new Error(uploadCancelledErrorMessage);+ }+ };++ private async updateExistingFilesAndCollections(collections: Collection[]) {+ if (this.publicAlbumsCredentials) {+ this.existingFiles = await savedPublicCollectionFiles(+ this.publicAlbumsCredentials.accessToken,+ );+ } else {+ const files = await computeNormalCollectionFilesFromSaved();+ const userID = ensureLocalUser().id;+ this.existingFiles = files.filter((file) => file.ownerID == userID);+ }+ this.collections = new Map(+ collections.map((collection) => [collection.id, collection]),+ );+ }++ private async parseMetadataJSONFiles(+ items: UploadItemWithCollectionIDAndName[],+ ) {+ this.uiService.reset(items.length);++ for (const item of items) {+ this.abortIfCancelled();++ const { uploadItem, pathPrefix, fileName, collectionID } = item;+ log.info(`Parsing metadata JSON ${fileName}`);+ const metadataJSON = await tryParseTakeoutMetadataJSON(uploadItem!);+ if (metadataJSON) {+ const key = metadataJSONMapKeyForJSON(+ pathPrefix,+ collectionID,+ fileName,+ );+ this.parsedMetadataJSONMap.set(key, metadataJSON);+ this.uiService.increaseFileUploaded();+ }+ }+ }++ private async uploadMediaItems(mediaItems: ClusteredUploadItem[]) {+ this.itemsToBeUploaded = [...this.itemsToBeUploaded, ...mediaItems];+ this.uiService.reset(mediaItems.length);+ await UploadService.setFileCount(mediaItems.length);+ this.uiService.setUploadPhase("uploading");++ const uploadProcesses = new Array<Promise<void>>();+ for (+ let i = 0;+ i < maxConcurrentUploads && this.itemsToBeUploaded.length > 0;+ i+++ ) {+ this.comlinkCryptoWorkers[i] = createComlinkCryptoWorker();+ const worker = await this.comlinkCryptoWorkers[i]!.remote;+ uploadProcesses.push(this.uploadNextItemInQueue(worker));+ }+ await Promise.all(uploadProcesses);+ }++ private async uploadNextItemInQueue(worker: CryptoWorker) {+ const uiService = this.uiService;+ const uploadContext = {+ isCFUploadProxyDisabled: shouldDisableCFUploadProxy(),+ publicAlbumsCredentials: this.publicAlbumsCredentials,+ abortIfCancelled: this.abortIfCancelled.bind(this),+ updateUploadProgress:+ uiService.updateUploadProgress.bind(uiService),+ };++ while (this.itemsToBeUploaded.length > 0) {+ this.abortIfCancelled();+ logAboutMemoryPressureIfNeeded();++ const clusteredItem = this.itemsToBeUploaded.pop()!;+ const { localID, collectionID } = clusteredItem;+ const collection = this.collections.get(collectionID)!;+ const uploadableItem = { ...clusteredItem, collection };++ uiService.setFileProgress(localID, 0);+ await wait(0);++ const uploadResult = await upload(+ uploadableItem,+ this.uploaderName,+ this.existingFiles,+ this.parsedMetadataJSONMap,+ worker,+ uploadContext,+ );++ const finishedUploadType = await this.postUploadTask(+ uploadableItem,+ uploadResult,+ );++ uiService.moveFileToResultList(localID, finishedUploadType);+ uiService.increaseFileUploaded();+ UploadService.reducePendingUploadCount();+ }+ }++ private async postUploadTask(+ uploadableItem: UploadableUploadItem,+ uploadResult: UploadResult,+ ): Promise<FinishedUploadType> {+ const type = uploadResult.type;+ log.info(`Upload ${uploadableItem.fileName} | ${type}`);+ try {+ const processableUploadItem =+ await markUploadedAndObtainProcessableItem(uploadableItem);++ switch (uploadResult.type) {+ case "failed":+ case "blocked":+ // Retriable error.+ this.failedItems.push(uploadableItem);+ break;++ case "addedSymlink":+ this.updateExistingFiles(uploadResult.file);+ break;++ case "uploaded":+ case "uploadedWithStaticThumbnail":+ {+ const { file } = uploadResult;++ indexNewUpload(file, processableUploadItem);+ processVideoNewUpload(file, processableUploadItem);++ this.updateExistingFiles(file);+ }+ break;+ }++ if (isDesktop && watcher.isUploadRunning()) {+ watcher.onFileUpload(uploadableItem, uploadResult);+ }++ return type == "addedSymlink" ? "uploaded" : type;+ } catch (e) {+ log.error("Post file upload action failed", e);+ return "failed";+ }+ }++ public cancelRunningUpload() {+ log.info("User cancelled upload");+ this.uiService.setUploadPhase("cancelling");+ this.shouldUploadBeCancelled = true;+ }++ /**+ * Return the list of failed items from the last upload, along with other+ * state needed to attempt to reupload them.+ */+ public failedItemState() {+ return {+ items: [...this.failedItems],+ collections: [...this.collections.values()],+ parsedMetadataJSONMap: this.parsedMetadataJSONMap,+ };+ }++ public getUploaderName() {+ return this.uploaderName;+ }++ private updateExistingFiles(file: EnteFile) {+ this.existingFiles.push(file);+ this.onUploadFile!(file);+ }++ /**+ * `true` if an upload is currently in-progress (either a bunch of files+ * directly uploaded by the user, or files being uploaded by the folder+ * watch functionality).+ */+ public isUploadInProgress = () => {+ return this.uploadInProgress || watcher.isUploadRunning();+ };+}++/**+ * Singleton instance of {@link UploadManager}.+ */+export const uploadManager = new UploadManager();++/**+ * The data operated on by the intermediate stages of the upload.+ *+ * [Note: Intermediate file types during upload]+ *+ * As files progress through stages, they get more and more bits tacked on to+ * them. These types document the journey.+ *+ * - The input is {@link UploadItemWithCollection}. This can either be a new+ * {@link UploadItemWithCollection}, in which case it'll only have a+ * {@link localID}, {@link collectionID} and a {@link uploadItem}. Or it could+ * be a retry, in which case it'll not have a {@link uploadItem} but instead+ * will have data from a previous stage (concretely, it'll just be a+ * relabelled {@link ClusteredUploadItem}), like a snake eating its tail.+ *+ * - Immediately we convert it to {@link UploadItemWithCollectionIDAndName}.+ * This is to mostly systematize what we have, and also attach a+ * {@link fileName}.+ *+ * - These then get converted to "assets", whereby both parts of a live photo+ * are combined. This is a {@link ClusteredUploadItem}.+ *+ * - On to the {@link ClusteredUploadItem} we attach the corresponding+ * {@link collection}, giving us {@link UploadableUploadItem}. This is what+ * gets queued and then passed to the {@link upload}.+ */+type UploadItemWithCollectionIDAndName = UploadAsset & {+ /** A unique ID for the duration of the upload */+ localID: number;+ /** The ID of the collection to which this file should be uploaded. */+ collectionID: number;+ /**+ * The name of the file.+ *+ * In case of live photos, this'll be the name of the image part.+ */+ fileName: string;+};++const makeUploadItemWithCollectionIDAndName = (+ f: UploadItemWithCollection,+): UploadItemWithCollectionIDAndName => ({+ localID: f.localID,+ collectionID: f.collectionID,+ fileName: f.isLivePhoto+ ? uploadItemFileName(f.livePhotoAssets!.image)+ : uploadItemFileName(f.uploadItem!),+ isLivePhoto: f.isLivePhoto,+ uploadItem: f.uploadItem,+ pathPrefix: f.pathPrefix,+ livePhotoAssets: f.livePhotoAssets,+ externalParsedMetadata: f.externalParsedMetadata,+});++const splitMetadataAndMediaItems = (+ items: UploadItemWithCollectionIDAndName[],+): [+ metadata: UploadItemWithCollectionIDAndName[],+ media: UploadItemWithCollectionIDAndName[],+] =>+ items.reduce(+ ([metadata, media], f) => {+ if (lowercaseExtension(f.fileName) == "json") metadata.push(f);+ else media.push(f);+ return [metadata, media];+ },+ [+ new Array<UploadItemWithCollectionIDAndName>(),+ new Array<UploadItemWithCollectionIDAndName>(),+ ],+ );++/**+ * Go through the given files, combining any sibling image + video assets into a+ * single live photo when appropriate.+ */+const clusterLivePhotos = async (+ _items: UploadItemWithCollectionIDAndName[],+ parsedMetadataJSONMap: Map<string, ParsedMetadataJSON>,+) => {+ const result: ClusteredUploadItem[] = [];+ type ItemAsset = PotentialLivePhotoAsset & {+ localID: number;+ isLivePhoto?: boolean;+ };+ const items: ItemAsset[] = _items.map((item) => ({+ localID: item.localID,+ isLivePhoto: item.isLivePhoto,+ fileName: item.fileName,+ fileType: potentialFileTypeFromExtension(item.fileName) ?? -1,+ collectionID: item.collectionID,+ uploadItem: item.uploadItem!,+ pathPrefix: item.pathPrefix,+ }));+ items+ .sort((f, g) => {+ const cmp = nameAndExtension(f.fileName)[0].localeCompare(+ nameAndExtension(g.fileName)[0],+ );+ return cmp == 0 ? f.fileType - g.fileType : cmp;+ })+ .sort((f, g) => f.collectionID - g.collectionID);+ let index = 0;+ while (index < items.length - 1) {+ const fa = items[index]!;+ const ga = items[index + 1]!;+ if (await areLivePhotoAssets(fa, ga, parsedMetadataJSONMap)) {+ const [image, video] =+ fa.fileType == FileType.image ? [fa, ga] : [ga, fa];+ result.push({+ localID: fa.localID,+ collectionID: fa.collectionID,+ fileName: image.fileName,+ isLivePhoto: true,+ pathPrefix: image.pathPrefix,+ livePhotoAssets: {+ image: image.uploadItem,+ video: video.uploadItem,+ },+ });+ index += 2;+ } else {+ // They may already be a live photo (we might be retrying a+ // previously failed upload).+ result.push({ ...fa, isLivePhoto: fa.isLivePhoto ?? false });+ index += 1;+ }+ }+ if (index == items.length - 1) {+ const f = items[index]!;+ result.push({ ...f, isLivePhoto: f.isLivePhoto ?? false });+ }+ return result;+};++/**+ * Add logs if our usage increases some high water mark. This is solely so that+ * we have some indication in the logs if we get a user report of OOM crashes.+ */+const logAboutMemoryPressureIfNeeded = () => {+ if (!globalThis.electron) return;++ // performance.memory is deprecated in general as a Web standard, and is+ // also not available in the DOM types provided by TypeScript. However, it+ // is the method recommended by the Electron team (see the link about the V8+ // memory cage). The embedded Chromium supports it fine though, we just need+ // to goad TypeScript to accept the type.++ const { memory } = performance as unknown as {+ memory: { totalJSHeapSize: number; jsHeapSizeLimit: number };+ };++ const heapSize = memory.totalJSHeapSize;+ const heapLimit = memory.jsHeapSizeLimit;+ if (heapSize / heapLimit > 0.7) {+ log.info(+ `Memory usage (${heapSize} bytes of ${heapLimit} bytes) exceeds the high water mark`,+ );+ }+};diff --git a/web/apps/albums/vendor/photos/services/watch.ts b/web/apps/albums/vendor/photos/services/watch.tsnew file mode 100644index 0000000000..62d57b63d7--- /dev/null+++ b/web/apps/albums/vendor/photos/services/watch.ts@@ -0,0 +1,753 @@+/**+ * @file Interface with the Node.js layer of our desktop app to provide the+ * watch folders functionality.+ */++import debounce from "debounce";+import { ensureElectron } from "ente-base/electron";+import { basename, dirname, lowercaseExtension } from "ente-base/file-name";+import log from "ente-base/log";+import type {+ CollectionMapping,+ FolderWatch,+ FolderWatchSyncedFile,+} from "ente-base/types/ipc";+import { type UploadResult } from "ente-gallery/services/upload";+import type { UploadAsset } from "ente-gallery/services/upload/upload-service";+import { groupFilesByCollectionID } from "ente-gallery/utils/file";+import type { EnteFile } from "ente-media/file";+import { removeFromOwnCollection } from "ente-new/photos/services/collection";+import { computeAllCollectionFilesFromSaved } from "ente-new/photos/services/file";+import { ensureString } from "ente-utils/ensure";+import { type UploadItemWithCollection, uploadManager } from "./upload-manager";++/**+ * Watch for file system folders and automatically update the corresponding Ente+ * collections.+ *+ * This class relies on APIs exposed over the Electron IPC layer, and thus only+ * works when we're running inside our desktop app.+ */+class FolderWatcher {+ /** Pending file system events that we need to process. */+ private eventQueue: WatchEvent[] = [];+ /** The folder watch whose event we're currently processing */+ private activeWatch: FolderWatch | undefined;+ /**+ * If the file system directory corresponding to the (root) folder path of a+ * folder watch is deleted on disk, we note down that in this queue so that+ * we can ignore any file system events that come for it next.+ */+ private deletedFolderPaths: string[] = [];+ /**+ * A set of folder paths that were inaccessible in the last accessibility+ * check. Used to detect when a folder transitions from inaccessible to+ * accessible (e.g., when an external drive is reconnected).+ */+ private previouslyInaccessiblePaths = new Set<string>();+ /** `true` if we are using the uploader. */+ private uploadRunning = false;+ /** `true` if we are temporarily paused to let a user upload go through. */+ private isPaused = false;+ /**+ * A map from file paths to the (fileID, collectionID) of the file that was+ * uploaded (or symlinked) as part of the most recent upload attempt.+ */+ private uploadedFileForPath = new Map<string, EnteFile>();+ /**+ * A set of file paths that could not be uploaded in the most recent upload+ * attempt. These are the uploads that failed due to a permanent error that+ * a retry will not fix.+ */+ private unUploadableFilePaths = new Set<string>();++ /**+ * A function to call when we want to enqueue a new upload of the given list+ * of file paths to the given Ente collection.+ *+ * This is passed as a param to {@link init}.+ */+ private upload:+ | ((collectionName: string, filePaths: string[]) => void)+ | undefined;+ /**+ * A function to call when we want to trigger a full remote pull. It will+ * initiate the pull but will not await its completion.+ *+ * This is passed as a param to {@link init}.+ */+ private onTriggerRemotePull: (() => void) | undefined;++ /** A helper function that debounces invocations of {@link runNextEvent}. */+ private debouncedRunNextEvent: () => void;++ constructor() {+ // TODO:+ // eslint-disable-next-line @typescript-eslint/no-misused-promises+ this.debouncedRunNextEvent = debounce(() => this.runNextEvent(), 1000);+ }++ /**+ * Initialize the watcher and start processing file system events.+ *+ * This is only called when we're running in the context of our desktop app.+ *+ * The caller provides us with the hooks we can use to actually upload the+ * files, and to pull the latest changes from remote (say after deletion).+ */+ init(+ upload: (collectionName: string, filePaths: string[]) => void,+ onTriggerRemotePull: () => void,+ ) {+ this.upload = upload;+ this.onTriggerRemotePull = onTriggerRemotePull;+ this.registerListeners();+ this.initializeAccessibilityState();+ this.triggerSyncWithDisk();+ }++ /**+ * Initialize the accessibility tracking state by capturing which watches+ * are currently inaccessible. This allows subsequent checkAccessibility+ * calls to detect when a folder transitions from inaccessible to accessible.+ */+ private initializeAccessibilityState() {+ void this.getWatches().then((watches) => {+ for (const watch of watches) {+ if (watch.isAccessible === false) {+ this.previouslyInaccessiblePaths.add(watch.folderPath);+ }+ }+ if (this.previouslyInaccessiblePaths.size > 0) {+ log.info(+ `Folder watch: ${this.previouslyInaccessiblePaths.size} folder(s) currently inaccessible`,+ );+ }+ });+ }++ /** Return `true` if we are currently using the uploader. */+ isUploadRunning() {+ return this.uploadRunning;+ }++ /** Return `true` if syncing has been temporarily paused. */+ isSyncPaused() {+ return this.isPaused;+ }++ /**+ * Temporarily pause syncing and cancel any running uploads.+ *+ * This frees up the uploader for handling user initiated uploads.+ */+ pauseRunningSync() {+ this.isPaused = true;+ uploadManager.cancelRunningUpload();+ }++ /**+ * Resume from a temporary pause, resyncing from disk.+ *+ * Sibling of {@link pauseRunningSync}.+ */+ resumePausedSync() {+ this.isPaused = false;+ this.triggerSyncWithDisk();+ }++ /** Return the list of folders we are watching for changes. */+ async getWatches(): Promise<FolderWatch[]> {+ return await ensureElectron().watch.get();+ }++ /**+ * Check accessibility of all watch folders and trigger sync if any+ * previously inaccessible folder has become accessible.+ *+ * This is meant to be called when the app gains focus, allowing us to+ * detect when an external drive has been reconnected.+ */+ async checkAccessibility(): Promise<void> {+ try {+ const watches = await this.getWatches();++ // Determine which folders are currently inaccessible.+ const currentlyInaccessiblePaths = new Set<string>();+ for (const watch of watches) {+ if (watch.isAccessible === false) {+ currentlyInaccessiblePaths.add(watch.folderPath);+ }+ }++ // Check if any previously inaccessible folder is now accessible.+ const newlyAccessiblePaths: string[] = [];+ for (const path of this.previouslyInaccessiblePaths) {+ if (!currentlyInaccessiblePaths.has(path)) {+ // This folder was inaccessible before but is no longer in+ // the inaccessible set. Check if the watch still exists.+ const watchStillExists = watches.some(+ (w) => w.folderPath === path,+ );+ if (watchStillExists) {+ newlyAccessiblePaths.push(path);+ }+ }+ }++ // Update our tracking of inaccessible paths for the next check.+ this.previouslyInaccessiblePaths = currentlyInaccessiblePaths;++ // Only trigger sync if at least one folder became accessible.+ if (newlyAccessiblePaths.length > 0 && !this.isPaused) {+ log.info(+ `Folder watch: ${newlyAccessiblePaths.length} folder(s) became accessible (${newlyAccessiblePaths.join(", ")}), triggering sync`,+ );+ this.triggerSyncWithDisk();+ }+ } catch (e) {+ log.error("Error checking watch folder accessibility", e);+ }+ }++ /**+ * Return true if we are currently syncing files that belong to the given+ * {@link folderPath}.+ */+ isSyncingFolder(folderPath: string) {+ return this.activeWatch?.folderPath == folderPath;+ }++ /**+ * Add a new folder watch for the given root {@link folderPath}+ *+ * @param mapping The {@link CollectionMapping} to use to decide which+ * collection do files belonging to nested directories go to.+ *+ * @returns The updated list of watches.+ */+ async addWatch(folderPath: string, mapping: CollectionMapping) {+ const watches = await ensureElectron().watch.add(folderPath, mapping);+ this.triggerSyncWithDisk();+ return watches;+ }++ /**+ * Remove the folder watch for the given root {@link folderPath}.+ *+ * @returns The updated list of watches.+ */+ async removeWatch(folderPath: string) {+ return await ensureElectron().watch.remove(folderPath);+ }++ private triggerSyncWithDisk() {+ void this.syncWithDisk();+ }++ private async syncWithDisk() {+ try {+ const watches = await this.getWatches();++ this.eventQueue = [];+ const events = await deduceEvents(watches);+ log.info(`Folder watch deduced ${events.length} events`);+ this.eventQueue = this.eventQueue.concat(events);++ this.debouncedRunNextEvent();+ } catch (e) {+ log.error("Ignoring error while syncing watched folders", e);+ }+ }++ pushEvent(event: WatchEvent) {+ this.eventQueue.push(event);+ log.info("Folder watch event", event);+ this.debouncedRunNextEvent();+ }++ private registerListeners() {+ const watch = ensureElectron().watch;++ // [Note: File renames during folder watch]+ //+ // Renames come as two file system events - an `onAddFile` + an+ // `onRemoveFile` - in an arbitrary order.++ watch.onAddFile((path: string, watch: FolderWatch) => {+ this.pushEvent({+ action: "upload",+ collectionName: collectionNameForPath(path, watch),+ folderPath: watch.folderPath,+ filePath: path,+ });+ });++ watch.onRemoveFile((path: string, watch: FolderWatch) => {+ this.pushEvent({+ action: "trash",+ collectionName: collectionNameForPath(path, watch),+ folderPath: watch.folderPath,+ filePath: path,+ });+ });++ watch.onRemoveDir((path: string, watch: FolderWatch) => {+ if (path == watch.folderPath) {+ log.info(+ `Received file system delete event for a watched folder at ${path}`,+ );+ this.deletedFolderPaths.push(path);+ }+ });+ }++ private async runNextEvent() {+ if (this.eventQueue.length == 0 || this.activeWatch || this.isPaused)+ return;++ const event = this.dequeueClubbedEvent();+ if (!event) return;+ log.info(+ `Processing ${event.action} event for folder watch ${event.folderPath} (collectionName ${event.collectionName}, ${event.filePaths.length} files)`,+ );++ const skip = (reason: string) => {+ log.info(`Ignoring event since ${reason}`);+ this.debouncedRunNextEvent();+ };++ const watch = (await this.getWatches()).find(+ (watch) => watch.folderPath == event.folderPath,+ );+ if (!watch) {+ // Possibly stale+ skip(`no folder watch for found for ${event.folderPath}`);+ return;+ }++ if (watch.isAccessible === false) {+ skip(`folder ${event.folderPath} is inaccessible`);+ return;+ }++ if (event.action == "upload") {+ const paths = pathsToUpload(event.filePaths, watch);+ if (paths.length == 0) {+ skip("none of the files need uploading");+ return;+ }++ // Here we pass control to the uploader. When the upload is done,+ // the uploader will notify us by calling allFileUploadsDone.++ this.activeWatch = watch;+ this.uploadRunning = true;++ const collectionName = event.collectionName;+ log.info(+ `Folder watch requested upload of ${paths.length} files to collection ${collectionName}`,+ );++ this.upload!(collectionName, paths);+ } else {+ if (this.pruneFileEventsFromDeletedFolderPaths()) {+ skip("event was from a deleted folder path");+ return;+ }++ const [removed, rest] = watch.syncedFiles.reduce(+ ([removed, rest], syncedFile) => {+ (event.filePaths.includes(syncedFile.path)+ ? removed+ : rest+ ).push(syncedFile);+ return [removed, rest];+ },+ [new Array<FolderWatchSyncedFile>(), []],+ );++ this.activeWatch = watch;++ try {+ await this.moveToTrash(removed);+ } catch (e) {+ log.error(+ "Failed to trash files from watch folder, clearing stale sync entries",+ e,+ );+ }++ // Always update syncedFiles to remove stale entries, even if+ // trashing failed. Otherwise we'll keep retrying forever.+ await ensureElectron().watch.updateSyncedFiles(+ rest,+ watch.folderPath,+ );++ this.activeWatch = undefined;++ this.debouncedRunNextEvent();+ }+ }++ /**+ * Batch the next run of events with the same action, collection and folder+ * path into a single clubbed event that contains the list of all effected+ * file paths from the individual events.+ */+ private dequeueClubbedEvent(): ClubbedWatchEvent | undefined {+ const event = this.eventQueue.shift();+ if (!event) return undefined;++ const filePaths = [event.filePath];+ while (+ this.eventQueue.length > 0 &&+ event.action === this.eventQueue[0]?.action &&+ event.folderPath === this.eventQueue[0].folderPath &&+ event.collectionName === this.eventQueue[0].collectionName+ ) {+ filePaths.push(this.eventQueue[0].filePath);+ this.eventQueue.shift();+ }+ return { ...event, filePaths };+ }++ /**+ * Callback invoked by the uploader whenever a item we requested to+ * {@link upload} gets uploaded.+ */+ onFileUpload(item: UploadItemWithCollection, uploadResult: UploadResult) {+ // Re the usage of ensureString: For desktop watch, the only possibility+ // for a UploadItem is for it to be a string (the absolute path to a+ // file on disk).+ switch (uploadResult.type) {+ case "alreadyUploaded":+ case "addedSymlink":+ case "uploaded":+ case "uploadedWithStaticThumbnail":+ {+ // Done.+ if (item.isLivePhoto) {+ this.uploadedFileForPath.set(+ ensureString(item.livePhotoAssets?.image),+ uploadResult.file,+ );+ this.uploadedFileForPath.set(+ ensureString(item.livePhotoAssets?.video),+ uploadResult.file,+ );+ } else {+ this.uploadedFileForPath.set(+ ensureString(item.uploadItem),+ uploadResult.file,+ );+ }+ }+ break;+ case "unsupported":+ case "tooLarge":+ {+ // Non-retriable error.+ if (item.isLivePhoto) {+ this.unUploadableFilePaths.add(+ ensureString(item.livePhotoAssets?.image),+ );+ this.unUploadableFilePaths.add(+ ensureString(item.livePhotoAssets?.video),+ );+ } else {+ this.unUploadableFilePaths.add(+ ensureString(item.uploadItem),+ );+ }+ }+ break;+ }+ }++ /**+ * Callback invoked by the uploader whenever all the files we requested to+ * {@link upload} get uploaded.+ */+ async allFileUploadsDone(uploadedItems: UploadAsset[]) {+ const electron = ensureElectron();+ const watch = this.activeWatch!;++ log.debug(() => [+ "watch/allFileUploadsDone",+ JSON.stringify({ uploadedItems, watch }),+ ]);++ const { syncedFiles, ignoredFiles } =+ this.deduceSyncedAndIgnored(uploadedItems);++ if (syncedFiles.length > 0)+ await electron.watch.updateSyncedFiles(+ watch.syncedFiles.concat(syncedFiles),+ watch.folderPath,+ );++ if (ignoredFiles.length > 0)+ await electron.watch.updateIgnoredFiles(+ watch.ignoredFiles.concat(ignoredFiles),+ watch.folderPath,+ );++ this.activeWatch = undefined;+ this.uploadRunning = false;++ this.debouncedRunNextEvent();+ }++ private deduceSyncedAndIgnored(uploadedItems: UploadAsset[]) {+ const syncedFiles: FolderWatch["syncedFiles"] = [];+ const ignoredFiles: FolderWatch["ignoredFiles"] = [];++ const markSynced = (file: EnteFile, path: string) => {+ syncedFiles.push({+ path,+ uploadedFileID: file.id,+ collectionID: file.collectionID,+ });+ this.uploadedFileForPath.delete(path);+ };++ const markIgnored = (path: string) => {+ log.debug(() => `Permanently ignoring file at ${path}`);+ ignoredFiles.push(path);+ this.unUploadableFilePaths.delete(path);+ };++ for (const item of uploadedItems) {+ // Re the usage of ensureString: For desktop watch, the only+ // possibility for a UploadItem is for it to be a string (the+ // absolute path to a file on disk).+ if (item.isLivePhoto) {+ const imagePath = ensureString(item.livePhotoAssets?.image);+ const videoPath = ensureString(item.livePhotoAssets?.video);++ const imageFile = this.uploadedFileForPath.get(imagePath);+ const videoFile = this.uploadedFileForPath.get(videoPath);++ if (imageFile && videoFile) {+ markSynced(imageFile, imagePath);+ markSynced(videoFile, videoPath);+ } else if (+ this.unUploadableFilePaths.has(imagePath) &&+ this.unUploadableFilePaths.has(videoPath)+ ) {+ markIgnored(imagePath);+ markIgnored(videoPath);+ }+ } else {+ const path = ensureString(item.uploadItem);+ const file = this.uploadedFileForPath.get(path);+ if (file) {+ markSynced(file, path);+ } else if (this.unUploadableFilePaths.has(path)) {+ markIgnored(path);+ }+ }+ }++ return { syncedFiles, ignoredFiles };+ }++ private pruneFileEventsFromDeletedFolderPaths() {+ const deletedFolderPath = this.deletedFolderPaths.shift();+ if (!deletedFolderPath) return false;++ this.eventQueue = this.eventQueue.filter(+ (event) => !event.filePath.startsWith(deletedFolderPath),+ );++ return true;+ }++ private async moveToTrash(syncedFiles: FolderWatch["syncedFiles"]) {+ const syncedFileForID = new Map<number, FolderWatchSyncedFile>();+ for (const file of syncedFiles)+ syncedFileForID.set(file.uploadedFileID, file);++ // Use all collection files (including hidden) so that files removed+ // from the watch folder are also removed from hidden albums.+ const files = await computeAllCollectionFilesFromSaved();+ const filesToTrash = files.filter((file) => {+ const correspondingSyncedFile = syncedFileForID.get(file.id);+ if (+ correspondingSyncedFile &&+ correspondingSyncedFile.collectionID == file.collectionID+ ) {+ return true;+ }+ return false;+ });++ const filesByCollectionID = groupFilesByCollectionID(filesToTrash);+ for (const [id, files] of filesByCollectionID.entries()) {+ await removeFromOwnCollection(id, files);+ }++ this.onTriggerRemotePull!();+ }+}++/** The singleton instance of {@link FolderWatcher}. */+const watcher = new FolderWatcher();++export default watcher;++/**+ * A file system watch event encapsulates a change that has occurred on disk+ * that needs us to take some action within Ente to synchronize with the user's+ * Ente collections.+ *+ * Events get added in two ways:+ *+ * - When the app starts, it reads the current state of files on disk and+ * compares that with its last known state to determine what all events it+ * missed. This is easier than it sounds as we have only two events: add and+ * remove.+ *+ * - When the app is running, it gets live notifications from our file system+ * watcher (from the Node.js layer) about changes that have happened on disk,+ * which the app then enqueues onto the event queue if they pertain to the+ * files we're interested in.+ */+interface WatchEvent {+ /** The action to take */+ action: "upload" | "trash";+ /** The path of the root folder corresponding to the {@link FolderWatch}. */+ folderPath: string;+ /** The name of the Ente collection the file belongs to. */+ collectionName: string;+ /** The absolute path to the file under consideration. */+ filePath: string;+}++/**+ * A composite of multiple {@link WatchEvent}s that only differ in their+ * {@link filePath}.+ *+ * When processing events, we combine a run of events with the same+ * {@link action}, {@link folderPath} and {@link collectionName}. This allows us+ * to process all the affected {@link filePaths} in one shot.+ */+type ClubbedWatchEvent = Omit<WatchEvent, "filePath"> & { filePaths: string[] };++/**+ * Determine which events we need to process to synchronize the watched on-disk+ * folders to their corresponding collections.+ */+const deduceEvents = async (watches: FolderWatch[]): Promise<WatchEvent[]> => {+ const electron = ensureElectron();+ const events: WatchEvent[] = [];++ for (const watch of watches) {+ // Skip inaccessible folders (e.g., ejected external drives).+ if (watch.isAccessible === false) {+ log.info(+ `Skipping sync for inaccessible folder ${watch.folderPath}`,+ );+ continue;+ }++ const folderPath = watch.folderPath;++ const filePaths = await electron.fs.findFiles(folderPath);++ // Files that are on disk but not yet synced.+ for (const filePath of pathsToUpload(filePaths, watch))+ events.push({+ action: "upload",+ folderPath,+ collectionName: collectionNameForPath(filePath, watch),+ filePath,+ });++ // Previously synced files that are no longer on disk.+ for (const filePath of pathsToRemove(filePaths, watch))+ events.push({+ action: "trash",+ folderPath,+ collectionName: collectionNameForPath(filePath, watch),+ filePath,+ });+ }++ return events;+};++/**+ * Filter out hidden files, non-media files, and previously synced or ignored+ * paths from {@link paths} to get the list of paths that need to be uploaded+ * to the Ente collection.+ */+const pathsToUpload = (paths: string[], watch: FolderWatch) =>+ paths+ // Filter out files whose names begins with a dot.+ .filter((path) => !basename(path).startsWith("."))+ // Filter out known non-media files.+ .filter((path) => !shouldIgnoreForUpload(path))+ // Files that are on disk but not yet synced or ignored.+ .filter((path) => !isSyncedOrIgnoredPath(path, watch));++/**+ * Return the paths to previously synced files that are no longer on disk and so+ * must be removed from the Ente collection.+ */+const pathsToRemove = (paths: string[], watch: FolderWatch) =>+ watch.syncedFiles+ .map((f) => f.path)+ .filter((path) => !paths.includes(path));++const isSyncedOrIgnoredPath = (path: string, watch: FolderWatch) =>+ watch.ignoredFiles.includes(path) ||+ watch.syncedFiles.find((f) => f.path === path);++const collectionNameForPath = (path: string, watch: FolderWatch) =>+ watch.collectionMapping == "root"+ ? basename(watch.folderPath)+ : parentDirectoryName(path);++const parentDirectoryName = (path: string) => basename(dirname(path));++/**+ * Extensions of files that should not be uploaded from watch folders.+ *+ * These are common non-media file types that might be present in directories+ * containing photos and videos, but are not themselves media files.+ */+const ignoredExtensions = new Set([+ "zip",+ "rar",+ "7z",+ "tar",+ "gz",+ "bz2",+ "txt",+ "ini",+ "sfv",+ "md5",+ "sha1",+ "sha256",+ "sha512",+ "sha",+ "html",+ "htm",+ "xmp",+ "db",+]);++/**+ * Return `true` if the file at the given path should be ignored for uploads.+ *+ * This is used to filter out known non-media files from watch folders before+ * attempting to upload them. This prevents spurious "Skipped" messages and+ * error logs for files that we know beforehand are not photos or videos.+ */+const shouldIgnoreForUpload = (path: string): boolean => {+ const extension = lowercaseExtension(path);+ return extension !== undefined && ignoredExtensions.has(extension);+};diff --git a/web/apps/albums/vendor/photos/styles/global.css b/web/apps/albums/vendor/photos/styles/global.cssnew file mode 100644index 0000000000..1d8a983599--- /dev/null+++ b/web/apps/albums/vendor/photos/styles/global.css@@ -0,0 +1,14 @@+html,+body {+ height: 100%;+ flex: 1;+ display: flex;+ flex-direction: column;+}++#__next {+ flex: 1;+ display: flex;+ flex-direction: column;+ height: 100%;+}diff --git a/web/apps/albums/vendor/photos/styles/photoswipe.css b/web/apps/albums/vendor/photos/styles/photoswipe.cssnew file mode 100644index 0000000000..6ca38ba76c--- /dev/null+++ b/web/apps/albums/vendor/photos/styles/photoswipe.css@@ -0,0 +1,670 @@+.pswp-ente {+ /* The default z-index for PhotoSwipe is 10k, way beyond everything else.+ Give it a more moderate value so that MUI elements can be used with it. */+ z-index: calc(var(--mui-zIndex-drawer) - 1);+}++/* Shift the top bar by a fraction of the desktop title bar, if any. The top bar+ contents already have a decent top padding, so we don't need to shift by the+ entire amount. See also: [Note: Customize the desktop title bar] */+.pswp-ente .pswp__top-bar {+ top: calc(env(titlebar-area-height, 0px) * 0.4);+}++@media (width >= 450px) {+ .pswp-ente .pswp__top-bar {+ padding-top: 24px;+ }+}++/* Black gradient overlay at the top */+.pswp-ente .pswp__top-bar::before {+ content: "";+ position: absolute;+ /* Offset to start at the actual viewport top despite top-bar being shifted+ down for the desktop title bar. See line 10-12. */+ top: calc(env(titlebar-area-height, 0px) * -0.4);+ left: 0;+ right: 0;+ height: calc(125px + env(titlebar-area-height, 0px) * 0.4);+ background: linear-gradient(+ to top,+ transparent 0%,+ rgb(0 0 0 / 0.05) 20%,+ rgb(0 0 0 / 0.15) 40%,+ rgb(0 0 0 / 0.3) 60%,+ rgb(0 0 0 / 0.45) 80%,+ rgb(0 0 0 / 0.6) 100%+ );+ pointer-events: none;+ z-index: -1;+}++/* The PhotoSwipe CSS already disables and re-enables pointer-events for hidden+ UI elements, but for a reason that I didn't investigate more, that isn't+ working, and the hidden buttons still remain clickable.++ As a workaround, repeat the CSS, but with a higher specificity by including+ the button selector */++.pswp .pswp__hide-on-close button {+ pointer-events: none;+}++.pswp--ui-visible .pswp__hide-on-close button {+ pointer-events: auto;+}++/* Tweak the visual look of the preloader to match the rest of the elements */++.pswp-ente .pswp__preloader--active .pswp__icn {+ opacity: 0.4;+}++/*+ Error indicator on the file viewer.++ It is styled similar to the loading indicator provided by PhotoSwipe since it+ is meant to occupy the same space. Only one of these will be shown at the same+ time, so it can also set the auto right margin.+ */+.pswp-ente .pswp__error {+ position: relative;+ overflow: hidden;+ width: 50px;+ height: 60px;+ /* Unlike the loading indicator, "display" is used to toggle visibility, and+ the opacity is fixed to be similar to that of the counter. */+ display: none;+ opacity: 0.85;+}++.pswp-ente .pswp__error .pswp__icn {+ /* Use a warning color for the error icon */+ fill: var(--mui-palette-fixed-golden);+}++.pswp-ente .pswp__error .pswp__icn-shadow {+ /* Reduce the stroke from default (2px) to make it look better with the+ golden icon outline */+ stroke-width: 1px;+}++/* The ".pswp--ui-visible .pswp__hide-on-close" selector in PhotoSwipe's CSS+ sets the opacity of the arrows to 1, which doesn't match the rest of the+ controls (0.85). */+.pswp-ente.pswp--ui-visible .pswp__hide-on-close.pswp__button--arrow {+ opacity: 0.85;+}++.pswp-ente .pswp__error--active {+ display: initial;+}++/* Transform the built in controls to better fit our requirements */++.pswp-ente .pswp__counter {+ margin-top: 22.5px;+ margin-inline-start: 18px;+ margin-inline-end: 9px;+ line-height: 20px;+}++.pswp-ente-public-album .pswp__button--ente-logo {+ display: none;+}++@media (width >= 450px) {+ .pswp-ente .pswp__counter {+ margin-top: 22px;+ margin-inline-start: 44px;+ }+}++.pswp-ente .pswp__button--zoom .pswp__icn {+ top: 16px;+ transform: scale(0.85);+}++/* When counter is hidden (single photo), give zoom button the left margin */+.pswp-ente.pswp--one-slide .pswp__top-bar .pswp__button--zoom {+ margin-left: 4px;+}++@media (width >= 450px) {+ .pswp-ente.pswp--one-slide .pswp__top-bar .pswp__button--zoom {+ margin-left: 28px;+ }+}++.pswp-ente .pswp__preloader {+ transform: translate(-2px, 2px);+}++.pswp-ente .pswp__error {+ transform: translate(-2px, 2px);+}++.pswp-ente .pswp__button--close .pswp__icn {+ transform: translate(-6px, 0) scale(0.925);+}++.pswp-ente .pswp__button--close {+ margin-right: 2px;+}++/* Remove black strokes from top bar icons */+.pswp-ente .pswp__top-bar .pswp__icn-shadow {+ stroke-width: 0;+}++@media (width >= 450px) {+ .pswp-ente .pswp__top-bar .pswp__button {+ margin-left: 8px;+ }++ .pswp-ente .pswp__button--close {+ margin-right: 20px;+ }+}++.pswp-ente .pswp__button--arrow--prev .pswp__icn {+ transform: scale(0.8);+}++.pswp-ente .pswp__button--arrow--next .pswp__icn {+ /* default is a horizontal flip, transform: scale(-1, 1); */+ transform: scale(-0.8, 0.8);+}++/* Toggleable live photo buttons */++.pswp-ente button.pswp-ente-off .pswp__icn {+ /* PhotoSwipe already uses the CSS opacity, so reduce the color's opacity */+ fill: rgb(255 255 255 / 0.6);+}++/* Make the controls fit the top bar on mobile sized screens */+@media (width < 450px) {+ .pswp-ente .pswp__button {+ width: 44px;+ }++ .pswp-ente .pswp__counter {+ margin-inline-start: 10px;+ margin-inline-end: 0;+ }++ .pswp-ente .pswp__button--close {+ margin-right: -2px;+ }++ .pswp-ente-public-album+ .pswp__top-bar+ .pswp__button:not(.pswp__button--ente-logo):not(.pswp__button--zoom) {+ margin-top: 1px;+ }++ .pswp-ente-public-album .pswp__counter,+ .pswp-ente-public-album .pswp__button--zoom {+ display: none;+ }++ .pswp-ente-public-album .pswp__button--ente-logo {+ display: flex;+ align-items: center;+ justify-content: center;+ margin-top: 21.5px;+ margin-inline-start: 4px;+ margin-inline-end: 0;+ width: auto;+ min-width: 0;+ padding-inline: 0;+ height: 20px;+ color: rgb(255 255 255 / 0.85);+ }++ .pswp-ente-public-album .pswp__button--ente-logo .pswp__ente-logo-svg {+ display: block;+ height: 15px;+ width: auto;+ }+}++@media (width < 350px) {+ .pswp-ente .pswp__button {+ width: 42px;+ }++ .pswp-ente .pswp__counter {+ margin-inline-start: 4px;+ }++ .pswp-ente .pswp__button--close {+ margin-right: -4px;+ }++ .pswp-ente-public-album .pswp__button--ente-logo {+ margin-inline-start: 2px;+ }+}++/* Caption styling */++.pswp-ente .pswp__caption {+ border-radius: 3px;+ /* Same opacity as the other controls. */+ color: rgb(255 255 255 / 0.85);+ max-width: 375px;+ max-height: 200px;+ p {+ margin: 12px 17px;+ /* 4 lines max, ellipsis on overflow. */+ word-break: break-word;+ overflow: hidden;+ text-overflow: ellipsis;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 4;+ line-clamp: 4;+ }+}++/* Desktop caption: max 40% width */+@media (width >= 450px) {+ .pswp-ente .pswp__caption {+ max-width: 40%;+ }+}++.pswp-ente .pswp__caption.ente-video {+ /* Add blur box background for videos since we hide the gradient overlay */+ background-color: rgb(0 0 0 / 0.2);+ backdrop-filter: blur(10px);+ border-radius: 16px;+ /* Since there is too much going on in this part of the screen now, also+ reduce the maximum number of lines for the caption. */+ p {+ -webkit-line-clamp: 2;+ line-clamp: 2;+ }+}++.pswp-ente .pswp__caption-more {+ color: white;+ text-decoration: underline;+ cursor: pointer;+}++/* When More link is present, don't use line-clamp since JS already truncated */+.pswp-ente .pswp__caption p:has(.pswp__caption-more) {+ display: block;+ -webkit-line-clamp: unset;+ line-clamp: unset;+}++/* Change the cursor on the thumbnail to the default arrow to indicate that it+ is not interactable (PhotoSwipe by default shows the zoom out icon). */+.pswp-ente .pswp__img {+ cursor: auto;+}++/*+ Make the controllable video elements we render as custom PhotoSwipe content+ take .pswp-ente up the entire container.+ */+.pswp-ente video[controls] {+ width: 100%;+ height: 100%;+}++/*+ I tried various ways to get media-controller to embed a normal video, but in+ all methods I kept getting a flickering at the edges on Chrome. My best guess+ is that it happens when the resolved size of the video is a fractional value.++ This is the current magic incantation that seems to get them to play without+ the video's frame jittering. Note that the streaming hls-video elements work+ fine without any workarounds, it is only the vanilla video elements that have+ this issue and necessitate this workaround. The downside is that clicking+ "outside" the video works for hls-video, but not for vanilla videos.+ */+.pswp-ente media-controller.ente-vanilla-video {+ width: 100%;+ height: 100%;++ video {+ width: calc(100% - 1px);+ height: calc(100% - 1px);+ }+}++/*+ Style the custom video controls we provide.++ The media-controller itself is center positioned (shrinking if needed) by+ PhotoSwipe using the width and height of the video that we provide to it.++ The controls are absolutely position at the bottom of the screen instead of+ being attached to the video.+ */+.pswp-ente .pswp__media-controls {+ display: none;+ position: absolute;+ bottom: 0px;+ left: 0px;+ right: 0px;++ background: linear-gradient(transparent, rgb(0 0 0 / 0.8));++ /* Similar to our other controls */+ --media-icon-color: rgb(255 255 255 / 0.8);+ /* NB: We don't reset the font-weight, so this'll be using 400 instead of+ the 500 we use elsewhere. See: [Note: Font weights].++ We don't reset it because on this screen the 400 looks better (for now).+ */+ --media-font-family: "Inter Variable", sans-serif;+ --media-control-background: transparent;+ --media-control-hover-background: rgb(255 255 255 / 0.12);+ /*+ Prevent menus from occluding clicks on other controls when hidden.++ [Note: Showing menus outside of media-controller]++ This is all very hacky. The standalone control example+ (https://media-chrome.mux.dev/examples/vanilla/standalone-controls.html),+ doesn't (as of now) include a menu, so it is possible this is just not+ supported. None of the media controller examples I could find show menus+ work for our specific scenario (the controls detached from the the media+ controller itself, and shown at the bottom of the screen).++ As such, a lot of undocumented and arbitrary tweaks are needed. This is a+ house of cards, and might fall when the media-chrome version is updated;+ on the other hand, they might also add better support for our scenario, in+ which case this should be possible straightforwardly.+ */+ --media-menu-hidden-max-height: 1px;+ --media-menu-max-height: 1000px;+}++/*+ Stack controls rows vertically.+ */+.pswp-ente .pswp__media-controls > div {+ display: flex;+ flex-direction: column;+}++/* Controls are shown in a disabled state while video data is still loading. */+.pswp-ente .pswp__media-controls.pswp__media-controls--visible {+ display: block;+}++.pswp-ente+ .pswp__media-controls.pswp__media-controls--disabled+ media-control-bar:not(:first-child),+.pswp-ente+ .pswp__media-controls.pswp__media-controls--disabled+ media-playback-rate-menu {+ opacity: 0.45;+ pointer-events: none;+}++media-control-bar {+ padding-inline: 12px;+}++media-control-bar:last-child {+ padding-block-end: 4px;+}++media-loading-indicator {+ /* Similar to the top bar loading indicator */+ --media-icon-color: rgb(255 255 255 / 0.6);+}++/* Used as a spacer. */+media-text-display {+ flex-grow: 1;+}++media-time-range {+ --media-range-bar-color: red;+ --media-range-thumb-background: var(--media-range-bar-color);+ --media-control-hover-background: transparent;+ --media-control-padding: 0px;+}++media-time-range:hover {+ --media-range-track-height: 5px;+ --media-range-thumb-transform: scale(1.1);+}++/*+ Hide specific controls when the user's browser doesn't support the feature+ they trigger.+ */+media-pip-button[mediapipunavailable],+media-fullscreen-button[mediafullscreenunavailable] {+ display: none;+}++media-settings-menu {+ /*+ Restore the background for the settings menu (we made it transparent). The+ default is var(--_menu-bg), which is rgb(20 20 30 / .8).+ */+ --media-control-background: var(--mui-palette-fixed-dark-background-paper);+ /* Regular, but since the rest of media controls use 400, it+ appears heavier. */+ --media-font-weight: 500;+ /*+ Bring it above the rest of our controls.++ See: [Note: Showing menus outside of media-controller]+ */+ z-index: 1;+}++/* Hide the bottom right controls when hovering over the video controls or+ when the settings menu is open. */+body:has(+ media-time-range[mediapreviewtime],+ media-settings-menu:not([hidden])+) {+ & .pswp-ente .pswp__bottom-right-controls {+ display: none;+ }+}++/*+ Video fullscreen mode styles.++ When entering fullscreen via the video controls, we hide the PhotoSwipe+ navigation UI (top bar, arrows) and only show the video controls at the+ bottom. The controls auto-hide and appear when the user moves to the bottom.+ */++/* Hide navigation controls in video fullscreen mode */+.pswp-ente.pswp--video-fullscreen .pswp__top-bar,+.pswp-ente.pswp--video-fullscreen .pswp__button--arrow {+ display: none !important;+}++/* Auto-hide video controls in fullscreen, show when mouse near bottom */+.pswp-ente.pswp--video-fullscreen .pswp__media-controls {+ opacity: 0;+ transition: opacity 0.3s ease;+}++/* Show controls when hovering or when settings menu is open */+.pswp-ente.pswp--video-fullscreen .pswp__media-controls:hover,+.pswp-ente.pswp--video-fullscreen:has(media-settings-menu:not([hidden]))+ .pswp__media-controls {+ opacity: 1;+}++/* JS adds this class when mouse is near bottom of screen */+.pswp-ente.pswp--video-fullscreen.pswp--controls-visible .pswp__media-controls {+ opacity: 1;+}++/* Also hide the bottom right controls in video fullscreen mode */+.pswp-ente.pswp--video-fullscreen .pswp__bottom-right-controls {+ display: none;+}++/* Bottom controls container (caption on left, action buttons on right on desktop) */+.pswp-ente .pswp__bottom-right-controls {+ position: absolute;+ bottom: 20px;+ right: 24px;+ display: flex;+ /* column-reverse to show buttons on top, caption below (matching original HTML order) */+ flex-direction: column-reverse;+ align-items: flex-end;+ gap: 12px;+}++/* Black gradient overlay at the bottom */+.pswp-ente .pswp__bottom-right-controls::before {+ content: "";+ position: absolute;+ bottom: -20px;+ left: -24px;+ right: -24px;+ height: 225px;+ background: linear-gradient(+ to bottom,+ transparent 0%,+ rgb(0 0 0 / 0.05) 20%,+ rgb(0 0 0 / 0.15) 40%,+ rgb(0 0 0 / 0.3) 60%,+ rgb(0 0 0 / 0.45) 80%,+ rgb(0 0 0 / 0.6) 100%+ );+ pointer-events: none;+ z-index: -1;+}++/* Row layout on desktop: caption on left, buttons on right */+@media (width >= 450px) {+ .pswp-ente .pswp__bottom-right-controls {+ bottom: 40px;+ left: 28px;+ right: 44px;+ flex-direction: row;+ align-items: flex-end;+ gap: 24px;+ }++ .pswp-ente .pswp__bottom-right-controls::before {+ bottom: -40px;+ left: -28px;+ right: -44px;+ }+}++/* Extra offset for video to clear video controls */+.pswp-ente .pswp__bottom-right-controls:has(.pswp__caption.ente-video) {+ bottom: 100px;+}++/* Hide gradient overlay for videos since they have their own controls gradient */+.pswp-ente .pswp__bottom-right-controls:has(.pswp__caption.ente-video)::before {+ display: none;+}++/* Hide gradient overlay when description is not present */+.pswp-ente+ .pswp__bottom-right-controls:has(+ .pswp__caption[style*="display: none"]+ )::before {+ display: none;+}++/* Action buttons row - margin-left: auto keeps them on the right when no caption */+.pswp-ente .pswp__action-buttons {+ display: flex;+ flex-direction: row;+ gap: 20px;+ margin-left: auto;+}++.pswp-ente .pswp__action-button {+ width: 56px;+ height: 56px;+ border-radius: 50%;+ background-color: rgb(0 0 0 / 0.6);+ border: 1px solid rgb(255 255 255 / 0.2);+ cursor: pointer;+ display: flex;+ align-items: center;+ justify-content: center;+ transition: background-color 0.2s ease;+}++.pswp-ente .pswp__action-button:hover {+ background-color: rgb(0 0 0 / 0.8);+}++.pswp-ente .pswp__action-button svg {+ width: 28px;+ height: 28px;+ fill: white;+}++/* Comment button with count indicator */+.pswp-ente .pswp__action-button--comment {+ position: relative;+}++.pswp-ente .pswp__comment-count {+ position: absolute;+ top: -6px;+ right: -6px;+ width: 24px;+ height: 24px;+ border-radius: 50%;+ background-color: #fff;+ color: #000;+ font-family: "Inter Variable", sans-serif;+ font-size: 12px;+ font-weight: 600;+ line-height: 24px;+ text-align: center;+ display: none;+}++.pswp-ente .pswp__comment-count:not(:empty) {+ display: block;+}++/* Reduce padding on mobile */+@media (width < 450px) {+ .pswp-ente .pswp__bottom-right-controls {+ bottom: 12px;+ left: 12px;+ right: 12px;+ }++ .pswp-ente .pswp__bottom-right-controls::before {+ bottom: -12px;+ left: -12px;+ right: -12px;+ }+}++/* Heart (like) button icons - uses pswp__hidden class toggled by showIf() */+#pswp__icn-heart-fill {+ display: none;+}++#pswp__icn-heart-fill:not(.pswp__hidden) {+ display: inline;+}++#pswp__icn-heart.pswp__hidden {+ display: none;+}diff --git a/web/apps/albums/vendor/photos/types/supercluster.d.ts b/web/apps/albums/vendor/photos/types/supercluster.d.tsnew file mode 100644index 0000000000..3a6d672fb6--- /dev/null+++ b/web/apps/albums/vendor/photos/types/supercluster.d.ts@@ -0,0 +1,87 @@+declare module "supercluster" {+ export type BBox = [number, number, number, number];++ export interface PointGeometry {+ type: "Point";+ coordinates: [number, number];+ }++ export interface PointFeature<TPointProperties = Record<string, unknown>> {+ type: "Feature";+ properties: TPointProperties;+ geometry: PointGeometry;+ }++ export interface ClusterProperties {+ cluster: true;+ cluster_id: number;+ point_count: number;+ point_count_abbreviated?: number | string;+ }++ export interface ClusterFeature<+ TClusterProperties = Record<string, unknown>,+ > {+ type: "Feature";+ properties: TClusterProperties & ClusterProperties;+ geometry: PointGeometry;+ }++ export type ClusterOrPoint<+ TPointProperties = Record<string, unknown>,+ TClusterProperties = Record<string, unknown>,+ > = PointFeature<TPointProperties> | ClusterFeature<TClusterProperties>;++ export interface SuperclusterOptions<+ TPointProperties = Record<string, unknown>,+ TClusterProperties = Record<string, unknown>,+ > {+ radius?: number;+ maxZoom?: number;+ minZoom?: number;+ minPoints?: number;+ extent?: number;+ nodeSize?: number;+ log?: boolean;+ generateId?: boolean;+ map?: (props: TPointProperties) => TClusterProperties;+ reduce?: (+ accumulated: TClusterProperties,+ props: TClusterProperties,+ ) => void;+ }++ export default class Supercluster<+ TPointProperties = Record<string, unknown>,+ TClusterProperties = Record<string, unknown>,+ > {+ constructor(+ options?: SuperclusterOptions<TPointProperties, TClusterProperties>,+ );+ load(points: PointFeature<TPointProperties>[]): this;+ getClusters(+ bbox: BBox,+ zoom: number,+ ): ClusterOrPoint<TPointProperties, TClusterProperties>[];+ getChildren(+ clusterId: number,+ ): ClusterOrPoint<TPointProperties, TClusterProperties>[];+ getLeaves(+ clusterId: number,+ limit: number,+ offset: number,+ ): PointFeature<TPointProperties>[];+ getClusterExpansionZoom(clusterId: number): number;+ getTile?(+ z: number,+ x: number,+ y: number,+ ): {+ features: {+ type: "Feature";+ geometry: { type: "Point"; coordinates: [number, number] };+ properties: Record<string, unknown>;+ }[];+ } | null;+ }+}diff --git a/web/apps/albums/vendor/photos/utils/file/index.ts b/web/apps/albums/vendor/photos/utils/file/index.tsnew file mode 100644index 0000000000..b1821fd676--- /dev/null+++ b/web/apps/albums/vendor/photos/utils/file/index.ts@@ -0,0 +1,111 @@+import type { AddSaveGroup } from "ente-gallery/components/utils/save-groups";+import { downloadAndSaveFiles } from "ente-gallery/services/save";+import type { EnteFile } from "ente-media/file";+import { fileFileName, ItemVisibility } from "ente-media/file-metadata";+import { FileType } from "ente-media/file-type";+import { type SelectionContext } from "ente-new/photos/components/gallery";+import { type FileOp } from "ente-new/photos/components/SelectedFileOptions";+import {+ addToFavoritesCollection,+ deleteFromTrash,+ hideFiles,+ moveToTrash,+ removeFromFavoritesCollection,+} from "ente-new/photos/services/collection";+import { updateFilesVisibility } from "ente-new/photos/services/file";+import { t } from "i18next";++export interface SelectedState {+ [k: number]: boolean;+ ownCount: number;+ count: number;+ collectionID: number | undefined;+ /**+ * The context in which the selection was made. Only set by newer code if+ * there is an active selection (older code continues to rely on the+ * {@link collectionID} logic).+ */+ context: SelectionContext | undefined;+}+export type SetSelectedState = React.Dispatch<+ React.SetStateAction<SelectedState>+>;++export function getSelectedFiles(+ selected: SelectedState,+ files: EnteFile[],+): EnteFile[] {+ const selectedFilesIDs = new Set<number>();+ for (const [key, val] of Object.entries(selected)) {+ if (typeof val == "boolean" && val) {+ selectedFilesIDs.add(Number(key));+ }+ }++ return files.filter((file) => selectedFilesIDs.has(file.id));+}++export const performFileOp = async (+ op: FileOp,+ files: EnteFile[],+ onAddSaveGroup: AddSaveGroup,+ markTempDeleted: (files: EnteFile[]) => void,+ clearTempDeleted: () => void,+ markTempHidden: (files: EnteFile[]) => void,+ clearTempHidden: () => void,+ fixCreationTime: (files: EnteFile[]) => void,+) => {+ switch (op) {+ case "download": {+ const singleFile = files.length === 1 ? files[0] : undefined;+ const title =+ singleFile?.metadata.fileType === FileType.livePhoto+ ? fileFileName(singleFile)+ : t("files_count", { count: files.length });+ await downloadAndSaveFiles(files, title, onAddSaveGroup);+ break;+ }+ case "fixTime":+ fixCreationTime(files);+ break;+ case "favorite":+ await addToFavoritesCollection(files);+ break;+ case "unfavorite":+ await removeFromFavoritesCollection(files);+ break;+ case "archive":+ await updateFilesVisibility(files, ItemVisibility.archived);+ break;+ case "unarchive":+ await updateFilesVisibility(files, ItemVisibility.visible);+ break;+ case "hide":+ try {+ markTempHidden(files);+ await hideFiles(files);+ } catch (e) {+ clearTempHidden();+ throw e;+ }+ break;+ case "trash":+ try {+ markTempDeleted(files);+ await moveToTrash(files);+ } catch (e) {+ clearTempDeleted();+ throw e;+ }+ break;+ case "deletePermanently":+ try {+ markTempDeleted(files);+ await deleteFromTrash(files.map((file) => file.id));+ } catch (e) {+ clearTempDeleted();+ throw e;+ }+ break;+ }+};diff --git a/web/apps/albums/vendor/photos/utils/photoFrame/index.ts b/web/apps/albums/vendor/photos/utils/photoFrame/index.tsnew file mode 100644index 0000000000..672c85d2b7--- /dev/null+++ b/web/apps/albums/vendor/photos/utils/photoFrame/index.ts@@ -0,0 +1,192 @@+// TODO: Audit this file+import type { SelectionContext } from "ente-new/photos/components/gallery";+import type { GalleryBarMode } from "ente-new/photos/components/gallery/reducer";+import type { SelectedState, SetSelectedState } from "utils/file";++// TODO: All this is unnecessarily complex, and needs reworking.+export const handleSelectCreator =+ (+ setSelected: SetSelectedState,+ mode: GalleryBarMode | undefined,+ userID: number | undefined,+ activeCollectionID: number,+ activePersonID: string | undefined,+ setRangeStartIndex: (index: number | undefined) => void,+ ) =>+ ({ id, ownerID }: { id: number; ownerID: number }, index?: number) =>+ (checked: boolean) => {+ if (typeof index != "undefined") {+ if (checked) {+ setRangeStartIndex(index);+ } else {+ setRangeStartIndex(undefined);+ }+ }+ setSelected((_selected) => {+ const { selected, newContext } = createSelectedAndContext(+ mode,+ activeCollectionID,+ activePersonID,+ _selected,+ );++ const handleCounterChange = (count: number) => {+ if (selected[id] === checked) {+ return count;+ }+ if (checked) {+ return count + 1;+ } else {+ return count - 1;+ }+ };++ const handleAllCounterChange = () => {+ if (ownerID === userID) {+ return {+ ownCount: handleCounterChange(selected.ownCount),+ count: handleCounterChange(selected.count),+ };+ } else {+ return { count: handleCounterChange(selected.count) };+ }+ };+ return {+ ...selected,+ [id]: checked,+ collectionID: activeCollectionID,+ context: newContext,+ ...handleAllCounterChange(),+ };+ });+ };++export const handleSelectCreatorMulti =+ (+ setSelected: SetSelectedState,+ mode: GalleryBarMode | undefined,+ userID: number | undefined,+ activeCollectionID: number,+ activePersonID: string | undefined,+ ) =>+ (files: { id: number; ownerID: number }[]) =>+ (checked: boolean) => {+ setSelected((_selected) => {+ const { selected, newContext } = createSelectedAndContext(+ mode,+ activeCollectionID,+ activePersonID,+ _selected,+ );++ const newSelected = { ...selected };+ let newCount = selected.count;+ let newOwnCount = selected.ownCount;++ if (checked) {+ for (const file of files) {+ if (!newSelected[file.id]) {+ newSelected[file.id] = true;+ newCount++;+ if (file.ownerID === userID) newOwnCount++;+ }+ }+ } else {+ for (const file of files) {+ if (newSelected[file.id]) {+ newSelected[file.id] = false;+ newCount--;+ if (file.ownerID === userID) newOwnCount--;+ }+ }+ }++ return {+ ...newSelected,+ count: newCount,+ ownCount: newOwnCount,+ collectionID: activeCollectionID,+ context: newContext,+ };+ });+ };++const createSelectedAndContext = (+ mode: GalleryBarMode | undefined,++ activeCollectionID: number,+ activePersonID: string | undefined,+ selected: SelectedState,+) => {+ if (!mode) {+ // Retain older behavior for non-gallery call sites.+ if (selected.collectionID !== activeCollectionID) {+ selected = {+ ownCount: 0,+ count: 0,+ collectionID: 0,+ context: undefined,+ };+ }+ } else if (!selected.context) {+ // Gallery will specify a mode, but a fresh selection starts off+ // without a context, so fill it in with the current context.+ selected = {+ ...selected,+ context:+ mode == "people"+ ? { mode, personID: activePersonID! }+ : { mode, collectionID: activeCollectionID },+ };+ } else {+ // Both mode and context are defined.+ if (selected.context.mode != mode) {+ // Clear selection if mode has changed.+ selected = {+ ownCount: 0,+ count: 0,+ collectionID: 0,+ context:+ mode == "people"+ ? { mode, personID: activePersonID! }+ : { mode, collectionID: activeCollectionID },+ };+ } else {+ if (selected.context.mode == "people") {+ if (selected.context.personID != activePersonID) {+ // Clear selection if person has changed.+ selected = {+ ownCount: 0,+ count: 0,+ collectionID: 0,+ context: {+ mode: selected.context.mode,+ personID: activePersonID!,+ },+ };+ }+ } else {+ if (selected.context.collectionID != activeCollectionID) {+ // Clear selection if collection has changed.+ selected = {+ ownCount: 0,+ count: 0,+ collectionID: 0,+ context: {+ mode: selected.context.mode,+ collectionID: activeCollectionID,+ },+ };+ }+ }+ }+ }++ const newContext: SelectionContext | undefined = !mode+ ? undefined+ : mode == "people"+ ? { mode, personID: activePersonID! }+ : { mode, collectionID: activeCollectionID };++ return { selected, newContext };+};diff --git a/web/apps/albums/vendor/photos/utils/public-album.ts b/web/apps/albums/vendor/photos/utils/public-album.tsnew file mode 100644index 0000000000..451538cf82--- /dev/null+++ b/web/apps/albums/vendor/photos/utils/public-album.ts@@ -0,0 +1,4 @@+/**+ * Get the destination URL for "Try Ente" actions in public albums.+ */+export const getEnteURL = (): string => "https://ente.io/get";diff --git a/web/apps/albums/vendor/photos/utils/quick-link.ts b/web/apps/albums/vendor/photos/utils/quick-link.tsnew file mode 100644index 0000000000..307ceb8541--- /dev/null+++ b/web/apps/albums/vendor/photos/utils/quick-link.ts@@ -0,0 +1,78 @@+import { appendCollectionKeyToShareURL } from "ente-gallery/services/share";+import type { EnteFile } from "ente-media/file";+import { fileCreationTime } from "ente-media/file-metadata";++const shortMonths = [+ "",+ "Jan",+ "Feb",+ "Mar",+ "Apr",+ "May",+ "Jun",+ "Jul",+ "Aug",+ "Sep",+ "Oct",+ "Nov",+ "Dec",+];++/**+ * Date-range formatting used by quick-link naming (kept in mobile parity).+ */+export const quickLinkDateRangeForCreationTimes = (+ firstCreationTime: number,+ secondCreationTime: number,+) => {+ const startTime = new Date(firstCreationTime / 1000);+ const endTime = new Date(secondCreationTime / 1000);++ if (startTime.getFullYear() != endTime.getFullYear()) {+ return `${shortMonths[startTime.getMonth() + 1]} ${startTime.getDate()}, ${startTime.getFullYear()} - ${shortMonths[endTime.getMonth() + 1]} ${endTime.getDate()}, ${endTime.getFullYear()}`;+ }+ if (startTime.getMonth() != endTime.getMonth()) {+ return `${shortMonths[startTime.getMonth() + 1]} ${startTime.getDate()} - ${shortMonths[endTime.getMonth() + 1]} ${endTime.getDate()}, ${endTime.getFullYear()}`;+ }+ if (startTime.getDate() != endTime.getDate()) {+ return `${shortMonths[startTime.getMonth() + 1]} ${startTime.getDate()} - ${shortMonths[endTime.getMonth() + 1]} ${endTime.getDate()}, ${endTime.getFullYear()}`;+ }+ return `${shortMonths[endTime.getMonth() + 1]} ${endTime.getDate()}, ${endTime.getFullYear()}`;+};++export const quickLinkDateRangeForFiles = (files: EnteFile[]) => {+ if (!files.length) return undefined;++ let minCreationTime = Number.POSITIVE_INFINITY;+ let maxCreationTime = Number.NEGATIVE_INFINITY;+ for (const file of files) {+ const creationTime = fileCreationTime(file);+ if (creationTime < minCreationTime) minCreationTime = creationTime;+ if (creationTime > maxCreationTime) maxCreationTime = creationTime;+ }++ return quickLinkDateRangeForCreationTimes(minCreationTime, maxCreationTime);+};++export const quickLinkNameForFiles = (files: EnteFile[]) =>+ quickLinkDateRangeForFiles(files) ?? "Quick link";++const substituteCustomDomainIfNeeded = (+ url: string,+ customDomain: string | undefined,+) => {+ if (!customDomain) return url;+ const u = new URL(url);+ u.host = customDomain;+ return u.href;+};++export const resolveQuickLinkURL = async (+ publicURL: string,+ collectionKey: string,+ customDomain: string | undefined,+) =>+ substituteCustomDomainIfNeeded(+ await appendCollectionKeyToShareURL(publicURL, collectionKey),+ customDomain,+ );diff --git a/web/apps/albums/vendor/photos/utils/upload/canvas-integrity.ts b/web/apps/albums/vendor/photos/utils/upload/canvas-integrity.tsnew file mode 100644index 0000000000..62f1bc23bb--- /dev/null+++ b/web/apps/albums/vendor/photos/utils/upload/canvas-integrity.ts@@ -0,0 +1,54 @@+const probeWidth = 2;+const probeHeight = 2;++const expectedProbeData = Uint8ClampedArray.from([+ 17, 83, 149, 255, 203, 29, 101, 255, 67, 131, 197, 255, 239, 53, 11, 255,+]);++const hasSamePixels = (+ lhs: Uint8ClampedArray,+ rhs: Uint8ClampedArray,+): boolean => {+ if (lhs.length !== rhs.length) return false;+ for (let i = 0; i < lhs.length; i++) {+ if (lhs[i] !== rhs[i]) return false;+ }+ return true;+};++export const hasReliableCanvasReadback = (): boolean => {+ try {+ const canvas = document.createElement("canvas");+ canvas.width = probeWidth;+ canvas.height = probeHeight;++ const ctx = canvas.getContext("2d", { willReadFrequently: true });+ if (!ctx) return false;++ const probeImageData = new ImageData(+ new Uint8ClampedArray(expectedProbeData),+ probeWidth,+ probeHeight,+ );+ ctx.putImageData(probeImageData, 0, 0);++ const firstReadback = ctx.getImageData(+ 0,+ 0,+ probeWidth,+ probeHeight,+ ).data;+ if (!hasSamePixels(firstReadback, expectedProbeData)) return false;++ const secondReadback = ctx.getImageData(+ 0,+ 0,+ probeWidth,+ probeHeight,+ ).data;++ return hasSamePixels(firstReadback, secondReadback);+ } catch {+ return false;+ }+};