Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

Deduplicate albums utility helpers

Anand Baburajan18340b34ca15
diff --git a/web/apps/albums/src/public-album/components/FileListWithViewer.tsx b/web/apps/albums/src/public-album/components/FileListWithViewer.tsx
index 2a02f9aa26..e224d59dab 100644
--- a/web/apps/albums/src/public-album/components/FileListWithViewer.tsx
+++ b/web/apps/albums/src/public-album/components/FileListWithViewer.tsx
@@ -6,10 +6,10 @@ import {
LazyFileViewer,
scheduleFileViewerPreload,
} from "@/public-album/viewer/lib/lazy";
-import type { AddSaveGroup } from "@/shared/state/save-groups";
import { styled } from "@mui/material";
import { isSameDay } from "ente-base/date";
import { formattedDate } from "ente-base/i18n-date";
+import type { AddSaveGroup } from "ente-gallery/components/utils/save-groups";
import type { EnteFile } from "ente-media/file";
import { fileCreationPhotoDate, fileFileName } from "ente-media/file-metadata";
import { t } from "i18next";
diff --git a/web/apps/albums/src/public-album/components/TripLayout/index.tsx b/web/apps/albums/src/public-album/components/TripLayout/index.tsx
index bd1579d518..c721b021a7 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/index.tsx
+++ b/web/apps/albums/src/public-album/components/TripLayout/index.tsx
@@ -7,10 +7,10 @@ import {
LazyPublicFeedSidebar,
scheduleFileViewerPreload,
} from "@/public-album/viewer/lib/lazy";
-import { useSaveGroupsActions } from "@/shared/state/save-groups";
import { Box, styled, useMediaQuery, useTheme } from "@mui/material";
import { useModalVisibility } from "ente-base/components/utils/modal";
import type { PublicAlbumsCredentials } from "ente-base/http";
+import { useSaveGroupsActions } from "ente-gallery/components/utils/save-groups";
import { type Collection } from "ente-media/collection";
import { type EnteFile } from "ente-media/file";
import { useCallback, useEffect, useRef, useState } from "react";
diff --git a/web/apps/albums/src/public-album/download/components/ActiveDownloadStatusNotifications.tsx b/web/apps/albums/src/public-album/download/components/ActiveDownloadStatusNotifications.tsx
index f73fbcdd14..f82c8dd49b 100644
--- a/web/apps/albums/src/public-album/download/components/ActiveDownloadStatusNotifications.tsx
+++ b/web/apps/albums/src/public-album/download/components/ActiveDownloadStatusNotifications.tsx
@@ -1,4 +1,4 @@
-import { useSaveGroups } from "@/shared/state/save-groups";
+import { useSaveGroups } from "ente-gallery/components/utils/save-groups";
import dynamic from "next/dynamic";
import { type DownloadStatusNotificationsProps } from "./DownloadStatusNotifications";
diff --git a/web/apps/albums/src/public-album/download/components/DownloadStatusNotifications.tsx b/web/apps/albums/src/public-album/download/components/DownloadStatusNotifications.tsx
index 3d22e4c01b..f79cdc49c3 100644
--- a/web/apps/albums/src/public-album/download/components/DownloadStatusNotifications.tsx
+++ b/web/apps/albums/src/public-album/download/components/DownloadStatusNotifications.tsx
@@ -1,8 +1,3 @@
-import {
- isSaveComplete,
- isSaveCompleteWithErrors,
- type SaveGroup,
-} from "@/shared/state/save-groups";
import { Notification } from "@/shared/ui/feedback/Notification";
import {
Download01Icon,
@@ -21,6 +16,11 @@ import {
Typography,
} from "@mui/material";
import { useBaseContext } from "ente-base/context";
+import {
+ isSaveComplete,
+ isSaveCompleteWithErrors,
+ type SaveGroup,
+} from "ente-gallery/components/utils/save-groups";
import { t } from "i18next";
import { useState } from "react";
diff --git a/web/apps/albums/src/public-album/download/services/download-manager.ts b/web/apps/albums/src/public-album/download/services/download-manager.ts
index 364c8eed5e..d491532c6d 100644
--- a/web/apps/albums/src/public-album/download/services/download-manager.ts
+++ b/web/apps/albums/src/public-album/download/services/download-manager.ts
@@ -7,7 +7,6 @@ import {
playableVideoURL,
renderableImageBlob,
} from "@/public-album/media/processing/convert";
-import { detectFileTypeInfoFromChunk } from "@/public-album/media/utils/detect-type";
import { blobCache, type BlobCache } from "ente-base/blob-cache";
import {
decryptBlobBytes,
@@ -23,6 +22,7 @@ import {
} from "ente-base/http";
import log from "ente-base/log";
import { customAPIOrigin } from "ente-base/origins";
+import { detectFileTypeInfoFromChunk } from "ente-gallery/utils/detect-type";
import type { EnteFile } from "ente-media/file";
import { fileFileName } from "ente-media/file-metadata";
import { FileType } from "ente-media/file-type";
diff --git a/web/apps/albums/src/public-album/download/services/save.ts b/web/apps/albums/src/public-album/download/services/save.ts
index d6dd3a9c56..3ff0f4e963 100644
--- a/web/apps/albums/src/public-album/download/services/save.ts
+++ b/web/apps/albums/src/public-album/download/services/save.ts
@@ -1,9 +1,12 @@
import { downloadManager } from "@/public-album/download/services/download-manager";
-import type { AddSaveGroup, UpdateSaveGroup } from "@/shared/state/save-groups";
import { assertionFailed } from "ente-base/assert";
import { nameAndExtension } from "ente-base/file-name";
import log from "ente-base/log";
import { saveAsFileAndRevokeObjectURL } from "ente-base/utils/web";
+import type {
+ AddSaveGroup,
+ UpdateSaveGroup,
+} from "ente-gallery/components/utils/save-groups";
import type { EnteFile } from "ente-media/file";
import { fileFileName } from "ente-media/file-metadata";
import { FileType } from "ente-media/file-type";
diff --git a/web/apps/albums/src/public-album/media/metadata/exif.ts b/web/apps/albums/src/public-album/media/metadata/exif.ts
deleted file mode 100644
index f49107cda9..0000000000
--- a/web/apps/albums/src/public-album/media/metadata/exif.ts
+++ /dev/null
@@ -1,666 +0,0 @@
-import { inWorker } from "ente-base/env";
-import {
- parseMetadataDate,
- type ParsedMetadata,
- type ParsedMetadataDate,
-} from "ente-media/file-metadata";
-import ExifReader from "exifreader";
-
-/**
- * Extract Exif and other metadata from the given file.
- *
- * [Note: Exif]
- *
- * Exif is a standard for metadata embedded in photos. Exif tags arise from the
- * TIFF specification but now can be found in other file formats, notably JPG,
- * PNG, AVI, MOV, TIFF-based RAW images (and TIFF itself)
- *
- * The standard uses "Exif" (not "EXIF") to refer to itself. We do the same.
- *
- * Exif is now commonly used as a synedoche for all forms of metadata that gets
- * embedded in a file, and this is also how we use the term. So these functions
- * extract and operate on not just Exif tags, but also XMP (XML metadata
- * embedded in images) and IPTC (another metadat standard) tags.
- *
- * A list for metadata tags can be found in exiftool's documentation:
- * https://exiftool.org/TagNames
- *
- * The library we use is https://github.com/mattiasw/ExifReader.
- */
-export const extractExif = async (file: File) =>
- await extractRawExif(file).then(parseExif);
-
-/**
- * Parse an already extracted {@link RawExifTags}.
- *
- * See: {@link extractExif}. This function does just the parsing step, for use
- * when we've already extracted the raw data.
- */
-export const parseExif = (tags: RawExifTags) => {
- const location = parseLocation(tags);
- const creationDate = parseCreationDate(tags);
- const dimensions = parseDimensions(tags);
- const description = parseDescription(tags);
- const camera = parseCamera(tags);
-
- const metadata: ParsedMetadata = dimensions ?? {};
- if (creationDate) metadata.creationDate = creationDate;
- if (location) metadata.location = location;
- if (description) metadata.description = description;
- if (camera?.make) metadata.cameraMake = camera.make;
- if (camera?.model) metadata.cameraModel = camera.model;
- return metadata;
-};
-
-/**
- * Parse GPS location from the metadata embedded in the file.
- *
- * - If a location is returned, then both latitude and longitude will be
- * defined.
- * - NaNs are ignored, and treated as if they are not defined.
- */
-const parseLocation = (tags: RawExifTags) => {
- const latitude = tags.gps?.Latitude;
- const longitude = tags.gps?.Longitude;
-
- if (latitude === undefined || longitude === undefined) return undefined;
- if (Number.isNaN(latitude) || Number.isNaN(longitude)) return undefined;
-
- return { latitude, longitude };
-};
-
-/**
- * Parse a single "best" creation date for an image from the metadata embedded
- * in the file.
- *
- * A file has multiple types of metadata, and each of these has multiple types
- * of dates, so we use some an a heuristic ordering (based on experience with
- * the photos we find out in the wild) to pick a "best" date.
- */
-const parseCreationDate = (tags: RawExifTags) => {
- const { DateTimeOriginal, DateTimeDigitized, MetadataDate, DateTime } =
- parseDates(tags);
- return DateTimeOriginal ?? DateTimeDigitized ?? MetadataDate ?? DateTime;
-};
-
-/**
- * Dates extracted from the Exif and other metadata embedded in a file.
- *
- * These are the dates corresponding to the various options we show to the user
- * for the "Fix date" functionality. These don't come solely from the Exif but
- * from all forms of metadata we support (Exif, XMP, IPTC). They roughly
- * correspond to the three Exif DateTime* tags, and the XMP MetadataDate tag.
- */
-interface ParsedExifDates {
- DateTimeOriginal: ParsedMetadataDate | undefined;
- DateTimeDigitized: ParsedMetadataDate | undefined;
- DateTime: ParsedMetadataDate | undefined;
- MetadataDate: ParsedMetadataDate | undefined;
-}
-
-/**
- * Extract dates from Exif and other metadata for the given file.
- */
-export const extractExifDates = (file: File): Promise<ParsedExifDates> =>
- extractRawExif(file).then(parseDates);
-
-/**
- * Parse all date related fields from the metadata embedded in the file,
- * grouping them into chunks that somewhat reflect the Exif ontology.
- */
-const parseDates = (tags: RawExifTags) => {
- // Ignore dates whose epoch is 0.
- //
- // Some customers (not sure how prevalent this is) reported photos with Exif
- // dates set to "0000:00:00 00:00:00". Ignore any date whose timestamp is 0
- // so that we try with a subsequent (possibly correct) date in the sequence.
- //
- // Filter out a known corrupted date value, "4501:01:01 00:00:00".
- // Certain devices default to this bogus timestamp, so skip it to allow other dates.
- const valid = (d: ParsedMetadataDate | undefined) => {
- if (!d?.timestamp) return undefined;
- if (d.dateTime === "4501-01-01T00:00:00.000") return undefined;
- return d;
- };
-
- const exif = parseExifDates(tags);
- const iptc = parseIPTCDates(tags);
- const xmp = parseXMPDates(tags);
-
- return {
- DateTimeOriginal:
- valid(xmp.DateTimeOriginal) ??
- valid(iptc.DateTimeOriginal) ??
- valid(exif.DateTimeOriginal) ??
- valid(xmp.DateCreated),
- DateTimeDigitized:
- valid(xmp.DateTimeDigitized) ??
- valid(iptc.DateTimeDigitized) ??
- valid(exif.DateTimeDigitized) ??
- valid(xmp.CreateDate),
- DateTime: valid(xmp.DateTime ?? exif.DateTime ?? xmp.ModifyDate),
- MetadataDate: valid(xmp.MetadataDate),
- };
-};
-
-/**
- * Parse a date from an Exif date and offset tag combination.
- *
- * @param tags Metadata tags associated with a file.
- *
- * @param dateTag The name of the date tag to use.
- *
- * @param offsetTag The name of the offset tag corresponding to {@link dateTag}.
- *
- * @returns a {@link Date} (UTC epoch milliseconds).
- *
- * [Note: Exif dates]
- *
- * The most important bit we usually wish out of Exif is the date and time when
- * the photo was taken. The Exif specification has the following tags related to
- * photo's date:
- *
- * - DateTimeOriginal
- * - DateTimeDigitized (aka "CreateDate")
- * - DateTime (aka "ModifyDate")
- *
- * DateTimeOriginal is meant to signify best when the original image was taken,
- * and we use it as the photo's creation date whenever it is present. If not, we
- * fallback to DateTimeDigitized or DateTime (in that order).
- *
- * Each of these is a string of the format
- *
- * YYYY:MM:DD HH:mm:ss
- *
- * where
- *
- * YYYY 4 digit (zero padded) year
- * MM 2 digit (zero padded) month, with Jan as 01 and Dec as 12.
- * DD 2 digit (zero padded) day of the month (1 to 31)
- * HH 2 digit (zero padded) hours since midnight (00 to 23)
- * mm 2 digit (zero padded) minutes (00 to 59)
- * ss 2 digit (zero padded) seconds (00 to 59)
- *
- * Additionally (and optionally), there are three SubSecTime* tags that provide
- * the fractional seconds (one for each of the above):
- *
- * - SubSecTimeOriginal
- * - SubSecTimeDigitized
- * - SubSecTime
- *
- * Each of which is a string specifying the fractional digits.
- *
- * The dates are all in the local time of the place where the photo was taken.
- * To convert these to UTC, we also need to know the offset from UTC of that
- * local time. This is provided by the three OffsetTime* tags (one for each of
- * the above):
- *
- * - OffsetTimeOriginal
- * - OffsetTimeDigitized
- * - OffsetTime
- *
- * Each of these is a string of the format
- *
- * ±HH:mm
- *
- * denoting the signed hour and minute offset from UTC.
- *
- * Note that these OffsetTime* tags are relatively new additions (prior to
- * smartphones, cameras did not have a good way of knowing their TZ), and most
- * old photos will not have this information. In such cases, we assume that
- * these photos are in the local time where this code is running. This is
- * manifestly going to be incorrect in some cases, but it is a better assumption
- * than assuming UTC, which, while deterministic, is going to incorrect in an
- * overwhelming majority of cases.
- */
-const parseExifDates = ({ exif }: RawExifTags) => ({
- DateTimeOriginal: parseExifDate(
- exif?.DateTimeOriginal,
- exif?.SubSecTimeOriginal,
- exif?.OffsetTimeOriginal,
- ),
- DateTimeDigitized: parseExifDate(
- exif?.DateTimeDigitized,
- exif?.SubSecTimeDigitized,
- exif?.OffsetTimeDigitized,
- ),
- DateTime: parseExifDate(exif?.DateTime, exif?.SubSecTime, exif?.OffsetTime),
-});
-
-const parseExifDate = (
- dateTag: ExifReader.StringArrayTag | undefined,
- subSecTag: ExifReader.StringArrayTag | undefined,
- offsetTag: ExifReader.StringArrayTag | undefined,
-) => {
- const [dateString] = dateTag?.value ?? [];
- if (!dateString) return undefined;
-
- const [subSecString] = subSecTag?.value ?? [];
- const [offsetString] = offsetTag?.value ?? [];
-
- // Perform minor syntactic changes to the Exif date, and add the optional
- // offset, to construct a string in the Javascript date time string format.
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format
- //
- // YYYY:MM:DD HH:mm:ss±HH:mm
- // YYYY-MM-DDTHH:mm:ss±HH:mm
- //
- // When the offset string is missing, the date time is interpreted as local
- // time. This is the behaviour we want.
- //
- // For details see [Note: Exif dates]
-
- return parseMetadataDate(
- dateString.replace(":", "-").replace(":", "-").replace(" ", "T") +
- (subSecString ? "." + subSecString : "") +
- (offsetString ?? ""),
- );
-};
-
-/**
- * Parse date related tags from XMP.
- *
- * The XMP information in the file can have the date related information in tags
- * spread across multiple namespaces.
- *
- * For a list of XMP tags, see https://exiftool.org/TagNames/XMP.html.
- */
-const parseXMPDates = ({ xmp }: RawExifTags) => ({
- /* XMP namespace is indicated for each group */
- // exif:
- DateTimeOriginal: parseXMPDate(xmp?.DateTimeOriginal),
- DateTimeDigitized: parseXMPDate(xmp?.DateTimeDigitized),
- // exif: or tiff:
- DateTime: parseXMPDate(xmp?.DateTime),
- // xmp:
- CreateDate: parseXMPDate(xmp?.CreateDate),
- ModifyDate: parseXMPDate(xmp?.ModifyDate),
- MetadataDate: parseXMPDate(xmp?.MetadataDate),
- // photoshop:
- DateCreated: parseXMPDate(xmp?.DateCreated),
-});
-
-/**
- * Parse an XMP date tag.
- *
- * [Note: XMP dates]
- *
- * XMP dates use a format same as the ISO-8601 format that is used by JavaScript
- * as its date time string format.
- *
- * YYYY-MM-DDThh:mm:ss.sTZD
- *
- * The main difference being, unlike JavaScript, all of the above components
- * except YYYY are optional. In practice, browsers gracefully handle these
- * scenarios, so we can directly use the JavaScript date constructor.
- *
- * References:
- * - https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata#date-value-type
- * - https://developer.adobe.com/xmp/docs/XMPNamespaces/XMPDataTypes/#date
- */
-const parseXMPDate = (xmpTag: ExifReader.XmpTag | undefined) => {
- if (!xmpTag) return undefined;
- const s = xmpTag.value;
- if (typeof s != "string") return undefined;
-
- return parseMetadataDate(s);
-};
-
-/**
- * Parse date related tags from IPTC.
- */
-const parseIPTCDates = ({ iptc }: RawExifTags) => ({
- DateTimeOriginal: parseIPTCDate(
- iptc?.["Date Created"],
- iptc?.["Time Created"],
- ),
- DateTimeDigitized: parseIPTCDate(
- iptc?.["Digital Creation Date"],
- iptc?.["Digital Creation Time"],
- ),
-});
-
-/**
- * Parse an IPTC date tag.
- *
- * [Note: IPTC dates]
- *
- * IPTC date time values are split across two tag:
- *
- * - A tag containing the date as as 8 digit number of the form `YYYYMMDD`.
- *
- * - A tag containing the time as an 11 character string of the form
- * `HHMMSS±HHMM`.
- *
- * They lack separators, but together these tags are meant to encode the same
- * information as the ISO 8601 date format (that XMP and JavaScript also use).
- *
- * Reference:
- * - http://www.iptc.org/std/IIM/4.1/specification/IIMV4.1.pdf
- *
- * ---
- *
- * @param dateTag The tag containing the date part of the date.
- *
- * @param timeTag The tag containing the time part of the date.
- */
-const parseIPTCDate = (
- dateTag: ExifReader.NumberArrayTag | undefined,
- timeTag: ExifReader.NumberArrayTag | undefined,
-) => {
- // The library we use (ExifReader) parses them into a usable representation,
- // which we can use directly. Some notes:
- //
- // - There are currently no separate TypeScript types for the IPTC tags, and
- // instead they are listed as part of the ExifTags.
- //
- // - For the date, whenever possible ExifReader parses the raw data into a
- // description of the form 'YYYY-MM-DD' (See `getCreationDate` in its
- // source code).
- //
- // - For the time, whenever possible ExifReader parses the raw data into a
- // description either of the form 'HH:mm:ss` or `HH:mm:ss±HH:mm` (See
- // `getCreationTime` in its source code).
- if (!dateTag) return undefined;
- let s = dateTag.description;
-
- if (timeTag) s = s + "T" + timeTag.description;
-
- return parseMetadataDate(s);
-};
-
-/**
- * Parse the width and height of the image from the metadata embedded in the
- * file, taking into account any orientation tags that are also present.
- */
-const parseDimensions = (tags: RawExifTags) => {
- // Go through all possibilities in order, returning the first pair with both
- // the width and height defined, and non-zero.
-
- const pair = (w: number | undefined, h: number | undefined) =>
- w && h ? { width: w, height: h } : undefined;
-
- const shouldSwapForExifOrientation = (orientation: number | undefined) => {
- switch (orientation) {
- case 5:
- case 6:
- case 7:
- case 8:
- return true;
- default:
- return false;
- }
- };
-
- const shouldSwapForXMPOrientation = (
- orientation: ExifReader.XmpTag["value"] | undefined,
- ) => {
- if (typeof orientation != "string") return false;
- switch (orientation) {
- case "5":
- case "6":
- case "7":
- case "8":
- return true;
- default:
- return false;
- }
- };
-
- // 1. Use the width and height from the file itself (e.g. JPEG data).
-
- let wh =
- pair(
- tags.file?.["Image Width"]?.value,
- tags.file?.["Image Height"]?.value,
- ) ??
- pair(
- tags.pngFile?.["Image Width"]?.value,
- tags.pngFile?.["Image Height"]?.value,
- ) ??
- pair(
- tags.gif?.["Image Width"]?.value,
- tags.gif?.["Image Height"]?.value,
- ) ??
- pair(tags.riff?.ImageWidth?.value, tags.riff?.ImageHeight?.value);
- if (wh) {
- // The dimensions read from the file headers can still correspond to
- // the un-rotated pixel matrix. For orientations 5-8, we need to swap
- // them to represent the display dimensions used by masonry.
- const shouldSwap =
- shouldSwapForExifOrientation(tags.exif?.Orientation?.value) ||
- (tags.exif?.Orientation?.value == undefined &&
- shouldSwapForXMPOrientation(tags.xmp?.Orientation?.value));
- return shouldSwap ? { width: wh.height, height: wh.width } : wh;
- }
-
- // 2. Exif dimensions, taking Orientation also into account if needed.
-
- wh =
- pair(
- tags.exif?.ImageWidth?.value,
- /* The Exif spec calls it ImageLength, not ImageHeight. */
- tags.exif?.ImageLength?.value,
- ) ??
- pair(
- tags.exif?.PixelXDimension?.value,
- tags.exif?.PixelYDimension?.value,
- );
- if (wh) {
- // Exif Orientation tags can have the following values:
- //
- // 1 = Horizontal (normal)
- // 2 = Mirror horizontal
- // 3 = Rotate 180
- // 4 = Mirror vertical
- // 5 = Mirror horizontal and rotate 270 CW
- // 6 = Rotate 90 CW
- // 7 = Mirror horizontal and rotate 90 CW
- // 8 = Rotate 270 CW
- //
- // Ref: https://exiftool.org/TagNames/EXIF.html
-
- const swap = shouldSwapForExifOrientation(
- tags.exif?.Orientation?.value,
- );
-
- return swap ? { width: wh.height, height: wh.width } : wh;
- }
-
- // 3. XMP dimensions, taking Orientation also into account if needed.
-
- wh =
- pair(
- parseXMPNum(tags.xmp?.ImageWidth),
- parseXMPNum(tags.xmp?.ImageLength),
- ) ??
- pair(
- parseXMPNum(tags.xmp?.PixelXDimension),
- parseXMPNum(tags.xmp?.PixelYDimension),
- );
-
- if (wh) {
- // The Orientation present in XMP (as a TIFF tag) also uses the same
- // constants as Exif above.
- //
- // Ref: https://exiftool.org/TagNames/XMP.html
-
- const swap = shouldSwapForXMPOrientation(tags.xmp?.Orientation?.value);
-
- return swap ? { width: wh.height, height: wh.width } : wh;
- }
-
- return undefined;
-};
-
-/**
- * Try to parse the given XMP tag as a number.
- */
-const parseXMPNum = (xmpTag: ExifReader.XmpTag | undefined) => {
- if (!xmpTag) return undefined;
- const s = xmpTag.value;
- if (typeof s != "string") return undefined;
-
- const n = parseInt(s, 10);
- if (isNaN(n)) return undefined;
- return n;
-};
-
-export type RawExifTags = Omit<ExifReader.ExpandedTags, "Thumbnail" | "xmp"> & {
- xmp?: ExifReader.XmpTags;
-};
-
-/**
- * Extract "raw" exif and other metadata from the given file.
- *
- * @param blob A {@link Blob} containing the data of an {@link EnteFile}.
- *
- * @return A JSON object containing the raw exif and other metadata that was
- * found in the given {@link blob}.
- *
- * ---
- *
- * [Note: Defining "raw" Exif]
- *
- * We wish for a canonical "raw" JSON representing all the Exif data associated
- * with a file. This goal is tricky to achieve because:
- *
- * - While Exif itself is a standard, with a standard set of tags (a numeric
- * id), in practice vendors can use tags more than what are currently listed
- * in the standard.
- *
- * - We're not just interested in Exif tags, but rather at all forms of metadata
- * (e.g. XMP, IPTC) that can be embedded in a file.
- *
- * By default, the library we use (ExifReader) returns a merged object
- * containing all tags it understands from all forms of metadata that it knows
- * about.
- *
- * Since it only returns the tags it understands, it acts an an implicit
- * whitelist. This implicit whitelist behaviour can be turned off by specifying
- * the `includeUnknown` flag, but for our case it is useful since it acts as a
- * safeguard against extracting an unbounded amounts of data (for example, there
- * is an Exif tag for thumbnails. While we specifically filter out that
- * particular tag, it is not hard to imagine some other unforeseen vendor
- * specific tag containing a similarly large amounts of embedded data).
- *
- * So we keep the default behaviour of returning only the tags that the library
- * knows about. Luckily for us, it returns all the XMP tags even if this flag is
- * specified, and that is one place where we'd like unknown tags so that we can
- * selectively start adding support for them.
- *
- * The other default behaviour, of returning a merged object, is a bit more
- * problematic for our use case, since it loses information. Thus, to keep
- * things more deterministic, we specify the `expanded` flag which returns all
- * these different forms of metadata separately.
- *
- * That's for the tags we get. Now to their contents. Generally for each tag
- * (but not for always), we get an entry with an "id", "value" (e.g. the raw
- * bytes), and a "description" (which is the raw data parsed to a form that is
- * more usable). Technically speaking, the value is the raw data we want, but in
- * some cases, the availability of a pre-parsed description will be convenient
- * too. So we don't prune anything, and keep all three.
- *
- * All this means we end up with a JSON whose exact structure is tied to the
- * library we're using (ExifReader), or even its version (the library reserves
- * the right to change the formatting of the "description" fields in minor
- * version updates).
- *
- * So this is not really "raw" Exif. But with that caveat out of the way,
- * practically this should be raw enough given the tradeoffs mentioned above,
- * while allowing us to consume this JSON in arbitrary clients without needing
- * to know about ExifReader specifically.
- */
-export const extractRawExif = async (blob: Blob): Promise<RawExifTags> => {
- // The browser's DOMParser is not available in web workers. So if this
- // function gets called in from a web worker, then it would not be able to
- // parse XMP tags.
- //
- // There is a way around this problem, by also installing ExifReader's
- // optional peer dependency "@xmldom/xmldom". But since we currently have no
- // use case for calling this code in a web worker, we just abort immediately
- // to let future us know that we need to install it.
- if (inWorker())
- throw new Error("DOMParser is not available in web workers");
-
- const tags = await ExifReader.load(await blob.arrayBuffer(), {
- async: true,
- expanded: true,
- });
-
- // Remove the embedded thumbnail (if any).
- delete tags.Thumbnail;
- delete tags.exif?.Thumbnail;
-
- // Remove the embedded MPF images (if any).
- //
- // The TypeScript definition is out of data and doesn't include the top
- // level 'mpf', so we need to cast. From the source:
- //
- // > The images can be accessed by the tags.Images array (tags.mpf.Images if
- // > using expanded: true).
- //
- delete (tags as Record<string, unknown>).mpf;
-
- // Remove the raw XMP (if any).
- //
- // The `includeUnknown` flag does not have any effect on the XMP parser, so
- // we already get all the key value pairs in the XMP as part of the "xmp"
- // object, retaining the raw string is unnecessary.
- //
- // We need to cast to remove the non-optional _raw property. Be aware that
- // this means that from this point onwards, the TypeScript type is out of
- // sync with the actual value (TypeScript type says _raw is always present,
- // while the actual value doesn't have it).
- delete (tags.xmp as Partial<typeof tags.xmp>)?._raw;
-
- return tags;
-};
-
-/**
- * Return a number from a raw Exif tag value.
- *
- * Some numeric Exif values are stored as arrays of two numbers [p, q]
- * representing a rational number p/q. ExifReader usually converts this and for
- * us, but not always.
- *
- * This function takes such potentially ambiguous (already converted or not)
- * values and returns a number.
- */
-export const tagNumericValue = (
- tag: ExifReader.NumberTag | ExifReader.NumberArrayTag,
-) => {
- const v = tag.value;
- return Array.isArray(v) ? (v[0] ?? 0) / (v[1] ?? 1) : v;
-};
-
-const parseCamera = (tags: RawExifTags) => {
- const makeDescription = tags.exif?.Make?.description;
- const modelDescription = tags.exif?.Model?.description;
- const make = makeDescription?.trim();
- const model = modelDescription?.trim();
- if (!make && !model) return undefined;
- return { make, model };
-};
-
-/**
- * Parse the description for an image from the metadata embedded in the file.
- *
- * This function will read the description from the following fields, in order:
- *
- * 1. XMP-dc:description
- * 2. IPTC | Caption/Abstract (120)
- * 3. EXIF IFD0 | 0x010e | ImageDescription
- *
- * For an overview of why this ordering was chosen, see
- * https://github.com/ente/ente/discussions/3857#discussioncomment-11764990
- */
-const parseDescription = (tags: RawExifTags) =>
- // While the TypeScript tags for these three fields are varying (The XMP one
- // doesn't have a static type, the IPTC one is marked as a number array, and
- // the Exif one is a string array), for all three of these, the ExifReader
- // description property (not related to the image "description" in the sense
- // of this function) holds the singular string we're interested in.
- tags.xmp?.description?.description ??
- tags.iptc?.["Caption/Abstract"]?.description ??
- tags.exif?.ImageDescription?.description;
diff --git a/web/apps/albums/src/public-album/media/processing/convert.ts b/web/apps/albums/src/public-album/media/processing/convert.ts
index dd5c8814d9..e3aa53c85d 100644
--- a/web/apps/albums/src/public-album/media/processing/convert.ts
+++ b/web/apps/albums/src/public-album/media/processing/convert.ts
@@ -1,10 +1,10 @@
import { lowercaseExtension } from "ente-base/file-name";
import log from "ente-base/log";
+import { detectFileTypeInfo } from "ente-gallery/utils/detect-type";
import type { EnteFile } from "ente-media/file";
import { KnownFileTypeInfos } from "ente-media/file-type";
import { isHEICExtension, needsJPEGConversion } from "ente-media/formats";
import { heicToJPEG } from "ente-media/heic-convert";
-import { detectFileTypeInfo } from "../utils/detect-type";
import { convertToMP4 } from "./ffmpeg";
/**
diff --git a/web/apps/albums/src/public-album/media/utils/detect-type.ts b/web/apps/albums/src/public-album/media/utils/detect-type.ts
deleted file mode 100644
index 819c43dbfc..0000000000
--- a/web/apps/albums/src/public-album/media/utils/detect-type.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import { lowercaseExtension } from "ente-base/file-name";
-import {
- FileType,
- KnownFileTypeInfos,
- KnownNonMediaFileExtensions,
- type FileTypeInfo,
-} from "ente-media/file-type";
-import { fileTypeFromBuffer } from "file-type";
-
-/**
- * Read the file's initial contents or use the file's name to detect its type.
- *
- * This is a more convenient to use abstraction over
- * {@link detectFileTypeInfoFromChunk} for use when we already have a
- * {@link File} object. See that method's documentation for more details.
- *
- * @param file A {@link File} object
- *
- * @returns The detected {@link FileTypeInfo}.
- */
-export const detectFileTypeInfo = async (file: File): Promise<FileTypeInfo> =>
- detectFileTypeInfoFromChunk(() => readInitialChunkOfFile(file), file.name);
-
-/**
- * The lower layer implementation of the type detector.
- *
- * Usually, when the code already has a {@link File} object at hand, it is
- * easier to use the higher level {@link detectFileTypeInfo} function.
- *
- * However, this lower level function is also exposed for use in cases like
- * during upload where we might not have a File object and would like to provide
- * the initial chunk of the file's contents in a different way.
-
- * This function first reads an initial chunk of the file and tries to detect
- * the file's {@link FileTypeInfo} from it. If that doesn't work, it then falls
- * back to using the file's name to detect it.
- *
- * If neither of these two approaches work, it throws an exception.
- *
- * If we were able to detect the file type, but it is explicitly not a media
- * (image or video) format that we support, then also this function will throw
- * an exception. Such exceptions can be identified using the
- * {@link isFileTypeNotSupportedError} predicate.
-*
- * @param readInitialChunk A function to call to read the initial chunk of the
- * file's data. There is no strict requirement for the size of the chunk this
- * function should return, generally the first few KBs should be good.
- *
- * @param fileNameOrPath The full path or just the file name of the file whose
- * type we're trying to determine. This is used by the fallback layer that tries
- * to detect the type info from the file's extension.
- */
-export const detectFileTypeInfoFromChunk = async (
- readInitialChunk: () => Promise<Uint8Array>,
- fileNameOrPath: string,
-): Promise<FileTypeInfo> => {
- try {
- const typeResult = await detectFileTypeFromBuffer(
- await readInitialChunk(),
- );
-
- const mimeType = typeResult.mime;
-
- let fileType: FileType;
- if (mimeType.startsWith("image/")) {
- fileType = FileType.image;
- } else if (mimeType.startsWith("video/")) {
- fileType = FileType.video;
- } else {
- // This string should satisfy `isFileTypeNotSupportedError`.
- throw new Error(`Unsupported file format (MIME type ${mimeType})`);
- }
-
- return {
- fileType,
- // See https://github.com/sindresorhus/file-type/blob/main/core.d.ts
- // for the full list of ext values.
- extension: typeResult.ext,
- mimeType,
- };
- } catch (e) {
- const extension = lowercaseExtension(fileNameOrPath);
- const known = KnownFileTypeInfos.find((f) => f.extension == extension);
- if (known) return known;
-
- if (extension && KnownNonMediaFileExtensions.includes(extension)) {
- // This string should satisfy `isFileTypeNotSupportedError`.
- throw new Error(
- `Unsupported file format (extension ${extension})`,
- { cause: e },
- );
- }
-
- throw e;
- }
-};
-
-export const isFileTypeNotSupportedError = (e: unknown) =>
- e instanceof Error && e.message.startsWith("Unsupported file format");
-
-const readInitialChunkOfFile = async (file: File) => {
- const chunkSizeForTypeDetection = 4100;
- const chunk = file.slice(0, chunkSizeForTypeDetection);
- return new Uint8Array(await chunk.arrayBuffer());
-};
-
-const detectFileTypeFromBuffer = async (buffer: Uint8Array) => {
- const result = await fileTypeFromBuffer(buffer);
- if (!result)
- throw Error("Could not deduce file type from the file's contents");
- return result;
-};
diff --git a/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx b/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx
index 75b98bb8fa..348cae5688 100644
--- a/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx
+++ b/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx
@@ -32,10 +32,6 @@ import { type FileViewerInitialSidebar } from "@/public-album/viewer/components/
import type { PublicAlbumSingleFileViewerProps } from "@/public-album/viewer/components/PublicAlbumSingleFileViewer";
import { type PublicFeedItemClickInfo } from "@/public-album/viewer/components/PublicFeedSidebar";
import { LazyPublicFeedSidebar } from "@/public-album/viewer/lib/lazy";
-import {
- useSaveGroupsActions,
- type AddSaveGroup,
-} from "@/shared/state/save-groups";
import {
GalleryItemsHeaderAdapter,
GalleryItemsSummary,
@@ -75,6 +71,10 @@ import {
} from "ente-base/http";
import log from "ente-base/log";
import { apiOrigin, isCustomAPIOrigin } from "ente-base/origins";
+import {
+ useSaveGroupsActions,
+ type AddSaveGroup,
+} from "ente-gallery/components/utils/save-groups";
import type { Collection } from "ente-media/collection";
import { type EnteFile } from "ente-media/file";
import { fileFileName } from "ente-media/file-metadata";
diff --git a/web/apps/albums/src/public-album/upload/components/Upload.tsx b/web/apps/albums/src/public-album/upload/components/Upload.tsx
index 1dc09ff800..ed49c8cbee 100644
--- a/web/apps/albums/src/public-album/upload/components/Upload.tsx
+++ b/web/apps/albums/src/public-album/upload/components/Upload.tsx
@@ -26,7 +26,6 @@ import type {
} from "@/public-album/upload/services/upload-manager";
import { uploadManager } from "@/public-album/upload/services/upload-manager";
import { hasReliableCanvasReadback } from "@/public-album/upload/utils/canvas-integrity";
-import { useFileInput } from "@/shared/hooks/useFileInput";
import { Album02Icon, Folder01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
@@ -52,6 +51,7 @@ import { basename } from "ente-base/file-name";
import type { PublicAlbumsCredentials } from "ente-base/http";
import log from "ente-base/log";
import { UploadProgress } from "ente-gallery/components/UploadProgress";
+import { useFileInput } from "ente-gallery/components/utils/use-file-input";
import { type Collection } from "ente-media/collection";
import type { EnteFile } from "ente-media/file";
import { firstNonEmpty } from "ente-utils/array";
diff --git a/web/apps/albums/src/public-album/upload/pipeline/date.ts b/web/apps/albums/src/public-album/upload/pipeline/date.ts
deleted file mode 100644
index 3b200bf83c..0000000000
--- a/web/apps/albums/src/public-album/upload/pipeline/date.ts
+++ /dev/null
@@ -1,231 +0,0 @@
-import { nameAndExtension } from "ente-base/file-name";
-import log from "ente-base/log";
-
-/**
- * Try to extract a date (as epoch microseconds) from a file name by matching it
- * against certain known patterns for media files.
- *
- * This uses all sorts of arbitrary heuristics gathered over time from feedback
- * by users. In particular, this is meant to capture the dates from screenshots
- * and chat app forwards.
- *
- * If the filename doesn't match a known pattern, or if there is some error
- * during the parsing, return `undefined`.
- */
-export const tryParseEpochMicrosecondsFromFileName = (
- fileName: string,
-): number | undefined => {
- try {
- return parseEpochMicrosecondsFromFileName(fileName);
- } catch (e) {
- log.error(`Could not extract date from file name ${fileName}`, e);
- return undefined;
- }
-};
-
-// Not sure why we have a try catch, but until there is a chance to validate
-// that it doesn't indeed throw, keep this actual logic into this separate and
-// more readable function.
-const parseEpochMicrosecondsFromFileName = (fileName: string) => {
- let date: Date | undefined;
-
- fileName = fileName.trim();
-
- // Known patterns.
- if (fileName.startsWith("IMG-") || fileName.startsWith("VID-")) {
- // WhatsApp media files
- // - e.g. "IMG-20171218-WA0028.jpg"
- const p = fileName.split("-");
- const dateString = p[1];
- if (dateString) {
- date = parseDateFromFusedDateString(dateString);
- }
- } else if (fileName.startsWith("Screenshot_")) {
- // Screenshots on Android
- // - e.g. "Screenshot_20181227-152914.jpg"
- const dateString = fileName.replace("Screenshot_", "");
- date = parseDateFromFusedDateString(dateString);
- } else if (fileName.startsWith("signal-")) {
- // Signal images
- //
- // Signal Android uses "yyyy-MM-dd-HH-mm-ss-SSS"
- // https://github.com/signalapp/Signal-Android/commit/39e14e922bf3f5f11b796455355f69e2189d482f
- //
- // e.g. "signal-2024-08-17-21-58-10-982-1.jpg"
- //
- // Signal Desktop uses "YYYY-MM-DD-HHmmss"
- // https://github.com/signalapp/Signal-Desktop/blob/41216f1378899709d03507649e4a602cebb0d064/js/views/attachment_view.js#L97
- //
- // e.g. "signal-2018-08-21-100217.jpg"
- //
- const p = fileName.split("-");
- if (p.length > 5) {
- const dateString = `${p[1]}${p[2]}${p[3]}-${p[4]}${p[5]}${p[6]}`;
- date = parseDateFromFusedDateString(dateString);
- } else if (p.length > 1) {
- const dateString = `${p[1]}${p[2] ?? ""}${p[3] ?? ""}-${p[4] ?? ""}`;
- date = parseDateFromFusedDateString(dateString);
- }
- }
-
- if (!date) {
- const [name] = nameAndExtension(fileName);
-
- if (name.endsWith("_iOS")) {
- // Parse (some) iOS filenames.
- //
- // As reported by a customer, iOS sometimes (unknown exactly when)
- // does not retain the Exif date but instead puts it in the filename
- // in a format like `20230427_145116000_iOS.jpg`, and that Apple
- // Photos can parse it back from there.
- //
- // I couldn't find more official documentation from a quick look,
- // but there do seem to be other people on the internet
- // corraborating this:
- //
- // > iOS 11, (older versions do the same thing), when I take a photo
- // > or video, the filename consists of the following:
- // > 20170923_220934000_iOS ... file name is based on UTC/GMT time.
- // >
- // > https://discussions.apple.com/thread/8087977
-
- const p = name.split("_");
- if (p.length == 3) {
- const dateString = `${p[0]}-${p[1]}`;
- date = parseDateFromFusedDateString(dateString);
- }
- }
- }
-
- // Generic pattern.
- if (!date) {
- date = parseDateFromDigitGroups(fileName);
- }
-
- // Ignore invalid.
- if (!date || isNaN(date.getTime())) {
- return undefined;
- }
-
- // Convert to epoch microseconds.
- const unixTime = date.getTime() * 1000;
- if (unixTime === Date.UTC(0, 0, 0, 0, 0, 0, 0) || unixTime === 0) {
- // Ignore dateTimeStrings of the form "0000:00:00 00:00:00". We do
- // encounter such missing data in the wild.
- return undefined;
- } else if (unixTime > Date.now() * 1000) {
- // We shouldn't be ignoring future dates, but since this is a file name
- // parser, a future date usually indicates that we parsed some unrelated
- // number that shouldn't have been parsed.
- return undefined;
- } else {
- return unixTime;
- }
-};
-
-/**
- * An intermediate data structure we use for the functions in this file. It
- * stores the various components of a JavaScript date.
- *
- * In particular, the month is 0-indexed, as it is for the JavaScript Date's
- * `getMonth`.
- */
-interface DateComponents {
- year: number;
- month: number;
- day: number;
- hour: number;
- minute: number;
- second: number;
-}
-
-/**
- * Parse a date from a string of the form "YYYYMMDD-HHMMSS". Any extra
- * characters at the end are ignored.
- */
-const parseDateFromFusedDateString = (s: string) =>
- validateAndGetDateFromComponents({
- year: Number(s.slice(0, 4)),
- // JavaScript Date's month is 0-indexed.
- month: Number(s.slice(4, 6)) - 1,
- day: Number(s.slice(6, 8)),
- hour: Number(s.slice(9, 11)),
- minute: Number(s.slice(11, 13)),
- second: Number(s.slice(13, 15)),
- });
-
-/**
- * Try to see if we can parse an date from a string with arbitrary separators.
- *
- * For example, consider a string like "2018-08-19 12:34:45". We see if it is
- * possible to extract six symbol separated digit groups from the string. If so,
- * we use them to form a date.
- */
-export const parseDateFromDigitGroups = (s: string) => {
- const [year, month, day, hour, minute, second] = s.match(/\d+/g) ?? [];
-
- // If the filename has 8 consecutive and then 6 consecutive digits, then
- // there is a high possibility that it is a date of the form
- // "YYYYMMDD-HHMMSS".
- if (year?.length == 8 && month?.length == 6) {
- return parseDateFromFusedDateString(year + "-" + month);
- }
-
- return validateAndGetDateFromComponents({
- year: Number(year),
- // JavaScript Date's month is 0-indexed.
- month: Number(month) - 1,
- day: Number(day),
- hour: Number(hour),
- minute: Number(minute),
- second: Number(second),
- });
-};
-
-const validateAndGetDateFromComponents = (components: DateComponents) => {
- let date = dateFromComponents(components);
- if (hasTimeValues(components) && !isTimePartValid(date, components)) {
- // If the date has time values but they are not valid then remove them.
- date = dateFromComponents({
- ...components,
- hour: 0,
- minute: 0,
- second: 0,
- });
- }
- if (!isDatePartValid(date, components)) {
- return undefined;
- }
- if (
- date.getFullYear() < 1990 ||
- date.getFullYear() > new Date().getFullYear() + 1
- ) {
- return undefined;
- }
- return date;
-};
-
-const isDatePartValid = (date: Date, { year, month, day }: DateComponents) =>
- date.getFullYear() === year &&
- date.getMonth() === month &&
- date.getDate() === day;
-
-const isTimePartValid = (
- date: Date,
- { hour, minute, second }: DateComponents,
-) =>
- date.getHours() === hour &&
- date.getMinutes() === minute &&
- date.getSeconds() === second;
-
-const dateFromComponents = (dateComponents: DateComponents) => {
- const { year, month, day, hour, minute, second } = dateComponents;
- if (hasTimeValues(dateComponents)) {
- return new Date(year, month, day, hour, minute, second);
- } else {
- return new Date(year, month, day);
- }
-};
-
-const hasTimeValues = ({ hour, minute, second }: DateComponents) =>
- !isNaN(hour) && !isNaN(minute) && !isNaN(second);
diff --git a/web/apps/albums/src/public-album/upload/pipeline/md5.ts b/web/apps/albums/src/public-album/upload/pipeline/md5.ts
deleted file mode 100644
index 4e4770b6e1..0000000000
--- a/web/apps/albums/src/public-album/upload/pipeline/md5.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-/**
- * Minimal MD5 implementation tailored for computing a base64 encoded checksum
- * of Uint8Array inputs.
- *
- * The implementation follows RFC 1321.
- */
-
-const shifts = new Uint8Array([
- 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5,
- 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11,
- 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10,
- 15, 21,
-]);
-
-const constants = (() => {
- const k = new Uint32Array(64);
- for (let i = 0; i < 64; i++) {
- k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32);
- }
- return k;
-})();
-
-const leftRotate = (value: number, amount: number) =>
- (value << amount) | (value >>> (32 - amount));
-
-const toUint8ArrayLE = (word: number) => {
- const bytes = new Uint8Array(4);
- bytes[0] = word & 0xff;
- bytes[1] = (word >>> 8) & 0xff;
- bytes[2] = (word >>> 16) & 0xff;
- bytes[3] = (word >>> 24) & 0xff;
- return bytes;
-};
-
-const bytesToBase64 = (bytes: Uint8Array) => {
- if (typeof Buffer != "undefined") {
- return Buffer.from(bytes).toString("base64");
- }
- let binary = "";
- for (const byte of bytes) {
- binary += String.fromCharCode(byte);
- }
- return btoa(binary);
-};
-
-export const computeMd5Base64 = (data: Uint8Array): string => {
- const originalLengthBits = data.length * 8;
- const paddedLength =
- (((data.length + 8) >>> 6) << 4) +
- 16; /* (n + 64) rounded up to multiple of 64 bytes, expressed in 32-bit words */
- const words = new Uint32Array(paddedLength);
-
- for (const [i, value] of data.entries()) {
- const wordIndex = i >> 2;
- const existing = words[wordIndex] ?? 0;
- words[wordIndex] = existing | (value << ((i % 4) * 8));
- }
-
- const paddingIndex = data.length >> 2;
- const paddingExisting = words[paddingIndex] ?? 0;
- words[paddingIndex] = paddingExisting | (0x80 << ((data.length % 4) * 8));
- words[paddedLength - 2] = originalLengthBits & 0xffffffff;
- words[paddedLength - 1] = (originalLengthBits / 0x100000000) | 0;
-
- let a = 0x67452301;
- let b = 0xefcdab89;
- let c = 0x98badcfe;
- let d = 0x10325476;
-
- for (let i = 0; i < words.length; i += 16) {
- let A = a;
- let B = b;
- let C = c;
- let D = d;
-
- for (let j = 0; j < 64; j++) {
- let f: number;
- let g: number;
-
- if (j < 16) {
- f = (B & C) | (~B & D);
- g = j;
- } else if (j < 32) {
- f = (D & B) | (~D & C);
- g = (5 * j + 1) % 16;
- } else if (j < 48) {
- f = B ^ C ^ D;
- g = (3 * j + 5) % 16;
- } else {
- f = C ^ (B | ~D);
- g = (7 * j) % 16;
- }
-
- const temp = D;
- D = C;
- C = B;
- const word = words[i + g] ?? 0;
- const constant = constants[j] ?? 0;
- const shift = shifts[j] ?? 0;
- const sum = (A + f + constant + word) >>> 0;
- B = (B + leftRotate(sum, shift)) >>> 0;
- A = temp;
- }
-
- a = (a + A) >>> 0;
- b = (b + B) >>> 0;
- c = (c + C) >>> 0;
- d = (d + D) >>> 0;
- }
-
- const digest = new Uint8Array(16);
- digest.set(toUint8ArrayLE(a), 0);
- digest.set(toUint8ArrayLE(b), 4);
- digest.set(toUint8ArrayLE(c), 8);
- digest.set(toUint8ArrayLE(d), 12);
-
- return bytesToBase64(digest);
-};
diff --git a/web/apps/albums/src/public-album/upload/pipeline/upload-service.ts b/web/apps/albums/src/public-album/upload/pipeline/upload-service.ts
index fd60b6b1ea..2c182f6807 100644
--- a/web/apps/albums/src/public-album/upload/pipeline/upload-service.ts
+++ b/web/apps/albums/src/public-album/upload/pipeline/upload-service.ts
@@ -1,15 +1,10 @@
// TODO: Audit this file
/* eslint-disable @typescript-eslint/ban-ts-comment */
-import { extractExif } from "@/public-album/media/metadata/exif";
import {
determineVideoDuration,
extractVideoMetadata,
} from "@/public-album/media/processing/ffmpeg";
-import {
- detectFileTypeInfoFromChunk,
- isFileTypeNotSupportedError,
-} from "@/public-album/media/utils/detect-type";
import type { BytesOrB64 } from "ente-base/crypto/types";
import { streamEncryptionChunkSize } from "ente-base/crypto/types";
import { type CryptoWorker } from "ente-base/crypto/worker";
@@ -22,6 +17,13 @@ import {
type PublicAlbumsCredentials,
} from "ente-base/http";
import log from "ente-base/log";
+import { extractExif } from "ente-gallery/services/exif";
+import { tryParseEpochMicrosecondsFromFileName } from "ente-gallery/services/upload/date";
+import { computeMd5Base64 } from "ente-gallery/services/upload/md5";
+import {
+ detectFileTypeInfoFromChunk,
+ isFileTypeNotSupportedError,
+} from "ente-gallery/utils/detect-type";
import { decryptRemoteFile, type EnteFile } from "ente-media/file";
import {
fileFileName,
@@ -47,8 +49,6 @@ import {
type UploadPathPrefix,
type UploadResult,
} from ".";
-import { tryParseEpochMicrosecondsFromFileName } from "./date";
-import { computeMd5Base64 } from "./md5";
import { matchJSONMetadata, type ParsedMetadataJSON } from "./metadata-json";
import {
completeMultipartUpload,
diff --git a/web/apps/albums/src/public-album/viewer/components/CommentsSidebar.tsx b/web/apps/albums/src/public-album/viewer/components/CommentsSidebar.tsx
index 57ad44ec5e..2746e48a57 100644
--- a/web/apps/albums/src/public-album/viewer/components/CommentsSidebar.tsx
+++ b/web/apps/albums/src/public-album/viewer/components/CommentsSidebar.tsx
@@ -10,7 +10,6 @@ import {
getStoredAnonIdentity,
} from "@/public-album/social/api/public-reaction";
import { useBrowserBackClose } from "@/shared/hooks/useBrowserBackClose";
-import { getAvatarColor } from "@/shared/utils/avatar-colors";
import CloseIcon from "@mui/icons-material/Close";
import {
Avatar,
@@ -28,6 +27,7 @@ import {
import { type ModalVisibilityProps } from "ente-base/components/utils/modal";
import type { PublicAlbumsCredentials } from "ente-base/http";
import log from "ente-base/log";
+import { getAvatarColor } from "ente-gallery/utils/avatar-colors";
import type { EnteFile } from "ente-media/file";
import i18n, { t } from "i18next";
import React, {
diff --git a/web/apps/albums/src/public-album/viewer/components/FileInfo.tsx b/web/apps/albums/src/public-album/viewer/components/FileInfo.tsx
index 18d7b81f61..16e10e5ae0 100644
--- a/web/apps/albums/src/public-album/viewer/components/FileInfo.tsx
+++ b/web/apps/albums/src/public-album/viewer/components/FileInfo.tsx
@@ -1,8 +1,3 @@
-import {
- tagNumericValue,
- type RawExifTags,
-} from "@/public-album/media/metadata/exif";
-import { formattedByteSize } from "@/shared/utils/byte-size";
import CalendarTodayIcon from "@mui/icons-material/CalendarToday";
import CameraOutlinedIcon from "@mui/icons-material/CameraOutlined";
import LocationOnOutlinedIcon from "@mui/icons-material/LocationOnOutlined";
@@ -30,6 +25,9 @@ import {
} from "ente-base/components/utils/modal";
import { formattedDate, formattedTime } from "ente-base/i18n-date";
import type { Location } from "ente-base/types";
+import { CopyButton } from "ente-gallery/components/FileInfoComponents";
+import { tagNumericValue, type RawExifTags } from "ente-gallery/services/exif";
+import { formattedByteSize } from "ente-gallery/utils/units";
import type { EnteFile } from "ente-media/file";
import {
fileCreationPhotoDate,
@@ -40,7 +38,6 @@ import {
import { FileType } from "ente-media/file-type";
import { t } from "i18next";
import React, { useMemo } from "react";
-import { CopyButton } from "./FileInfoComponents";
export interface FileInfoExif {
tags: RawExifTags | undefined;
diff --git a/web/apps/albums/src/public-album/viewer/components/FileInfoComponents.tsx b/web/apps/albums/src/public-album/viewer/components/FileInfoComponents.tsx
deleted file mode 100644
index f6d1d05efb..0000000000
--- a/web/apps/albums/src/public-album/viewer/components/FileInfoComponents.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import ContentCopyIcon from "@mui/icons-material/ContentCopy";
-import DoneIcon from "@mui/icons-material/Done";
-import { IconButton, Tooltip, type SvgIconProps } from "@mui/material";
-import { useClipboardCopy } from "ente-base/components/utils/hooks";
-import { t } from "i18next";
-
-interface CopyButtonProps {
- /**
- * The text to copy when the button is clicked.
- */
- text: string;
- /**
- * The size of the icon.
- */
- size?: SvgIconProps["fontSize"];
-}
-
-export const CopyButton: React.FC<CopyButtonProps> = ({ text, size }) => {
- const [copied, handleClick] = useClipboardCopy(text);
-
- const Icon = copied ? DoneIcon : ContentCopyIcon;
-
- return (
- <Tooltip arrow open={copied} title={t("copied")}>
- <IconButton onClick={handleClick} color="secondary">
- <Icon fontSize={size} />
- </IconButton>
- </Tooltip>
- );
-};
diff --git a/web/apps/albums/src/public-album/viewer/components/LikesSidebar.tsx b/web/apps/albums/src/public-album/viewer/components/LikesSidebar.tsx
index 5bed513799..0920d7a693 100644
--- a/web/apps/albums/src/public-album/viewer/components/LikesSidebar.tsx
+++ b/web/apps/albums/src/public-album/viewer/components/LikesSidebar.tsx
@@ -1,7 +1,6 @@
import { downloadManager } from "@/public-album/download/services/download-manager";
import { getStoredAnonIdentity } from "@/public-album/social/api/public-reaction";
import { useBrowserBackClose } from "@/shared/hooks/useBrowserBackClose";
-import { getAvatarColor } from "@/shared/utils/avatar-colors";
import CloseIcon from "@mui/icons-material/Close";
import {
Avatar,
@@ -15,6 +14,7 @@ import {
} from "@mui/material";
import { type ModalVisibilityProps } from "ente-base/components/utils/modal";
import log from "ente-base/log";
+import { getAvatarColor } from "ente-gallery/utils/avatar-colors";
import type { EnteFile } from "ente-media/file";
import { t } from "i18next";
import React, {
diff --git a/web/apps/albums/src/public-album/viewer/components/PublicAlbumSingleFileViewer.tsx b/web/apps/albums/src/public-album/viewer/components/PublicAlbumSingleFileViewer.tsx
index 2e147ba945..0a8d264000 100644
--- a/web/apps/albums/src/public-album/viewer/components/PublicAlbumSingleFileViewer.tsx
+++ b/web/apps/albums/src/public-album/viewer/components/PublicAlbumSingleFileViewer.tsx
@@ -1,7 +1,6 @@
import { LazyNotification } from "@/app/lazy/global-ui";
import { getEnteURL } from "@/public-album/access/utils/external-links";
import { downloadManager } from "@/public-album/download/services/download-manager";
-import type { AddSaveGroup } from "@/shared/state/save-groups";
import CheckIcon from "@mui/icons-material/Check";
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import DownloadOutlinedIcon from "@mui/icons-material/DownloadOutlined";
@@ -27,12 +26,13 @@ import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";
import { useBaseContext } from "ente-base/context";
import type { PublicAlbumsCredentials } from "ente-base/http";
import log from "ente-base/log";
+import type { AddSaveGroup } from "ente-gallery/components/utils/save-groups";
+import { createPSRegisterElementIconHTML } from "ente-gallery/components/viewer/icons";
import type { EnteFile } from "ente-media/file";
import { fileFileName } from "ente-media/file-metadata";
import { FileType } from "ente-media/file-type";
import { t } from "i18next";
import { useCallback, useEffect, useMemo, useState } from "react";
-import { createPSRegisterElementIconHTML } from "../lib/icons";
import { FileViewer } from "./FileViewer";
export interface PublicAlbumSingleFileViewerProps {
diff --git a/web/apps/albums/src/public-album/viewer/components/PublicFeedSidebar.tsx b/web/apps/albums/src/public-album/viewer/components/PublicFeedSidebar.tsx
index 4c99d0a762..c81719034c 100644
--- a/web/apps/albums/src/public-album/viewer/components/PublicFeedSidebar.tsx
+++ b/web/apps/albums/src/public-album/viewer/components/PublicFeedSidebar.tsx
@@ -7,7 +7,6 @@ import {
type PublicFeedReaction,
} from "@/public-album/social/api/public-reaction";
import { useBrowserBackClose } from "@/shared/hooks/useBrowserBackClose";
-import { getAvatarColor } from "@/shared/utils/avatar-colors";
import CloseIcon from "@mui/icons-material/Close";
import {
Avatar,
@@ -24,6 +23,7 @@ import { useInterval } from "ente-base/components/utils/hooks";
import { type ModalVisibilityProps } from "ente-base/components/utils/modal";
import type { PublicAlbumsCredentials } from "ente-base/http";
import log from "ente-base/log";
+import { getAvatarColor } from "ente-gallery/utils/avatar-colors";
import type { EnteFile } from "ente-media/file";
import { FileType } from "ente-media/file-type";
import { t } from "i18next";
diff --git a/web/apps/albums/src/public-album/viewer/lib/data-source.ts b/web/apps/albums/src/public-album/viewer/lib/data-source.ts
index 8a951cf5b5..46fdc2925d 100644
--- a/web/apps/albums/src/public-album/viewer/lib/data-source.ts
+++ b/web/apps/albums/src/public-album/viewer/lib/data-source.ts
@@ -1,11 +1,11 @@
import { downloadManager } from "@/public-album/download/services/download-manager";
-import { extractRawExif, parseExif } from "@/public-album/media/metadata/exif";
import {
hlsPlaylistDataForFile,
type HLSPlaylistDataForFile,
} from "@/public-album/media/video/preview";
import type { FileInfoExif } from "@/public-album/viewer/components/FileInfo";
import log from "ente-base/log";
+import { extractRawExif, parseExif } from "ente-gallery/services/exif";
import type { EnteFile } from "ente-media/file";
import { FileType } from "ente-media/file-type";
import { ensureString } from "ente-utils/ensure";
diff --git a/web/apps/albums/src/public-album/viewer/lib/icons.tsx b/web/apps/albums/src/public-album/viewer/lib/icons.tsx
deleted file mode 100644
index 562a049f1d..0000000000
--- a/web/apps/albums/src/public-album/viewer/lib/icons.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-/**
- * @file [Note: SVG paths of MUI icons]
- *
- * When creating buttons for use with PhotoSwipe, we need to provide just the
- * contents of the SVG element (e.g. paths) as an HTML string.
- *
- * Since we only need a handful, these strings were created by temporarily
- * adding the following code in some existing React component to render the
- * corresponding MUI icon React component to a string, and retain the path.
- *
- *
- * import { renderToString } from "react-dom/server";
- * import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
- *
- * console.log(renderToString(<InfoOutlinedIcon />));
- */
-
-// The transforms are not part of the originals, they have been applied
-// separately to get these icons to align with the ones built into PhotoSwipe.
-const paths = {
- // "@mui/icons-material/ErrorOutline"
- error: '<path d="M11 15h2v2h-2zm0-8h2v6h-2zm.99-5C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8" transform="translate(7, 5.7) scale(0.85)"',
- // Custom heart outline icon (30x26 viewBox)
- heart: '<path d="M12.4926 23.4794C8.64537 20.6025 1.02344 14.0254 1.02344 8.10676C1.02344 4.19475 3.89425 1.02344 7.84162 1.02344C9.88707 1.02344 11.9325 1.70526 14.6598 4.43253C17.3871 1.70526 19.4325 1.02344 21.478 1.02344C25.4253 1.02344 28.2962 4.19475 28.2962 8.10676C28.2962 14.0254 20.6743 20.6025 16.827 23.4794C15.5324 24.4474 13.7872 24.4474 12.4926 23.4794Z" stroke="white" stroke-width="2.04545" stroke-linecap="round" stroke-linejoin="round" fill="none"',
- // Custom heart filled icon (30x26 viewBox) - green fill for liked state
- "heart-fill":
- '<path d="M12.4926 23.4794C8.64537 20.6025 1.02344 14.0254 1.02344 8.10676C1.02344 4.19475 3.89425 1.02344 7.84162 1.02344C9.88707 1.02344 11.9325 1.70526 14.6598 4.43253C17.3871 1.70526 19.4325 1.02344 21.478 1.02344C25.4253 1.02344 28.2962 4.19475 28.2962 8.10676C28.2962 14.0254 20.6743 20.6025 16.827 23.4794C15.5324 24.4474 13.7872 24.4474 12.4926 23.4794Z" stroke="#22c55e" stroke-width="2.04545" stroke-linecap="round" stroke-linejoin="round" fill="#22c55e"',
- // Custom comment bubble icon (28x28 viewBox, scaled to match heart)
- comment:
- '<path d="M13.636 25.9087C16.0633 25.9087 18.4361 25.189 20.4544 23.8404C22.4726 22.4919 24.0456 20.5751 24.9745 18.3326C25.9034 16.09 26.1465 13.6224 25.6729 11.2417C25.1994 8.86105 24.0305 6.67426 22.3141 4.95788C20.5978 3.24151 18.411 2.07265 16.0303 1.5991C13.6496 1.12556 11.182 1.3686 8.93944 2.29749C6.69689 3.22639 4.78015 4.79941 3.43161 6.81765C2.08306 8.83589 1.36328 11.2087 1.36328 13.636C1.36328 15.6651 1.85419 17.5783 2.72692 19.2637L1.36328 25.9087L8.00828 24.5451C9.69373 25.4178 11.6083 25.9087 13.636 25.9087Z" stroke="white" stroke-width="2.04545" stroke-linecap="round" stroke-linejoin="round" fill="none" transform="translate(1.5, 1.5) scale(0.9)"',
- // "@mui/icons-material/AlbumOutlined"
- live: '<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8m0-12.5c-2.49 0-4.5 2.01-4.5 4.5s2.01 4.5 4.5 4.5 4.5-2.01 4.5-4.5-2.01-4.5-4.5-4.5m0 5.5c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1" transform="translate(2, 8.7) scale(0.75)"',
- // "@mui/icons-material/VolumeUp"
- vol: '<path d="M3 9v6h4l5 5V4L7 9zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02M14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77" transform="translate(0, 9) scale(0.75)"',
- // Custom star icon (outline)
- favorite:
- '<path d="M8.69381 1.56975C9.38617 0.609562 10.7995 0.609562 11.4919 1.56975L13.7114 4.64784C13.9253 4.9445 14.2255 5.16569 14.5699 5.28031L18.1427 6.46961C19.2572 6.84061 19.6939 8.20365 19.0073 9.16808L16.8062 12.2597C16.5941 12.5577 16.4794 12.9156 16.4783 13.2831L16.4669 17.0962C16.4634 18.2857 15.32 19.1281 14.2033 18.764L10.6234 17.5966C10.2784 17.4841 9.90729 17.4841 9.56228 17.5966L5.98245 18.764C4.86575 19.1281 3.72231 18.2857 3.71876 17.0962L3.70737 13.2831C3.70628 12.9156 3.5916 12.5577 3.37946 12.2597L1.17839 9.16808C0.491785 8.20365 0.928537 6.84061 2.04305 6.46961L5.61584 5.28031C5.96017 5.16569 6.26041 4.9445 6.47432 4.64784L8.69381 1.56975Z" fill="none" stroke="white" stroke-width="1.7" transform="translate(5.5, 6)"',
- // Custom star icon (filled)
- "favorite-fill":
- '<path d="M8.69381 1.56975C9.38617 0.609562 10.7995 0.609562 11.4919 1.56975L13.7114 4.64784C13.9253 4.9445 14.2255 5.16569 14.5699 5.28031L18.1427 6.46961C19.2572 6.84061 19.6939 8.20365 19.0073 9.16808L16.8062 12.2597C16.5941 12.5577 16.4794 12.9156 16.4783 13.2831L16.4669 17.0962C16.4634 18.2857 15.32 19.1281 14.2033 18.764L10.6234 17.5966C10.2784 17.4841 9.90729 17.4841 9.56228 17.5966L5.98245 18.764C4.86575 19.1281 3.72231 18.2857 3.71876 17.0962L3.70737 13.2831C3.70628 12.9156 3.5916 12.5577 3.37946 12.2597L1.17839 9.16808C0.491785 8.20365 0.928537 6.84061 2.04305 6.46961L5.61584 5.28031C5.96017 5.16569 6.26041 4.9445 6.47432 4.64784L8.69381 1.56975Z" transform="translate(5.5, 6)"',
- // "@mui/icons-material/FileDownloadOutlined"
- download:
- '<path d="M18 15v3H6v-3H4v3c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-3zm-1-4-1.41-1.41L13 12.17V4h-2v8.17L8.41 9.59 7 11l5 5z" transform="translate(0, 4)"',
- // "@mui/icons-material/InfoOutlined"
- info: '<path d="M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8" transform="translate(1, 4.5) scale(0.95)"',
- // "@mui/icons-material/MoreHoriz"
- more: '<path d="M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2" transform="translate(0, 4.5)"',
- // "@mui/icons-material/FullscreenOutlined"
- fullscreen:
- '<path d="M7 14H5v5h5v-2H7zm-2-4h2V7h3V5H5zm12 7h-3v2h5v-5h-2zM14 5v2h3v3h2V5z" transform="translate(0, 4.5)"',
- // "@mui/icons-material/FullscreenExitOutlined"
- "fullscreen-exit":
- '<path d="M5 16h3v3h2v-5H5zm3-8H5v2h5V5H8zm6 11h2v-3h3v-2h-5zm2-11V5h-2v5h5V8z" transform="translate(0, 4.5)"',
-};
-
-type IconKeys = Exclude<
- keyof typeof paths,
- "favorite-fill" | "fullscreen-exit"
->;
-
-/**
- * Return an object that can be passed verbatim to the "html" option expected by
- * PhotoSwipe's registerElement function.
- *
- * API docs for registerElement:
- * https://photoswipe.com/adding-ui-elements/#uiregisterelement-api
- *
- * Example:
- *
- * html: {
- * isCustomSVG: true,
- * inner: '<path d="M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8" transform="translate(3.5, 3.5)" id="pswp__icn-info" />',
- * outlineID: "pswp__icn-info",
- * }
- *
- */
-export const createPSRegisterElementIconHTML = (name: IconKeys) => ({
- isCustomSVG: true,
- inner:
- name == "favorite"
- ? favoriteInner()
- : name == "fullscreen"
- ? fullscreenInner()
- : `${paths[name]} id="pswp__icn-${name}" />`,
- outlineID: `pswp__icn-${name}`,
-});
-
-// Favorite is a special case since it consists of two layers: outline and fill.
-const favoriteInner = () => {
- // Main outline (white stroke)
- const outline = `${paths.favorite} id="pswp__icn-favorite" />`;
- // Fill (for favorited state)
- const fill = `${paths["favorite-fill"]} id="pswp__icn-favorite-fill" />`;
- return outline + fill;
-};
-
-// Fullscreen is also a special case since it has two states.
-const fullscreenInner = () =>
- `${paths.fullscreen} id="pswp__icn-fullscreen" />${paths["fullscreen-exit"]} id="pswp__icn-fullscreen-exit" />`;
-
-/**
- * The path of "@mui/icons-material/Settings" as as string.
- *
- * Assumes `viewBox="0 0 24 24"`.
- */
-export const settingsSVGPath = `<path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6"></path>`;
-
-/**
- * The path for the custom heart outline icon.
- *
- * Assumes `viewBox="0 0 30 26"`.
- */
-export const heartSVGPath = paths.heart;
-
-/**
- * The path for the custom heart filled icon (green).
- *
- * Assumes `viewBox="0 0 30 26"`.
- */
-export const heartFillSVGPath = paths["heart-fill"];
-
-/**
- * The path for the custom comment bubble icon.
- *
- * Assumes `viewBox="0 0 28 28"`.
- */
-export const commentSVGPath = paths.comment;
diff --git a/web/apps/albums/src/public-album/viewer/lib/photoswipe.ts b/web/apps/albums/src/public-album/viewer/lib/photoswipe.ts
index 289fd31438..d7b3389a5e 100644
--- a/web/apps/albums/src/public-album/viewer/lib/photoswipe.ts
+++ b/web/apps/albums/src/public-album/viewer/lib/photoswipe.ts
@@ -3,6 +3,13 @@ import {
enteWordmarkViewBox,
} from "ente-base/components/ente-wordmark";
import log from "ente-base/log";
+import {
+ commentSVGPath,
+ createPSRegisterElementIconHTML,
+ heartFillSVGPath,
+ heartSVGPath,
+ settingsSVGPath,
+} from "ente-gallery/components/viewer/icons";
import type { EnteFile } from "ente-media/file";
import { FileType } from "ente-media/file-type";
import "hls-video-element";
@@ -26,13 +33,6 @@ import {
updateFileInfoExifIfNeeded,
type ItemData,
} from "./data-source";
-import {
- commentSVGPath,
- createPSRegisterElementIconHTML,
- heartFillSVGPath,
- heartSVGPath,
- settingsSVGPath,
-} from "./icons";
export interface FileViewerPhotoSwipeDelegate {
/**
diff --git a/web/apps/albums/src/shared/hooks/useFileInput.ts b/web/apps/albums/src/shared/hooks/useFileInput.ts
deleted file mode 100644
index a137b34ad3..0000000000
--- a/web/apps/albums/src/shared/hooks/useFileInput.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-import { useCallback, useEffect, useRef } from "react";
-
-interface UseFileInputParams {
- /**
- * If `true`, the file open dialog will ask the user to select directories.
- * Otherwise it'll ask the user to select files (default).
- */
- directory?: boolean;
- /**
- * If specified, it'll restrict the type of files that the user can select
- * by setting the "accept" attribute of the underlying HTML input element we
- * use to surface the file selector dialog. For value of accept can be an
- * extension or a MIME type (See
- * https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept).
- */
- accept?: string;
- /**
- * A callback that is invoked when the user selects files.
- *
- * It will be passed the list of {@link File}s that the user selected.
- *
- * This will be a list even if the user selected directories - in that case,
- * it will be the recursive list of files within this directory.
- *
- * If the user selected no items, then {@link onCancel} will be invoked.
- */
- onSelect: (selectedFiles: File[]) => void;
- /**
- * A callback that is invoked when the user cancels on the file / directory
- * dialog.
- */
- onCancel: () => void;
-}
-
-interface UseFileInputResult {
- /**
- * A function to call to get the properties that should be passed to a dummy
- * `input` element that needs to be created to anchor the select file
- * dialog. This input HTML element is not going to be visible, but it needs
- * to be part of the DOM for {@link openSelector} to have effect.
- */
- getInputProps: () => React.HTMLAttributes<HTMLInputElement>;
- /**
- * A function that can be called to open the select file / directory dialog.
- */
- openSelector: () => void;
-}
-
-/**
- * Wrap a open file selector into an easy to use package.
- *
- * Returns a {@link UseFileInputResult} which contains a function to get the
- * props for an input element, a function to open the file selector, and the
- * list of selected files.
- *
- * See the documentation of {@link UseFileInputParams} and
- * {@link UseFileInputResult} for more details.
- */
-export const useFileInput = ({
- directory,
- accept,
- onSelect,
- onCancel,
-}: UseFileInputParams): UseFileInputResult => {
- const inputRef = useRef<HTMLInputElement | null>(null);
-
- useEffect(() => {
- // React (as of 19) doesn't support attaching the onCancel event handler
- // via props, so do it using its ref.
- //
- // https://github.com/facebook/react/issues/27858
- inputRef.current!.addEventListener("cancel", onCancel);
- return () => {
- // Use optional chaining to avoid spurious errors during HMR.
- inputRef.current?.removeEventListener("cancel", onCancel);
- };
- }, [onCancel]);
-
- const openSelector = useCallback(() => {
- inputRef.current!.value = "";
- inputRef.current!.click();
- }, []);
-
- const handleChange: React.ChangeEventHandler<HTMLInputElement> = (
- event,
- ) => {
- const files = event.target.files;
- if (files?.length) {
- onSelect([...files]);
- } else {
- onCancel();
- }
- };
-
- // [Note: webkitRelativePath]
- //
- // If the webkitdirectory attribute of an <input> HTML element is set then
- // the File objects that we get will have `webkitRelativePath` property
- // containing the relative path to the selected directory.
- //
- // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory
- //
- // These paths use the POSIX path separator ("/").
- // https://stackoverflow.com/questions/62806233/when-using-webkitrelativepath-is-the-path-separator-operating-system-specific
- //
- const directoryOpts = directory
- ? { directory: "", webkitdirectory: "" }
- : {};
-
- const getInputProps = useCallback(
- () => ({
- type: "file",
- multiple: true,
- style: { display: "none" },
- ...directoryOpts,
- ref: inputRef,
- onChange: handleChange,
- ...(accept && { accept }),
- }),
- [directoryOpts, accept, handleChange],
- );
-
- return { getInputProps, openSelector };
-};
diff --git a/web/apps/albums/src/shared/state/save-groups.ts b/web/apps/albums/src/shared/state/save-groups.ts
deleted file mode 100644
index 9c068085b6..0000000000
--- a/web/apps/albums/src/shared/state/save-groups.ts
+++ /dev/null
@@ -1,248 +0,0 @@
-import { useSyncExternalStore } from "react";
-
-/**
- * An object that keeps track of progress of a user-initiated download of a set
- * of files to the user's device.
- *
- * This "download" is distinct from the downloads the app does from remote (e.g.
- * when the user is viewing them).
- *
- * What we're doing here is perhaps more accurately described "a user initiated
- * download of files to the user's device", but that is too long, so we instead
- * refer to this process as "saving them".
- *
- * Note however that the app's UI itself takes the user perspective, so the
- * upper (UI) layers use the word "download", while this implementation layer
- * uses the word "save", and there is an unavoidable incongruity in the middle.
- */
-export interface SaveGroup {
- /**
- * A randomly generated unique identifier of this set of saves.
- */
- id: number;
- /**
- * A callback to retry the download that created this save group.
- */
- retry?: () => void;
- /**
- * The user visible title of the save group.
- *
- * Depending on the context can either be an auto generated string (e.g "5
- * files"), or the name of the collection which is being downloaded.
- */
- title: string;
- /**
- * If this save group is associated with a {@link CollectionSummary}, then
- * the ID of that collection summary.
- *
- * The {@link SaveGroup} type is also used in the context of the albums app,
- * which does not use or need the concept of link {@link CollectionSummary},
- * we to avoid taking a dependency of the type we store these two relevant
- * properties - {@link collectionSummaryID} and
- * {@link isHiddenCollectionSummary} - inline.
- */
- collectionSummaryID?: number;
- /**
- * `true` if the collection summary associated with the save group is
- * hidden.
- */
- isHiddenCollectionSummary?: boolean;
- /**
- * The path to a directory on the user's file system that was selected by
- * the user to save the files in when they initiated the download on the
- * desktop app.
- *
- * This property is only set when running in the context of the desktop app.
- * The web app downloads to the user's default downloads folder, and when
- * running in the web app this property will not be set.
- */
- downloadDirPath?: string;
- /**
- * The total number of files to save to the user's device.
- */
- total: number;
- /**
- * The number of files that have been saved so far.
- */
- success: number;
- /**
- * The number of failures.
- */
- failed: number;
- /**
- * An {@link AbortController} that can be used to cancel the save.
- */
- canceller: AbortController;
- /**
- * The reason for the failure, if any.
- *
- * This is used to show a more specific error message to the user.
- * - "network_offline": The network went offline during download
- * - "file_error": One or more individual files failed to download
- * - undefined: No specific reason (generic error)
- */
- failureReason?: "network_offline" | "file_error";
- /**
- * `true` when we expect the ZIP download to span multiple parts, so part
- * numbers should be shown from the first part.
- */
- includeZipNumber?: boolean;
- /**
- * `true` when the ZIP file is being downloaded from memory to the user's
- * device. This is only relevant for web downloads where files are first
- * collected into a ZIP in memory, then saved to the device.
- */
- isDownloadingZip?: boolean;
- /**
- * The current ZIP part number being processed. Only relevant for web
- * downloads where files are batched into multiple ZIP parts.
- */
- currentPart?: number;
-}
-
-/**
- * Return `true` if there are no files in this save group that are pending.
- */
-export const isSaveComplete = ({ total, success, failed }: SaveGroup) =>
- total == success + failed;
-
-/**
- * Return `true` if there are no files in this save group that are pending, but
- * one or more files had failed to download.
- */
-export const isSaveCompleteWithErrors = (group: SaveGroup) =>
- group.failed > 0 && isSaveComplete(group);
-
-/**
- * Return `true` if this save was cancelled on a user request.
- */
-export const isSaveCancelled = (group: SaveGroup) =>
- group.canceller.signal.aborted;
-
-/**
- * A function that can be used to add a save group.
- *
- * It returns a function that can subsequently be used to update the save group
- * by applying a transform to it (see {@link UpdateSaveGroup}). The UI will
- * react and update itself on updates done this way.
- */
-export type AddSaveGroup = (
- group: Pick<
- SaveGroup,
- | "title"
- | "collectionSummaryID"
- | "isHiddenCollectionSummary"
- | "downloadDirPath"
- | "total"
- | "includeZipNumber"
- | "canceller"
- | "retry"
- >,
-) => UpdateSaveGroup;
-
-/**
- * A function that can be used to update a instance of a save group by applying
- * the provided transform.
- *
- * This is obtained by a call to an instance of {@link AddSaveGroup}. The UI
- * will update itself to reflect the changes made by the transform.
- */
-export type UpdateSaveGroup = (
- tranform: (prev: SaveGroup) => SaveGroup,
-) => void;
-
-/**
- * A function that can be used to remove a save group.
- *
- * Save groups can be removed both on user actions - if the user presses the
- * close button to discard the notification showing the status of the save group
- * (cancelling it if needed) - or programmatically, if it is found that there
- * are no files that need saving for a particular request.
- */
-export type RemoveSaveGroup = (saveGroup: SaveGroup) => void;
-
-/**
- * Keep save groups outside the component tree so remounts can rehydrate
- * in-progress downloads after route changes.
- */
-type SaveGroupsListener = () => void;
-
-let saveGroupsSnapshot: SaveGroup[] = [];
-const listeners = new Set<SaveGroupsListener>();
-
-// Notify subscribers after the snapshot changes.
-const emitChange = () => {
- for (const listener of listeners) listener();
-};
-
-// Return the current snapshot for external-store consumers.
-const getSnapshot = () => saveGroupsSnapshot;
-
-// Register a listener and return its unsubscribe cleanup.
-const subscribe = (listener: SaveGroupsListener) => {
- listeners.add(listener);
- return () => {
- listeners.delete(listener);
- };
-};
-
-const setSaveGroupsSnapshot = (
- next: SaveGroup[] | ((currentSaveGroups: SaveGroup[]) => SaveGroup[]),
-) => {
- saveGroupsSnapshot =
- typeof next == "function" ? next(saveGroupsSnapshot) : next;
- emitChange();
-};
-
-const addSaveGroup: AddSaveGroup = (saveGroup) => {
- const id = Math.random();
- setSaveGroupsSnapshot((groups) => [
- ...groups,
- { ...saveGroup, id, success: 0, failed: 0 },
- ]);
-
- return (tx: (group: SaveGroup) => SaveGroup) => {
- setSaveGroupsSnapshot((groups) =>
- groups.map((g) => (g.id == id ? tx(g) : g)),
- );
- };
-};
-
-const removeSaveGroup: RemoveSaveGroup = ({ id }) =>
- setSaveGroupsSnapshot((groups) => groups.filter((g) => g.id != id));
-
-export const resetSaveGroups = () => {
- if (!saveGroupsSnapshot.length) return;
-
- saveGroupsSnapshot = [];
- emitChange();
-};
-
-/**
- * A custom React hook that manages a list of active {@link SaveGroup}s, and
- * provides functions to add and remove entries to the list.
- */
-export const useSaveGroups = () => {
- const saveGroups = useSyncExternalStore(
- subscribe,
- getSnapshot,
- getSnapshot,
- );
-
- return {
- saveGroups,
- onAddSaveGroup: addSaveGroup,
- onRemoveSaveGroup: removeSaveGroup,
- };
-};
-
-/**
- * Return save-group actions without subscribing to progress updates.
- *
- * Use this in components that only need to initiate or dismiss downloads,
- * otherwise every save progress update will re-render the caller.
- */
-export const useSaveGroupsActions = () => ({
- onAddSaveGroup: addSaveGroup,
- onRemoveSaveGroup: removeSaveGroup,
-});
diff --git a/web/apps/albums/src/shared/utils/avatar-colors.ts b/web/apps/albums/src/shared/utils/avatar-colors.ts
deleted file mode 100644
index e7c231a6a6..0000000000
--- a/web/apps/albums/src/shared/utils/avatar-colors.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * Avatar colors matching the mobile app's contact colors.
- *
- * These colors are used to give users a consistent colored avatar
- * based on their identifier (email or user ID).
- */
-const avatarColors = [
- "#76549A", // Purple
- "#DF7861", // Coral
- "#94B49F", // Sage green
- "#87A2FB", // Periwinkle blue
- "#C689C6", // Orchid
- "#937DC2", // Soft purple
- "#325288", // Deep blue
- "#85B4E0", // Sky blue
- "#C1A3A3", // Dusty rose
- "#E1A059", // Amber
- "#426165", // Teal
- "#6B77B2", // Slate blue
- "#957FEF", // Violet
- "#DD9DE2", // Pink
- "#82AB8B", // Forest green
- "#9BBBE8", // Light blue
- "#8FBEBE", // Seafoam
- "#8AC3A1", // Mint
- "#A8B0F2", // Lavender
- "#B0C695", // Lime green
- "#E99AAD", // Rose
- "#D18484", // Salmon
- "#78B5A7", // Cyan
-];
-
-/**
- * Get a consistent avatar color for a user based on their email or userName.
- *
- * Uses the same algorithm as the mobile app: the string length modulo the
- * number of available colors determines the color index.
- *
- * @param identifier - The user's email or userName (any string)
- * @returns A hex color string from the avatar colors palette
- */
-export const getAvatarColor = (identifier: string): string => {
- return avatarColors[identifier.length % avatarColors.length]!;
-};
diff --git a/web/apps/albums/src/shared/utils/byte-size.ts b/web/apps/albums/src/shared/utils/byte-size.ts
deleted file mode 100644
index a5961212e5..0000000000
--- a/web/apps/albums/src/shared/utils/byte-size.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { t } from "i18next";
-
-/**
- * Localized unit keys.
- *
- * For each of these, there is expected to be a localized key under
- * "storage_unit". e.g. "storage_unit.tb".
- */
-const units = ["b", "kb", "mb", "gb", "tb"];
-
-/**
- * Convert the given number of {@link bytes} to a user visible string in an
- * appropriately sized unit.
- *
- * The returned string includes the (localized) unit suffix, e.g. "TB".
- *
- * @param precision Modify the number of digits after the decimal point.
- * Defaults to 2.
- */
-export function formattedByteSize(bytes: number, precision = 2): string {
- if (bytes <= 0) return `0 ${t("storage_unit.mb")}`;
-
- const i = Math.min(
- Math.floor(Math.log(bytes) / Math.log(1024)),
- units.length - 1,
- );
- const quantity = bytes / Math.pow(1024, i);
- const unit = units[i];
-
- return `${quantity.toFixed(precision)} ${t(`storage_unit.${unit}`)}`;
-}