Skip to content

armgit / ente

Public Imported from GitHub
0

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

Trim albums ente-base for public albums

Anand Baburajan9c7dc037442f
diff --git a/web/apps/albums/vendor/ente-base/app.ts b/web/apps/albums/vendor/ente-base/app.ts
index 0556caaca9..513f46a99e 100644
--- a/web/apps/albums/vendor/ente-base/app.ts
+++ b/web/apps/albums/vendor/ente-base/app.ts
@@ -10,121 +10,12 @@ export const appNames = [
"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;
-})();
+// This vendored copy only serves the public albums web app.
+export const appName: AppName = "albums";
+export const isDesktop = false;
+export const desktopAppVersion: string | undefined = undefined;
+export const staticAppTitle = "Ente Photos";
+export const clientPackageName = "io.ente.albums.web";
+export const clientIdentifier = clientPackageName;
diff --git a/web/apps/albums/vendor/ente-base/blob-cache.ts b/web/apps/albums/vendor/ente-base/blob-cache.ts
index c64ff317a4..c1b0b749a6 100644
--- a/web/apps/albums/vendor/ente-base/blob-cache.ts
+++ b/web/apps/albums/vendor/ente-base/blob-cache.ts
@@ -1,244 +1,43 @@
-import { isDesktop } from "./app";
+const blobCacheNames = ["thumbs"] as const;
-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;
+ let cache = cachedCaches.get(name);
+ if (!cache) {
+ cache = await openBlobCache(name);
+ cachedCaches.set(name, cache);
+ }
+ return cache;
};
-/**
- * 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) => {
+): Promise<BlobCache> => {
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),
+ has: async (key: string) => !!(await cache.match(key)),
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 });
+ await Promise.all(blobCacheNames.map((name) => caches.delete(name)));
};
diff --git a/web/apps/albums/vendor/ente-base/components/Head.tsx b/web/apps/albums/vendor/ente-base/components/Head.tsx
index 613ad6dcb0..15d9e07d6b 100644
--- a/web/apps/albums/vendor/ente-base/components/Head.tsx
+++ b/web/apps/albums/vendor/ente-base/components/Head.tsx
@@ -1,23 +1,12 @@
import Head from "next/head";
import React from "react";
import { haveWindow } from "../env";
-import {
- albumsAppOrigin,
- isCustomAlbumsAppOrigin,
- isCustomShareAppOrigin,
- shareAppOrigin,
-} from "../origins";
+import { albumsAppOrigin, isCustomAlbumsAppOrigin } 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>
@@ -31,21 +20,6 @@ export const CustomHead: React.FC<CustomHeadProps> = ({ title }) => (
</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>
@@ -58,7 +32,6 @@ export const CustomHeadAlbums: React.FC = () => (
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"
@@ -68,22 +41,6 @@ export const CustomHeadAlbums: React.FC = () => (
</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,
}) =>
@@ -94,48 +51,3 @@ export const CustomHeadPhotosOrAlbums: React.FC<CustomHeadProps> = ({
) : (
<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/OverflowMenu.tsx b/web/apps/albums/vendor/ente-base/components/OverflowMenu.tsx
deleted file mode 100644
index 9df36745b2..0000000000
--- a/web/apps/albums/vendor/ente-base/components/OverflowMenu.tsx
+++ /dev/null
@@ -1,199 +0,0 @@
-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/SingleInputDialog.tsx b/web/apps/albums/vendor/ente-base/components/SingleInputDialog.tsx
deleted file mode 100644
index 9a1cf64b69..0000000000
--- a/web/apps/albums/vendor/ente-base/components/SingleInputDialog.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-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/mui/SidebarDrawer.tsx b/web/apps/albums/vendor/ente-base/components/mui/SidebarDrawer.tsx
index 93862059e6..b7b0836ebe 100644
--- a/web/apps/albums/vendor/ente-base/components/mui/SidebarDrawer.tsx
+++ b/web/apps/albums/vendor/ente-base/components/mui/SidebarDrawer.tsx
@@ -5,24 +5,12 @@ import {
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,
@@ -37,61 +25,22 @@ export const SidebarDrawer: React.FC<DrawerProps> = ({
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();
@@ -101,22 +50,9 @@ export const NestedSidebarDrawer: React.FC<
}
};
- // 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" } } },
}}
@@ -130,21 +66,11 @@ 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,
@@ -181,15 +107,6 @@ export const SidebarDrawerTitlebar: React.FC<SidebarDrawerTitlebarProps> = ({
</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 &
diff --git a/web/apps/albums/vendor/ente-base/components/utils/theme.ts b/web/apps/albums/vendor/ente-base/components/utils/theme.ts
index 17f46cc8cc..6e8e620da0 100644
--- a/web/apps/albums/vendor/ente-base/components/utils/theme.ts
+++ b/web/apps/albums/vendor/ente-base/components/utils/theme.ts
@@ -1105,35 +1105,4 @@ const getComponents = (appName: AppName): Components => {
// 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/electron.ts b/web/apps/albums/vendor/ente-base/electron.ts
deleted file mode 100644
index 1bc6634445..0000000000
--- a/web/apps/albums/vendor/ente-base/electron.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-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/http.ts b/web/apps/albums/vendor/ente-base/http.ts
index d2942cb9ad..6d8489689b 100644
--- a/web/apps/albums/vendor/ente-base/http.ts
+++ b/web/apps/albums/vendor/ente-base/http.ts
@@ -1,4 +1,3 @@
-import { desktopAppVersion, isDesktop } from "ente-base/app";
import { wait } from "ente-utils/promise";
import { z } from "zod";
import { clientPackageName } from "./app";
@@ -15,7 +14,6 @@ import { ensureAuthToken } from "./token";
export const authenticatedRequestHeaders = async () => ({
"X-Auth-Token": await ensureAuthToken(),
"X-Client-Package": clientPackageName,
- ...(isDesktop && { "X-Client-Version": desktopAppVersion }),
});
/**
@@ -27,7 +25,6 @@ export const authenticatedRequestHeaders = async () => ({
*/
export const publicRequestHeaders = () => ({
"X-Client-Package": clientPackageName,
- ...(isDesktop && { "X-Client-Version": desktopAppVersion }),
});
/**
diff --git a/web/apps/albums/vendor/ente-base/id-worker.ts b/web/apps/albums/vendor/ente-base/id-worker.ts
deleted file mode 100644
index 593e2d236e..0000000000
--- a/web/apps/albums/vendor/ente-base/id-worker.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-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/log-web.ts b/web/apps/albums/vendor/ente-base/log-web.ts
index a87f8ccfc1..c500f58686 100644
--- a/web/apps/albums/vendor/ente-base/log-web.ts
+++ b/web/apps/albums/vendor/ente-base/log-web.ts
@@ -1,6 +1,6 @@
import { isDevBuild } from "ente-base/env";
import log from "ente-base/log";
-import { appName, appNames } from "./app";
+import { appName } from "./app";
/**
* Log a standard startup banner.
@@ -10,14 +10,6 @@ import { appName, appNames } from "./app";
* @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}`);
diff --git a/web/apps/albums/vendor/ente-base/log.ts b/web/apps/albums/vendor/ente-base/log.ts
index cc4de0068b..708cbbdb31 100644
--- a/web/apps/albums/vendor/ente-base/log.ts
+++ b/web/apps/albums/vendor/ente-base/log.ts
@@ -23,9 +23,7 @@ export const disableDiskLogs = () => (shouldLogToDisk = false);
* 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);
+ if (inWorker()) workerLogToDisk(message);
else webLogToDisk(message);
};
@@ -119,10 +117,8 @@ const logDebug = (param: () => unknown) => {
*
* 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.
+ * Messages are written to a ring buffer in local storage, and proxied back to
+ * the main thread when emitted from workers.
*/
export default {
/**
diff --git a/web/apps/albums/vendor/ente-base/origins.ts b/web/apps/albums/vendor/ente-base/origins.ts
index 45877a620a..1185534397 100644
--- a/web/apps/albums/vendor/ente-base/origins.ts
+++ b/web/apps/albums/vendor/ente-base/origins.ts
@@ -104,23 +104,6 @@ export const albumsAppOrigin = () =>
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.
*
diff --git a/web/apps/albums/vendor/ente-base/session.ts b/web/apps/albums/vendor/ente-base/session.ts
index f93b4f9c7e..28153238c6 100644
--- a/web/apps/albums/vendor/ente-base/session.ts
+++ b/web/apps/albums/vendor/ente-base/session.ts
@@ -1,22 +1,8 @@
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(),
@@ -31,36 +17,8 @@ const sessionKeyData = async (keyData: string): Promise<SessionKeyData> => {
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");
+const sessionKey = async (keyName: string) => {
+ const value = sessionStorage.getItem(keyName);
if (!value) return undefined;
const { encryptedData, key, nonce } = SessionKeyData.parse(
@@ -69,129 +27,20 @@ export const masterKeyFromSession = async () => {
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);
- }
+export const ensureMasterKeyFromSession = async () => {
+ const key = await masterKeyFromSession();
+ if (!key) throw new Error("Master key not found in session");
+ return key;
};
-/**
- * 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;
+export const haveMasterKeyInSession = () =>
+ !!sessionStorage.getItem("encryptionKey");
- sessionStorage.removeItem("keyEncryptionKey");
+export const masterKeyFromSession = async () => sessionKey("encryptionKey");
- const { encryptedData, key, nonce } = SessionKeyData.parse(
- JSON.parse(value),
+export const saveMasterKeyInSession = async (masterKey: string) => {
+ sessionStorage.setItem(
+ "encryptionKey",
+ JSON.stringify(await sessionKeyData(masterKey)),
);
- return decryptBox({ encryptedData, nonce }, key);
};
diff --git a/web/apps/albums/vendor/ente-base/types/ipc.ts b/web/apps/albums/vendor/ente-base/types/ipc.ts
index 795ae3d239..f782b4db02 100644
--- a/web/apps/albums/vendor/ente-base/types/ipc.ts
+++ b/web/apps/albums/vendor/ente-base/types/ipc.ts
@@ -1,921 +1,5 @@
-// 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/worker/comlink-worker.ts b/web/apps/albums/vendor/ente-base/worker/comlink-worker.ts
index 44169c2e43..7f57765df7 100644
--- a/web/apps/albums/vendor/ente-base/worker/comlink-worker.ts
+++ b/web/apps/albums/vendor/ente-base/worker/comlink-worker.ts
@@ -1,35 +1,9 @@
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) {
@@ -53,22 +27,8 @@ export class ComlinkWorker<T extends new () => InstanceType<T>> {
}
}
-/**
- * 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;