Skip to content

armgit / ente

Public Imported from GitHub
0

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

Trim duplicated photos code from albums app

Anand Baburajan425e77d8db6e
diff --git a/web/apps/albums/vendor/ente-gallery/components/FileInfo.tsx b/web/apps/albums/vendor/ente-gallery/components/FileInfo.tsx
index 65d06e67cd..0a7e043efc 100644
--- a/web/apps/albums/vendor/ente-gallery/components/FileInfo.tsx
+++ b/web/apps/albums/vendor/ente-gallery/components/FileInfo.tsx
@@ -1,187 +1,53 @@
-/* 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 PersonOutlineIcon from "@mui/icons-material/PersonOutline";
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 type { Location } from "ente-base/types";
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 type { ModalVisibilityProps } from "ente-base/components/utils/modal";
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 type { RawExifTags } from "ente-gallery/services/exif";
import { formattedByteSize } from "ente-gallery/utils/units";
-import { type EnteFile } from "ente-media/file";
+import type { EnteFile } from "ente-media/file";
import {
fileCreationPhotoDate,
+ fileDurationString,
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;
+import type { ReactNode } from "react";
-/**
- * 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;
};
@@ -190,996 +56,157 @@ export const FileInfo: React.FC<FileInfoProps> = ({
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 caption = file.pubMagicMetadata?.data.caption ?? exif?.parsed?.description;
+ const location = fileLocation(file) ?? exif?.parsed?.location;
const uploaderName = file.pubMagicMetadata?.data.uploaderName;
+ const date = fileCreationPhotoDate(file);
+ const mediaDetails = mediaDetailsCaption(file, exif?.parsed);
return (
- <FileInfoSidebar {...{ open, onClose }}>
+ <FileInfoSidebar anchor="right" {...{ open, onClose }}>
<SidebarDrawerTitlebar
onClose={onClose}
onRootClose={onClose}
title={t("info")}
/>
- <Stack sx={{ pt: 1, pb: 3, gap: "20px" }}>
- <Caption
- {...{
- file,
- allowEdits,
- onFileMetadataUpdate,
- onUpdateCaption,
- onClose,
- }}
+ <Stack sx={{ px: 1, pt: 1, pb: 3, gap: "16px" }}>
+ <InfoRow
+ icon={
+ file.metadata.fileType === FileType.video ? (
+ <VideocamOutlinedIcon />
+ ) : (
+ <PhotoOutlinedIcon />
+ )
+ }
+ title={fileFileName(file)}
+ caption={[
+ fileTypeLabel(file),
+ mediaDetails,
+ ]
+ .filter(Boolean)
+ .join(" β€’ ")}
+ action={<CopyButton text={fileFileName(file)} size="small" />}
/>
- <CreationTime {...{ file, allowEdits, onFileMetadataUpdate }} />
- <FileName
- {...{
- file,
- annotatedExif,
- allowEdits,
- onFileMetadataUpdate,
- }}
+
+ <InfoRow
+ icon={<CalendarTodayIcon />}
+ title={formattedDate(date)}
+ caption={formattedTime(date)}
/>
- {annotatedExif?.takenOnDevice && (
- <InfoItem
- icon={<CameraOutlinedIcon />}
- title={annotatedExif.takenOnDevice}
- caption={createMultipartCaption(
- annotatedExif.fNumber,
- annotatedExif.exposureTime,
- annotatedExif.iso,
- )}
+ {caption && (
+ <InfoRow
+ icon={<TextSnippetOutlinedIcon />}
+ title={caption}
+ caption="Caption"
/>
)}
- {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}
+ {location && (
+ <InfoRow
+ icon={<LocationOnOutlinedIcon />}
+ title={locationLabel(location)}
+ caption={
+ <Link
+ href={openStreetMapLink(location)}
+ target="_blank"
+ rel="noopener"
+ sx={{ fontWeight: "medium" }}
+ >
+ {t("view_on_map")}
+ </Link>
+ }
+ action={
+ <CopyButton
+ text={openStreetMapLink(location)}
+ size="small"
/>
- )}
- </>
- ) : (
- 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>
+ <InfoRow
+ icon={<PersonOutlineIcon />}
+ title={uploaderName}
+ caption="Uploader"
+ />
)}
</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)}`;
+const fileTypeLabel = (file: EnteFile) => {
+ switch (file.metadata.fileType) {
+ case FileType.video:
+ return t("video");
+ case FileType.livePhoto:
+ return t("live_photo");
+ case FileType.image:
+ default:
+ return t("image");
}
-
- 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,
- },
- }),
-}));
+const mediaDetailsCaption = (
+ file: EnteFile,
+ parsed: ParsedMetadata | undefined,
+) =>
+ [
+ parsed?.width && parsed?.height
+ ? `${parsed.width} Γ— ${parsed.height}`
+ : undefined,
+ file.info?.fileSize
+ ? formattedByteSize(file.info.fileSize)
+ : undefined,
+ fileDurationString(file),
+ ]
+ .filter(Boolean)
+ .join(" β€’ ");
+
+const locationLabel = ({ latitude, longitude }: Location) =>
+ `${latitude.toFixed(6)}, ${longitude.toFixed(6)}`;
-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;
-}
+const openStreetMapLink = ({ latitude, longitude }: Location) =>
+ `https://www.openstreetmap.org/?mlat=${latitude}&mlon=${longitude}#map=15/${latitude}/${longitude}`;
-/**
- * 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>
+const FileInfoSidebar = styled(SidebarDrawer)({
+ "& .MuiDrawer-paper": {
+ overflowX: "hidden",
+ },
+});
+
+const InfoRow: React.FC<{
+ icon: ReactNode;
+ title: ReactNode;
+ caption?: ReactNode;
+ action?: ReactNode;
+}> = ({ icon, title, caption, action }) => (
+ <Stack direction="row" sx={{ gap: 1.5, alignItems: "flex-start" }}>
+ <IconContainer>{icon}</IconContainer>
+ <Stack sx={{ minWidth: 0, flex: 1, gap: 0.25 }}>
+ <Typography sx={{ wordBreak: "break-word", fontWeight: "medium" }}>
+ {title}
+ </Typography>
+ {caption && (
<Typography
variant="small"
- {...(typeof caption != "string" && { component: "div" })}
- sx={{ color: "text.muted" }}
+ sx={{ color: "text.muted", wordBreak: "break-word" }}
>
{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 =
- '&copy; <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>
+ {action}
+ </Stack>
);
-const ChipButton = styled((props: ButtonProps) => (
- <Button color="secondary" {...props} />
-))(({ theme }) => ({ ...theme.typography.small, padding: "8px" }));
+const IconContainer = styled("div")(({ theme }) => ({
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ color: theme.vars.palette.text.muted,
+ paddingTop: "2px",
+}));
diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsx
index 8197acbf59..1eb3f6b610 100644
--- a/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsx
+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsx
@@ -4,7 +4,6 @@ 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";
@@ -21,7 +20,6 @@ import {
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";
@@ -31,7 +29,6 @@ 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";
@@ -41,11 +38,9 @@ import {
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 { 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,
@@ -55,10 +50,6 @@ import {
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";
@@ -154,7 +145,6 @@ export interface FileViewerFileAnnotation {
* `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;
}
/**
@@ -335,17 +325,6 @@ export type FileViewerProps = ModalVisibilityProps & {
* 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,
@@ -440,7 +419,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({
onDelete,
onSelectCollection,
onSelectPerson,
- onSaveEditedImageCopy,
onAddFileToCollection,
activeCollectionID,
publicAlbumsCredentials,
@@ -505,7 +483,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({
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);
@@ -657,7 +634,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({
// 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);
@@ -1465,33 +1441,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({
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;
@@ -1510,9 +1459,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({
!isInTrashSection &&
!isInIncomingSharedCollection;
- const showEditImage =
- !!handleEditImage && canModify && fileIsEditableImage(file);
-
const showDownload = (() => {
if (disableDownload) return undefined;
if (!onDownload) return undefined;
@@ -1545,7 +1491,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({
showDelete,
showArchive,
showCopyImage,
- showEditImage,
};
const annotatedFile = { file, annotation, itemData };
@@ -1559,7 +1504,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({
isInTrashSection,
isInHiddenSection,
onDownload,
- handleEditImage,
handleConfirmDelete,
],
);
@@ -1817,7 +1761,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({
openLikeAlbumSelector ||
openPublicLikeModal ||
!!moreMenuAnchorEl ||
- openImageEditor ||
openConfirmDelete ||
openShortcuts
) {
@@ -1850,7 +1793,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({
openLikeAlbumSelector,
openPublicLikeModal,
moreMenuAnchorEl,
- openImageEditor,
openConfirmDelete,
openShortcuts,
]);
@@ -2756,12 +2698,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({
</MoreMenuItem>
)}
- {activeAnnotatedFile.annotation.showEditImage && (
- <MoreMenuItem onClick={handleEditImage}>
- <MoreMenuItemTitle>{t("edit_image")}</MoreMenuItemTitle>
- <EditIcon />
- </MoreMenuItem>
- )}
<MoreMenuItem
onClick={handleToggleFullscreen}
divider
@@ -2793,14 +2729,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({
onClose={handleConfirmDeleteClose}
onConfirm={handleDelete}
/>
- {handleSaveEditedCopy && (
- <ImageEditorOverlay
- open={openImageEditor}
- onClose={handleImageEditorClose}
- file={activeAnnotatedFile.file}
- onSaveEditedCopy={handleSaveEditedCopy}
- />
- )}
<Shortcuts
open={openShortcuts}
onClose={handleShortcutsClose}
@@ -3057,23 +2985,6 @@ const Shortcut: React.FC<ShortcutProps> = ({ action, shortcut }) => (
</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
diff --git a/web/apps/albums/vendor/ente-gallery/services/save.ts b/web/apps/albums/vendor/ente-gallery/services/save.ts
index 51f42ed3c0..ea65cbf8f6 100644
--- a/web/apps/albums/vendor/ente-gallery/services/save.ts
+++ b/web/apps/albums/vendor/ente-gallery/services/save.ts
@@ -4,17 +4,18 @@ 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 {
+ exportMetadataDirectoryName,
+ exportTrashDirectoryName,
+} from "ente-gallery/export-dirs";
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 sanitize from "sanitize-filename";
import type {
AddSaveGroup,
UpdateSaveGroup,
@@ -32,6 +33,46 @@ interface DownloadLimits {
let cachedLimits: DownloadLimits | undefined;
+const sanitizeFilename = (s: string) => sanitize(s, { replacement: "_" });
+
+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;
+};
+
+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;
+};
+
/**
* Get download limits for the current device.
*
diff --git a/web/apps/albums/vendor/ente-gallery/services/video.ts b/web/apps/albums/vendor/ente-gallery/services/video.ts
index 9962f46516..4720924a33 100644
--- a/web/apps/albums/vendor/ente-gallery/services/video.ts
+++ b/web/apps/albums/vendor/ente-gallery/services/video.ts
@@ -1,332 +1,21 @@
-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 { decryptBlobBytes } 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 type { PublicAlbumsCredentials } from "ente-base/http";
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 log from "ente-base/log";
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();
-};
+import { fetchFileData, fetchFilePreviewData } from "./file-data";
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,
@@ -344,14 +33,15 @@ export const hlsPlaylistDataForFile = async (
);
if (!playlistFileData) return undefined;
- const {
- type,
- playlist: playlistTemplate,
- width,
- height,
- } = await decryptPlaylistJSON(playlistFileData, file);
+ let playlistJSON: PlaylistJSON;
+ try {
+ playlistJSON = await decryptPlaylistJSON(playlistFileData, file);
+ } catch (e) {
+ log.error(`Failed to read HLS playlist for ${fileLogID(file)}`, e);
+ return undefined;
+ }
- // A playlist format the current client does not understand.
+ const { type, playlist: playlistTemplate, width, height } = playlistJSON;
if (type != "hls_video") return undefined;
const videoURL = await fetchFilePreviewData(
@@ -361,78 +51,11 @@ export const hlsPlaylistDataForFile = async (
);
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" }),
);
@@ -441,30 +64,10 @@ export const hlsPlaylistDataForFile = async (
};
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>;
@@ -478,590 +81,14 @@ const decryptPlaylistJSON = async (
return PlaylistJSON.parse(JSON.parse(jsonString));
};
-/**
- * Convert a blob to a `data:` URL.
- */
+const gunzip = async (data: Uint8Array) =>
+ await new Response(
+ new Blob([data]).stream().pipeThrough(new DecompressionStream("gzip")),
+ ).text();
+
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-new/photos/components/AssignPersonDialog.tsx b/web/apps/albums/vendor/ente-new/photos/components/AssignPersonDialog.tsx
deleted file mode 100644
index d6c39bf746..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/AssignPersonDialog.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-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.tsx
deleted file mode 100644
index 45f5f08c1b..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/CollectionMappingChoice.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-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.tsx
deleted file mode 100644
index fd6734a897..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/CollectionSelector.tsx
+++ /dev/null
@@ -1,519 +0,0 @@
-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.tsx
deleted file mode 100644
index 980463e24c..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/CollectionsSortOptions.tsx
+++ /dev/null
@@ -1,249 +0,0 @@
-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.tsx
deleted file mode 100644
index 4536baecd4..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/EditLocationDialog.tsx
+++ /dev/null
@@ -1,826 +0,0 @@
-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 =
- '&copy; <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.tsx
deleted file mode 100644
index f46ecae0d8..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/FileContextMenu.tsx
+++ /dev/null
@@ -1,207 +0,0 @@
-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.tsx
deleted file mode 100644
index de1e3740c8..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/FileDateTimePicker.tsx
+++ /dev/null
@@ -1,151 +0,0 @@
-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.tsx
deleted file mode 100644
index 62e0b7b2aa..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/ImageEditorOverlay.tsx
+++ /dev/null
@@ -1,1361 +0,0 @@
-/* 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/PeopleList.tsx b/web/apps/albums/vendor/ente-new/photos/components/PeopleList.tsx
deleted file mode 100644
index bdf51a1934..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/PeopleList.tsx
+++ /dev/null
@@ -1,319 +0,0 @@
-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/SelectedFileOptions.tsx b/web/apps/albums/vendor/ente-new/photos/components/SelectedFileOptions.tsx
deleted file mode 100644
index b272fa5ede..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/SelectedFileOptions.tsx
+++ /dev/null
@@ -1,674 +0,0 @@
-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/Tiles.tsx b/web/apps/albums/vendor/ente-new/photos/components/Tiles.tsx
deleted file mode 100644
index f2b4e83286..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/Tiles.tsx
+++ /dev/null
@@ -1,269 +0,0 @@
-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.tsx
deleted file mode 100644
index d3d5d6f590..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/UnstyledButton.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-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/index.tsx b/web/apps/albums/vendor/ente-new/photos/components/gallery/index.tsx
deleted file mode 100644
index 22f2de3b43..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/gallery/index.tsx
+++ /dev/null
@@ -1,368 +0,0 @@
-/**
- * @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.ts
deleted file mode 100644
index dddbaf75bd..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/gallery/reducer.ts
+++ /dev/null
@@ -1,2082 +0,0 @@
-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.tsx
deleted file mode 100644
index 920405c01e..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/icons/StarIcon.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-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.tsx
deleted file mode 100644
index 16086e5cd1..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/icons/StarOffIcon.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-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.tsx
deleted file mode 100644
index 4dd90d07cd..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/sidebar/MLSettings.tsx
+++ /dev/null
@@ -1,319 +0,0 @@
-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.tsx
deleted file mode 100644
index 6648273b81..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/utils/download.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-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/use-snapshot.ts b/web/apps/albums/vendor/ente-new/photos/components/utils/use-snapshot.ts
deleted file mode 100644
index 0b76c01b3a..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/utils/use-snapshot.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-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.ts
deleted file mode 100644
index ebae892663..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/components/utils/use-wrap-async.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-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.ts
deleted file mode 100644
index 35cbceadc8..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/app-lock.ts
+++ /dev/null
@@ -1,1088 +0,0 @@
-/**
- * @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.ts
deleted file mode 100644
index 6c5395302e..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/avatar.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * 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.ts b/web/apps/albums/vendor/ente-new/photos/services/collection.ts
index 69bf36ca54..e4af4ee7c3 100644
--- a/web/apps/albums/vendor/ente-new/photos/services/collection.ts
+++ b/web/apps/albums/vendor/ente-new/photos/services/collection.ts
@@ -35,10 +35,10 @@ import { ItemVisibility, metadataHash } from "ente-media/file-metadata";
import {
createMagicMetadata,
encryptMagicMetadata,
+ type RemoteMagicMetadata,
} from "ente-media/magic-metadata";
import { splitByPredicate } from "ente-utils/array";
import { z } from "zod";
-import { batched, type UpdateMagicMetadataRequest } from "./file";
import {
removeCollectionIDLastSyncTime,
saveCollectionFiles,
@@ -56,6 +56,23 @@ const uncategorizedCollectionName = "Uncategorized";
const defaultHiddenCollectionName = ".hidden";
export const defaultHiddenCollectionUserFacingName = "Hidden";
const favoritesCollectionName = "Favorites";
+const requestBatchSize = 1000;
+
+interface UpdateMagicMetadataRequest {
+ id: number;
+ magicMetadata: RemoteMagicMetadata;
+}
+
+const batched = async <T, U>(
+ items: T[],
+ op: (batchItems: T[]) => Promise<U>,
+): Promise<U[]> => {
+ const result: U[] = [];
+ for (let i = 0; i < items.length; i += requestBatchSize) {
+ result.push(await op(items.slice(i, i + requestBatchSize)));
+ }
+ return result;
+};
/**
* Create a new album (a collection of type "album") on remote, and return its
diff --git a/web/apps/albums/vendor/ente-new/photos/services/file.ts b/web/apps/albums/vendor/ente-new/photos/services/file.ts
deleted file mode 100644
index ac82b9eea3..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/file.ts
+++ /dev/null
@@ -1,302 +0,0 @@
-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.ts
deleted file mode 100644
index 01d884b472..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/blob.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-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.ts
deleted file mode 100644
index 7736c34134..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/clip.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-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.ts
deleted file mode 100644
index d4e34378dc..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/cluster.ts
+++ /dev/null
@@ -1,426 +0,0 @@
-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.ts
deleted file mode 100644
index b6dcf31cfe..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/crop.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-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.ts
deleted file mode 100644
index 6372313f6f..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/db.ts
+++ /dev/null
@@ -1,406 +0,0 @@
-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.ts
deleted file mode 100644
index 66844b01dc..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/decode.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 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.ts
deleted file mode 100644
index e3f4c4a94b..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/face.ts
+++ /dev/null
@@ -1,831 +0,0 @@
-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.ts
deleted file mode 100644
index 8d91842922..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/image.ts
+++ /dev/null
@@ -1,238 +0,0 @@
-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.ts
deleted file mode 100644
index d5c23bf421..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/index.ts
+++ /dev/null
@@ -1,1005 +0,0 @@
-/**
- * @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.ts
deleted file mode 100644
index 9792514d7f..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/kvdb.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-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.ts
deleted file mode 100644
index b4506f0fff..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/math.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * 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.ts
deleted file mode 100644
index 6d04b619f9..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/ml-data.ts
+++ /dev/null
@@ -1,226 +0,0 @@
-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.ts
deleted file mode 100644
index 189be16169..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/people.ts
+++ /dev/null
@@ -1,840 +0,0 @@
-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.ts
deleted file mode 100644
index 16153b3b2b..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/worker-types.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * @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.ts
deleted file mode 100644
index 919f9fef77..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/ml/worker.ts
+++ /dev/null
@@ -1,653 +0,0 @@
-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.ts
index 2b49a16bfd..1aaf5b44fc 100644
--- a/web/apps/albums/vendor/ente-new/photos/services/photos-fdb.ts
+++ b/web/apps/albums/vendor/ente-new/photos/services/photos-fdb.ts
@@ -12,7 +12,12 @@ import {
import { type Collection } from "ente-media/collection";
import { type EnteFile } from "ente-media/file";
import { z } from "zod";
-import type { TrashItem } from "./trash";
+
+interface TrashItem {
+ file: EnteFile;
+ updatedAt: number;
+ deleteBy: number;
+}
/**
* Return all collections present in our local database.
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.ts
deleted file mode 100644
index 8bbe80c08e..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/remote-store.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-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.ts
deleted file mode 100644
index da95a32bc1..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/search/index.ts
+++ /dev/null
@@ -1,202 +0,0 @@
-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.ts
deleted file mode 100644
index 9a6eb25036..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/search/types.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-/**
- * @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.ts
deleted file mode 100644
index 831cdc9df3..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/search/worker.ts
+++ /dev/null
@@ -1,579 +0,0 @@
-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.ts
deleted file mode 100644
index 1601cac11d..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/settings.ts
+++ /dev/null
@@ -1,313 +0,0 @@
-/**
- * @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/trash.ts b/web/apps/albums/vendor/ente-new/photos/services/trash.ts
deleted file mode 100644
index d42dde4246..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/trash.ts
+++ /dev/null
@@ -1,277 +0,0 @@
-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.ts
deleted file mode 100644
index 7202441633..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/user-details.ts
+++ /dev/null
@@ -1,622 +0,0 @@
-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.ts
deleted file mode 100644
index 7558acee55..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/user-entity/db.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-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.ts
deleted file mode 100644
index 6a4dea2ce0..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/user-entity/index.ts
+++ /dev/null
@@ -1,292 +0,0 @@
-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.ts
deleted file mode 100644
index dd685e1bff..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/services/user-entity/remote.ts
+++ /dev/null
@@ -1,267 +0,0 @@
-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/utils/file-actions.ts b/web/apps/albums/vendor/ente-new/photos/utils/file-actions.ts
deleted file mode 100644
index b070360c9d..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/utils/file-actions.ts
+++ /dev/null
@@ -1,228 +0,0 @@
-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.ts
deleted file mode 100644
index a5731bfcc2..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/utils/gzip.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * 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.ts
deleted file mode 100644
index 94e935a525..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/utils/native-fs.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * @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.ts
deleted file mode 100644
index 7236cab798..0000000000
--- a/web/apps/albums/vendor/ente-new/photos/utils/web.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-/**
- * 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/photos/components/Upload.tsx b/web/apps/albums/vendor/photos/components/Upload.tsx
index 6f61480a63..a2f505f71a 100644
--- a/web/apps/albums/vendor/photos/components/Upload.tsx
+++ b/web/apps/albums/vendor/photos/components/Upload.tsx
@@ -45,7 +45,6 @@ import {
savedPublicCollectionUploaderName,
savePublicCollectionUploaderName,
} from "ente-new/albums/services/public-albums-fdb";
-import type { RemotePullOpts } from "ente-new/photos/components/gallery";
import { usePhotosAppContext } from "ente-new/photos/types/context";
import { firstNonEmpty } from "ente-utils/array";
import { t } from "i18next";
@@ -62,6 +61,15 @@ import { hasReliableCanvasReadback } from "utils/upload/canvas-integrity";
import { CanvasReadbackBlockedDialog } from "./CanvasReadbackBlockedDialog";
import { UploadProgress } from "./UploadProgress";
+interface RemotePullOpts {
+ /**
+ * Perform the pull without showing a global loading bar.
+ *
+ * Default: `false`.
+ */
+ silent?: boolean;
+}
+
interface UploadProps {
publicAlbumsCredentials?: PublicAlbumsCredentials;
uploadTypeSelectorView: boolean;