π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Reorganize albums app src structure
Anand Baburajan1701af040035
diff --git a/web/apps/albums/src/photos/types/context.ts b/web/apps/albums/src/app/context/albums-app-context.tssimilarity index 51%rename from web/apps/albums/src/photos/types/context.tsrename to web/apps/albums/src/app/context/albums-app-context.tsindex 5c5b75d2ea..cb4639c3f4 100644--- a/web/apps/albums/src/photos/types/context.ts+++ b/web/apps/albums/src/app/context/albums-app-context.ts@@ -1,10 +1,10 @@import { createContext, useContext } from "react";-import type { NotificationAttributes } from "../components/Notification";+import type { NotificationAttributes } from "@/shared/ui/feedback/Notification";/**- * The type of the React context available to all pages in the photos app.+ * The type of the React context available to all pages in the albums app.*/-export interface PhotosAppContextT {+export interface AlbumsAppContextT {/*** Show the global activity indicator (a loading bar at the top of the* page).@@ -15,25 +15,26 @@ export interface PhotosAppContextT {*/hideLoadingBar: () => void;/**- * Show a {@link Notification}, customizing its contents and click behaviour- * using the provided {@link NotificationAttributes}.+ * Show a {@link Notification}, customizing its contents and click+ * behaviour using the provided {@link NotificationAttributes}.*/showNotification: (attributes: NotificationAttributes) => void;}/**- * The React {@link Context} available to all nodes in the React tree of photos+ * The React {@link Context} available to all nodes in the React tree of albums* app pages.*/-export const PhotosAppContext = createContext<PhotosAppContextT | undefined>(+export const AlbumsAppContext = createContext<AlbumsAppContextT | undefined>(undefined,);/**- * Utility hook to get the photos {@link PhotosAppContextT}.+ * Utility hook to get the albums app context.*- * This context is provided at the top level _app component for the photos app,- * and thus is available to all React components in the Photos app's React tree.+ * This context is provided at the top level _app component for the albums app,+ * and thus is available to all React components in the albums app's React+ * tree.*/-export const usePhotosAppContext = (): PhotosAppContextT =>- useContext(PhotosAppContext)!;+export const useAlbumsAppContext = (): AlbumsAppContextT =>+ useContext(AlbumsAppContext)!;diff --git a/web/apps/albums/src/public-album/hooks/useNotification.ts b/web/apps/albums/src/app/hooks/useNotification.tssimilarity index 91%rename from web/apps/albums/src/public-album/hooks/useNotification.tsrename to web/apps/albums/src/app/hooks/useNotification.tsindex 7cacad72ce..5d3dc23ae7 100644--- a/web/apps/albums/src/public-album/hooks/useNotification.ts+++ b/web/apps/albums/src/app/hooks/useNotification.ts@@ -1,4 +1,4 @@-import { type NotificationAttributes } from "@/photos/components/Notification";+import { type NotificationAttributes } from "@/shared/ui/feedback/Notification";import { useCallback, useState } from "react";/**diff --git a/web/apps/albums/src/public-album/components/lazy-ui.ts b/web/apps/albums/src/app/lazy/global-ui.tssimilarity index 86%rename from web/apps/albums/src/public-album/components/lazy-ui.tsrename to web/apps/albums/src/app/lazy/global-ui.tsindex f0686d4399..fe52ba20a3 100644--- a/web/apps/albums/src/public-album/components/lazy-ui.ts+++ b/web/apps/albums/src/app/lazy/global-ui.ts@@ -2,7 +2,7 @@ import dynamic from "next/dynamic";export const LazyNotification = dynamic(() =>- import("@/photos/components/Notification").then(+ import("@/shared/ui/feedback/Notification").then(({ Notification }) => Notification,),{ ssr: false },diff --git a/web/apps/albums/src/app/providers/AlbumsAppProviders.tsx b/web/apps/albums/src/app/providers/AlbumsAppProviders.tsxnew file mode 100644index 0000000000..eff38c4fc0--- /dev/null+++ b/web/apps/albums/src/app/providers/AlbumsAppProviders.tsx@@ -0,0 +1,62 @@+import { AlbumsAppContext } from "@/app/context/albums-app-context";+import { useNotification } from "@/app/hooks/useNotification";+import {+ LazyAttributedMiniDialog,+ LazyNotification,+} from "@/app/lazy/global-ui";+import { useLoadingBar } from "@/shared/hooks/useLoadingBar";+import { ThemedLoadingBar } from "@/shared/ui/feedback/ThemedLoadingBar";+import { CssBaseline } from "@mui/material";+import { ThemeProvider } from "@mui/material/styles";+import { staticAppTitle } from "ente-base/app";+import { CustomHeadAlbums } from "ente-base/components/Head";+import { LoadingIndicator } from "ente-base/components/loaders";+import { useAttributedMiniDialog } from "ente-base/components/utils/dialog";+import { useSetupI18n } from "ente-base/components/utils/hooks-app";+import { photosTheme } from "ente-base/components/utils/theme";+import { BaseContext, deriveBaseContext } from "ente-base/context";+import { t } from "i18next";+import { useCallback, useMemo, type PropsWithChildren } from "react";++export const AlbumsAppProviders: React.FC<PropsWithChildren> = ({+ children,+}) => {+ const isI18nReady = useSetupI18n();+ const { showMiniDialog, miniDialogProps } = useAttributedMiniDialog();+ const { showNotification, notificationProps } = useNotification();+ const { loadingBarRef, showLoadingBar, hideLoadingBar } = useLoadingBar();+ const logout = useCallback(() => {+ // Public albums does not maintain a logged-in app session.+ }, []);++ const baseContext = useMemo(+ () => deriveBaseContext({ logout, showMiniDialog }),+ [logout, showMiniDialog],+ );+ const appContext = useMemo(+ () => ({ showLoadingBar, hideLoadingBar, showNotification }),+ [showLoadingBar, hideLoadingBar, showNotification],+ );+ const title = isI18nReady ? t("title_photos") : staticAppTitle;++ return (+ <ThemeProvider theme={photosTheme}>+ <CustomHeadAlbums {...{ title }} />+ <CssBaseline enableColorScheme />++ <ThemedLoadingBar ref={loadingBarRef} />+ {miniDialogProps.open && (+ <LazyAttributedMiniDialog {...miniDialogProps} />+ )}+ {notificationProps.open && (+ <LazyNotification {...notificationProps} />+ )}++ <BaseContext value={baseContext}>+ <AlbumsAppContext value={appContext}>+ {!isI18nReady ? <LoadingIndicator /> : children}+ </AlbumsAppContext>+ </BaseContext>+ </ThemeProvider>+ );+};diff --git a/web/apps/albums/src/public-album/styles/global.css b/web/apps/albums/src/app/styles/global.csssimilarity index 100%rename from web/apps/albums/src/public-album/styles/global.cssrename to web/apps/albums/src/app/styles/global.cssdiff --git a/web/apps/albums/src/public-album/styles/photoswipe.css b/web/apps/albums/src/app/styles/photoswipe.csssimilarity index 100%rename from web/apps/albums/src/public-album/styles/photoswipe.cssrename to web/apps/albums/src/app/styles/photoswipe.cssdiff --git a/web/apps/albums/src/gallery/services/files-db.ts b/web/apps/albums/src/gallery/services/files-db.tsdeleted file mode 100644index 5fd423b059..0000000000--- a/web/apps/albums/src/gallery/services/files-db.ts+++ /dev/null@@ -1,269 +0,0 @@-/**- * @file- *- * [Note: Files DB]- *- * Prior to us using idb for accessing IndexedDB, we used localForage (another- * IndexedDB library) for that purpose (See `docs/storage.md` for more context).- *- * Our use of localForage was (and is) limited to:- *- * - A single IndexedDB database named "ente-files" containing- *- * - A single table named "files"- *- * It stored more than files though - files, collections, trash, their- * corresponding sync times, and other bits and bobs related to them.- *- * > Note: File contents themselves are not stored in IndexedDB, only- * > {@link EnteFile}s.- *- * Since we've now switched to idb as our preferred IndexedDB library, the data- * stored in this files table could be considered legacy in a sense. But such- * would be an incorrect characterization - this code has no issues, and it- * stores core data for us (files and collections are as core as it gets).- *- * So this table is not legacy or deprecated, and there is currently no strong- * reason to migrate this data to another IndexedDB table (it works fine as it- * is, really). However we do want to avoid adding more items here, and maybe- * gradually move some of the "bits and bobs" elsewhere (e.g. KV DB).- *- * ---- *- * This file contains the common code and types. Application layer code should- * usually be accessing the app specific files DB by importing the functions- * from the following modules:- *- * - Photos app: `photos-fdb.ts`- * - Public albums app: `public-albums-fdb.ts`- *- * Note that even though both of them refer to the same conceptual "files DB",- * the actual storage is distinct since both the apps run on separate domains- * and so have their separate IndexedDB storage and thus separate files tables.- *- * Still, the key names are distinct to reduce chances of confusion: the public- * albums app stores data in keys prefixed with "public-".- */--import { haveWindow } from "ente-base/env";-import {- CollectionPrivateMagicMetadataData,- CollectionPublicMagicMetadataData,- CollectionShareeMagicMetadataData,- ignore,- RemoteCollectionUser,- RemotePublicURL,-} from "ente-media/collection";-import {- RemoteFileInfo,- RemoteFileObjectAttributes,- transformDecryptedMetadataJSON,- type EnteFile,-} from "ente-media/file";-import {- FileMetadata,- FilePrivateMagicMetadataData,- FilePublicMagicMetadataData,-} from "ente-media/file-metadata";-import type { MagicMetadata } from "ente-media/magic-metadata";-import { nullishToEmpty, nullToUndefined } from "ente-utils/transform";-import localForage from "localforage";-import { z } from "zod";--if (haveWindow()) {- localForage.config({- name: "ente-files",- version: 1.0,- storeName: "files",- });-}--/**- * Reexport localForage for use by (and only by):- * - photos-fdb.ts- * - public-albums-fdb.ts- * - migration.ts- */-export { localForage };--/**- * Return a Zod schema suitable for being used with the various magic metadata- * fields of a file or a collection.- */-const createMagicMetadataSchema = <T extends z.ZodType>(dataSchema: T) =>- z- .object({ version: z.number(), count: z.number(), data: dataSchema })- .nullish()- .transform(nullToUndefined);--/**- * Zod schema for a {@link Collection} stored in our local database.- *- * This is similar to {@link RemoteCollection}, but it differs in that it- * contains the decrypted values instead of the encrypted data and nonce pairs.- * There are also some other minor nullish transforms.- */-const LocalCollection = z- .looseObject({- id: z.number(),- owner: RemoteCollectionUser,- key: z.string(),- name: z.string(),- type: z.string(),- sharees: z- .array(RemoteCollectionUser)- .nullish()- .transform(nullishToEmpty),- publicURLs: z- .array(RemotePublicURL)- .nullish()- .transform(nullishToEmpty),- updationTime: z.number(),- magicMetadata: createMagicMetadataSchema(- CollectionPrivateMagicMetadataData,- ),- pubMagicMetadata: createMagicMetadataSchema(- CollectionPublicMagicMetadataData,- ),- sharedMagicMetadata: createMagicMetadataSchema(- CollectionShareeMagicMetadataData,- ),- })- .transform((c) => {- // Old data stored locally contained fields which are no longer needed.- // Do some zod gymnastics to drop these when reading (so that they're- // not written back the next time). This code was added June 2025,- // 1.7.14-beta, and can be removed after a bit (tag: Migration).- const {- encryptedKey,- keyDecryptionNonce,- encryptedName,- nameDecryptionNonce,- attributes,- isDeleted,- ...rest- } = c;- ignore([- encryptedKey,- keyDecryptionNonce,- encryptedName,- nameDecryptionNonce,- attributes,- isDeleted,- ]);- return rest;- });--export const LocalCollections = z.array(LocalCollection);--/**- * Zod schema for a {@link EnteFile} stored in our local database.- *- * This is similar to {@link RemoteEnteFile}, but it differs in that it contains- * the decrypted values instead of the encrypted data and nonce pairs.- */-const LocalEnteFile = z.looseObject({- id: z.number(),- collectionID: z.number(),- ownerID: z.number(),- key: z.string(),- file: RemoteFileObjectAttributes,- thumbnail: RemoteFileObjectAttributes,- info: RemoteFileInfo.nullish().transform(nullToUndefined),- updationTime: z.number(),- metadata: FileMetadata,- magicMetadata: createMagicMetadataSchema(FilePrivateMagicMetadataData),- pubMagicMetadata: createMagicMetadataSchema(FilePublicMagicMetadataData),-});--export const LocalEnteFiles = z.array(LocalEnteFile);--/**- * Apply transformations when reading files from the DB.- *- * There are two parts to it -- *- * 1. the required part (patching old entries that might be present in the local- * database),- * 2. the optional part (removing some unused fields).- *- * Part 1 ---- *- * Transform metadata in legacy files that might be present in the local- * database. Note that this will not be needed for files that are fetched- * afresh, since the corresponding transform is already done during- * {@link decryptRemoteFile}; this is only for handling potentially items that- * might've been already present locally.- *- * Part 2 ---- *- * Remove unused fields from the file objects when reading them.- *- * This is similar to the transformation we perform when reading collections- * from the database, to discard fields that are no longer forwarded when we- * parse the remote object, and thus will not be present in the local DB either- * when going forward. They might be present for the existing entries in DB- * though, which is why these functions are needed.- *- * However, since unlike collections, we don't route the files through Zod when- * reading. So instead we do it using this function. Effectively, the end result- * should be the same. In any case, doing this cleanup has no functional impact.- *- * Both parts added June 2025, 1.7.14-beta, prune eventually (tag: Migration).- */-export const transformFilesIfNeeded = (files: EnteFile[]) =>- isFilesTransformNeeded(files) ? files.map(transformFile) : files;--// Preflight check to turn the potentially non-trivial overhead (~50ms for 200k-// files if everything runs through transformFile) into an effective no-op-// (2-3ms) for the majority happy paths which don't need any transform.-const isFilesTransformNeeded = (- files: (EnteFile & { isDeleted?: unknown })[],-) =>- !!files.find(- (file) =>- "isDeleted" in file ||- !file.metadata.modificationTime ||- typeof file.metadata.fileType != "number",- );--const transformFile = (file: EnteFile & { isDeleted?: unknown }) => {- const {- isDeleted,- metadata: origMetadata,- magicMetadata,- pubMagicMetadata,- ...rest- } = file;- ignore(isDeleted);- // We live with the cast here since this migration code should eventually be- // removed. The cast is needed because in the original context,- // transformDecryptedMetadataJSON acts on arbitrary JSON objects that have- // not yet been validated to be of type FileMetadata.- const metadata = transformDecryptedMetadataJSON(- file.id,- origMetadata,- ) as FileMetadata;- if (magicMetadata) {- delete (magicMetadata as MagicMetadata & { header?: unknown }).header;- }- if (pubMagicMetadata) {- delete (pubMagicMetadata as MagicMetadata & { header?: unknown })- .header;- }- return {- ...rest,- metadata,- magicMetadata,- pubMagicMetadata,- } satisfies EnteFile;-};--/**- * A convenience Zod schema for a nullish number, with `null`s being transformed- * to `undefined`.- *- * This is convenient when parsing the various timestamps we keep corresponding- * to top level keys in the files DB. Don't use elsewhere!- */-export const LocalTimestamp = z.number().nullish().transform(nullToUndefined);diff --git a/web/apps/albums/src/pages/_app.tsx b/web/apps/albums/src/pages/_app.tsxindex cb06bf077b..d94320b79c 100644--- a/web/apps/albums/src/pages/_app.tsx+++ b/web/apps/albums/src/pages/_app.tsx@@ -1,73 +1,18 @@-import { ThemedLoadingBar } from "@/photos/components/ThemedLoadingBar";-import { useLoadingBar } from "@/photos/components/utils/use-loading-bar";-import { PhotosAppContext } from "@/photos/types/context";-import {- LazyAttributedMiniDialog,- LazyNotification,-} from "@/public-album/components/lazy-ui";-import { useNotification } from "@/public-album/hooks/useNotification";+import { AlbumsAppProviders } from "@/app/providers/AlbumsAppProviders";import "@fontsource-variable/inter";-import { CssBaseline } from "@mui/material";-import { ThemeProvider } from "@mui/material/styles";-import { staticAppTitle } from "ente-base/app";-import { CustomHeadAlbums } from "ente-base/components/Head";-import { LoadingIndicator } from "ente-base/components/loaders";-import { useAttributedMiniDialog } from "ente-base/components/utils/dialog";-import { useSetupI18n } from "ente-base/components/utils/hooks-app";-import { photosTheme } from "ente-base/components/utils/theme";-import { BaseContext, deriveBaseContext } from "ente-base/context";-import { t } from "i18next";import type { AppProps } from "next/app";-import { useCallback, useMemo } from "react";import "photoswipe/dist/photoswipe.css";-import "../public-album/styles/global.css";-import "../public-album/styles/photoswipe.css";+import "@/app/styles/global.css";+import "@/app/styles/photoswipe.css";type AlbumsAppProps = AppProps<Record<string, unknown>>;const App: React.FC<AlbumsAppProps> = ({ Component, pageProps }) => {- const isI18nReady = useSetupI18n();- const { showMiniDialog, miniDialogProps } = useAttributedMiniDialog();- const { showNotification, notificationProps } = useNotification();- const { loadingBarRef, showLoadingBar, hideLoadingBar } = useLoadingBar();- const logout = useCallback(() => {- // Public albums does not maintain a logged-in app session.- }, []);-- const baseContext = useMemo(- () => deriveBaseContext({ logout, showMiniDialog }),- [logout, showMiniDialog],- );- const appContext = useMemo(- () => ({ showLoadingBar, hideLoadingBar, showNotification }),- [showLoadingBar, hideLoadingBar, showNotification],- );- const title = isI18nReady ? t("title_photos") : staticAppTitle;-return (- <ThemeProvider theme={photosTheme}>- <CustomHeadAlbums {...{ title }} />- <CssBaseline enableColorScheme />-- <ThemedLoadingBar ref={loadingBarRef} />- {miniDialogProps.open && (- <LazyAttributedMiniDialog {...miniDialogProps} />- )}- {notificationProps.open && (- <LazyNotification {...notificationProps} />- )}-- <BaseContext value={baseContext}>- <PhotosAppContext value={appContext}>- {!isI18nReady ? (- <LoadingIndicator />- ) : (- <Component {...pageProps} />- )}- </PhotosAppContext>- </BaseContext>- </ThemeProvider>+ <AlbumsAppProviders>+ <Component {...pageProps} />+ </AlbumsAppProviders>);};diff --git a/web/apps/albums/src/pages/index.tsx b/web/apps/albums/src/pages/index.tsxindex eef070ed26..f65096b270 100644--- a/web/apps/albums/src/pages/index.tsx+++ b/web/apps/albums/src/pages/index.tsx@@ -1,1246 +1 @@-// TODO: Audit this file (too many null assertions + other issues)-/* eslint-disable @typescript-eslint/no-floating-promises */-import type { FullScreenDropZoneProps } from "@/gallery/components/FullScreenDropZone";-import {- useSaveGroupsActions,- type AddSaveGroup,-} from "@/gallery/components/utils/save-groups";-import { type FileViewerInitialSidebar } from "@/gallery/components/viewer/FileViewer";-import { LazyPublicFeedSidebar } from "@/gallery/components/viewer/lazy";-import { type PublicFeedItemClickInfo } from "@/gallery/components/viewer/PublicFeedSidebar";-import { setPublicAlbumsCredentials } from "@/gallery/services/public-albums-credentials";-import { sortFiles } from "@/gallery/utils/file";-import {- GalleryItemsHeaderAdapter,- GalleryItemsSummary,-} from "@/photos/components/gallery/ListHeader";-import { usePhotosAppContext } from "@/photos/types/context";-import { ActiveDownloadStatusNotifications } from "@/public-album/components/ActiveDownloadStatusNotifications";-import { FeedIcon } from "@/public-album/components/Collections/FeedIcon";-import { type FileListHeaderOrFooter } from "@/public-album/components/FileList";-import { FileListWithViewer } from "@/public-album/components/FileListWithViewer";-import { LazyNotification } from "@/public-album/components/lazy-ui";-import type { PasswordUnlockScreenProps } from "@/public-album/components/PasswordUnlockScreen";-import type { PublicAlbumSingleFileViewerProps } from "@/public-album/components/PublicAlbumSingleFileViewer";-import type { TripLayoutProps } from "@/public-album/components/TripLayout";-import type { UploadProps } from "@/public-album/components/Upload";-import {- getSelectedFiles,- type SelectedState,-} from "@/public-album/utils/file";-import { getEnteURL } from "@/public-album/utils/public-album";-import { quickLinkDateRangeForFiles } from "@/public-album/utils/quick-link";-import {- Download01Icon,- ImageAdd02Icon,- Share08Icon,-} from "@hugeicons/core-free-icons";-import { HugeiconsIcon } from "@hugeicons/react";-import CheckIcon from "@mui/icons-material/Check";-import CloseIcon from "@mui/icons-material/Close";-import {- Box,- Button,- IconButton,- Stack,- styled,- Tooltip,- useMediaQuery,-} from "@mui/material";-import Typography from "@mui/material/Typography";-import { SpacedRow, Stack100vhCenter } from "ente-base/components/containers";-import { EnteLogo } from "ente-base/components/EnteLogo";-import {- LoadingIndicator,- TranslucentLoadingOverlay,-} from "ente-base/components/loaders";-import type { ButtonishProps } from "ente-base/components/mui";-import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";-import { NavbarBase } from "ente-base/components/Navbar";-import { useIsSmallWidth } from "ente-base/components/utils/hooks";-import { useModalVisibility } from "ente-base/components/utils/modal";-import { useBaseContext } from "ente-base/context";-import {- isHTTP401Error,- isHTTPErrorWithStatus,- type PublicAlbumsCredentials,-} from "ente-base/http";-import log from "ente-base/log";-import {- albumsAppOrigin,- isCustomAlbumsAppOrigin,- isOfficialAlbumsApp,- photosAppOrigin,-} from "ente-base/origins";-import type { Collection } from "ente-media/collection";-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 dynamic from "next/dynamic";-import { useRouter } from "next/router";-import {- useCallback,- useEffect,- useMemo,- useRef,- useState,- type ComponentType,- type PropsWithChildren,-} from "react";-import { type FileWithPath } from "react-dropzone";--const LazyPublicAlbumSingleFileViewer =- dynamic<PublicAlbumSingleFileViewerProps>(- () =>- import(- "@/public-album/components/PublicAlbumSingleFileViewer"- ).then(- ({ PublicAlbumSingleFileViewer }) =>- PublicAlbumSingleFileViewer,- ),- { ssr: false, loading: () => <LoadingIndicator /> },- );--const LazyTripLayout = dynamic<TripLayoutProps>(- () =>- import("@/public-album/components/TripLayout").then(- ({ TripLayout }) => TripLayout,- ),- { ssr: false, loading: () => <LoadingIndicator /> },-);--const LazyUpload = dynamic<UploadProps>(- () =>- import("@/public-album/components/Upload").then(({ Upload }) => Upload),- { ssr: false },-);--const LazyPasswordUnlockScreen = dynamic<PasswordUnlockScreenProps>(- () =>- import("@/public-album/components/PasswordUnlockScreen").then(- ({ PasswordUnlockScreen }) => PasswordUnlockScreen,- ),- { ssr: false, loading: () => <LoadingIndicator /> },-);--const loadPublicAlbumsFDB = () => import("@/albums/services/public-albums-fdb");--const loadPublicCollectionService = () =>- import("@/albums/services/public-collection");--const loadShareService = () => import("@/gallery/services/share");--const loadJoinPublicAlbumRedirect = () =>- import("@/public-album/services/join-public-album-redirect");--const publicAlbumAllFilesCollectionID = 0;--export default function PublicCollectionGallery() {- const { showMiniDialog, onGenericError } = useBaseContext();- const { showLoadingBar, hideLoadingBar } = usePhotosAppContext();-- const [publicCollection, setPublicCollection] = useState<- Collection | undefined- >(undefined);- const [publicFiles, setPublicFiles] = useState<EnteFile[] | undefined>(- undefined,- );- const [errorMessage, setErrorMessage] = useState<string>("");- const [loading, setLoading] = useState(true);- const [isPasswordProtected, setIsPasswordProtected] = useState(false);- const [uploadTypeSelectorView, setUploadTypeSelectorView] = useState(false);- const [blockingLoad, setBlockingLoad] = useState(false);- const [shouldDisableDropzone, setShouldDisableDropzone] = useState(false);- const [isUploadInProgress, setIsUploadInProgress] = useState(false);- const [shouldRenderUpload, setShouldRenderUpload] = useState(false);- const [dragAndDropFiles, setDragAndDropFiles] = useState<FileWithPath[]>(- [],- );- const [selected, setSelected] = useState<SelectedState>({ count: 0 });-- // TODO: Can we convert these to state- const credentials = useRef<PublicAlbumsCredentials | undefined>(undefined);- const collectionKey = useRef<string | undefined>(undefined);-- const isRedirectingToAlbumsAppRef = useRef<boolean>(false);-- const { onAddSaveGroup } = useSaveGroupsActions();- const { show: showPublicFeed, props: publicFeedVisibilityProps } =- useModalVisibility();-- // Pending navigation from feed item click- const [pendingFileNavigation, setPendingFileNavigation] = useState<{- fileIndex: number;- sidebar?: FileViewerInitialSidebar;- commentID?: string;- }>();-- /**- * Handle clicks on feed items to navigate to the file and open sidebar.- */- const handleFeedItemClick = (info: PublicFeedItemClickInfo) => {- if (!publicFiles) return;-- // Find the file index in publicFiles- const fileIndex = publicFiles.findIndex((f) => f.id === info.fileID);- if (fileIndex === -1) return;-- // Close the feed sidebar- publicFeedVisibilityProps.onClose();-- // Determine which sidebar to open- const sidebar: FileViewerInitialSidebar =- info.type === "liked_photo" || info.type === "liked_video"- ? "likes"- : "comments";-- // Set navigation state- setPendingFileNavigation({- fileIndex,- sidebar,- commentID: info.commentID,- });- };-- const router = useRouter();-- const showPublicLinkExpiredMessage = () =>- showMiniDialog({- title: t("link_expired"),- message: t("link_expired_message"),- nonClosable: true,- continue: {- text: t("login"),- action: async () => {- if (isOfficialAlbumsApp) {- window.location.href = photosAppOrigin();- return;- }- await router.push("/");- },- },- cancel: false,- });-- /**- * Check if we need to redirect Trip albums from custom domains to albums.ente.io- * Returns true if a redirect was initiated, false otherwise.- * Reason: custom domains do not support the Trip layout fully- */- const checkAndRedirectForTripAlbum = (collection: Collection): boolean => {- if (- collection.pubMagicMetadata?.data.layout === "trip" &&- isOfficialAlbumsApp- ) {- const currentURL = new URL(window.location.href);- const albumsURL = new URL(albumsAppOrigin());-- if (currentURL.host !== albumsURL.host) {- isRedirectingToAlbumsAppRef.current = true;-- albumsURL.search = currentURL.search;- albumsURL.hash = currentURL.hash;-- window.location.href = albumsURL.href;- return true;- }- }- return false;- };-- useEffect(() => {- /**- * Determine credentials, read the locally cached state, then start- * pulling the latest from remote.- */- const main = async () => {- let redirectingToWebsite = false;- try {- const currentURL = new URL(window.location.href);- const t = currentURL.searchParams.get("t");- const [- { extractCollectionKeyFromShareURL },- {- savedPublicCollectionAccessTokenJWT,- savedPublicCollectionByKey,- savedPublicCollectionFiles,- },- ] = await Promise.all([- loadShareService(),- loadPublicAlbumsFDB(),- ]);- const ck = await extractCollectionKeyFromShareURL(currentURL);- if (!t && !ck) {- // Only redirect to ente.com if this is NOT a custom/self-hosted instance- if (!isCustomAlbumsAppOrigin) {- window.location.href = "https://ente.com";- redirectingToWebsite = true;- }- }- if (!t || !ck) {- return;- }- collectionKey.current = ck;- const collection = await savedPublicCollectionByKey(ck);- const accessToken = t;- let accessTokenJWT: string | undefined;- if (collection) {- setPublicCollection(collection);- setIsPasswordProtected(- !!collection.publicURLs[0]?.passwordEnabled,- );- setPublicFiles(- sortFilesForCollection(- await savedPublicCollectionFiles(accessToken),- collection,- ),- );- accessTokenJWT =- await savedPublicCollectionAccessTokenJWT(accessToken);- }- credentials.current = { accessToken, accessTokenJWT };- setPublicAlbumsCredentials(credentials.current);- await publicAlbumsRemotePull();- } finally {- if (- !redirectingToWebsite &&- !isRedirectingToAlbumsAppRef.current- ) {- setLoading(false);- }- }- };- main();- // TODO:- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- const downloadEnabled =- publicCollection?.publicURLs[0]?.enableDownload ?? true;- const collectEnabled =- publicCollection?.publicURLs[0]?.enableCollect ?? false;-- useEffect(() => {- if (!collectEnabled) return;- void import("@/gallery/services/upload").then(- ({ updateShouldDisableCFUploadProxy }) =>- updateShouldDisableCFUploadProxy(),- );- }, [collectEnabled]);-- useEffect(() => {- if (- uploadTypeSelectorView ||- dragAndDropFiles.length > 0 ||- isUploadInProgress- ) {- setShouldRenderUpload(true);- }- }, [dragAndDropFiles.length, isUploadInProgress, uploadTypeSelectorView]);-- /**- * Pull the latest data related to the public album from remote, updating- * both our local database and component state.- */- const publicAlbumsRemotePull = useCallback(async () => {- const accessToken = credentials.current!.accessToken;- showLoadingBar();- setLoading(true);- try {- const [- {- pullCollection,- pullPublicCollectionFiles,- removePublicCollectionFileData,- },- { removePublicCollectionAccessTokenJWT },- ] = await Promise.all([- loadPublicCollectionService(),- loadPublicAlbumsFDB(),- ]);- const { collection } = await pullCollection(- accessToken,- collectionKey.current!,- );-- if (checkAndRedirectForTripAlbum(collection)) {- return;- }-- setPublicCollection(collection);- const isPasswordProtected =- !!collection.publicURLs[0]?.passwordEnabled;- setIsPasswordProtected(isPasswordProtected);- setErrorMessage("");-- // Remove the locally cached accessTokenJWT if the sharer has- // disabled password protection on the link.- if (!isPasswordProtected && credentials.current?.accessTokenJWT) {- credentials.current.accessTokenJWT = undefined;- setPublicAlbumsCredentials(credentials.current);- removePublicCollectionAccessTokenJWT(accessToken);- }-- if (isPasswordProtected && !credentials.current?.accessTokenJWT) {- await removePublicCollectionFileData(accessToken);- } else {- try {- await pullPublicCollectionFiles(- credentials.current!,- collection,- (files) =>- setPublicFiles(- sortFilesForCollection(files, collection),- ),- );- } catch (e) {- // If we reached the try block and attempted to pull files,- // it means the accessToken itself is very likely valid- // (since the `pullCollection` succeeded just a moment ago).- //- // So a 401 Unauthorized now indicates that the- // accessTokenJWT is no longer valid since the sharer has- // changed the password.- //- // Clear the locally cached accessTokenJWT and ask the user- // to reenter the password.- if (isHTTP401Error(e)) {- credentials.current!.accessTokenJWT = undefined;- setPublicAlbumsCredentials(credentials.current);- } else {- throw e;- }- }- }- } catch (e) {- // The 410 Gone or 429 Rate limited can arise from either the- // collection pull or the files pull since they're part of the- // remote's access token check sequence.- //- // In practice, it almost always will be a consequence of the- // collection pull since it happens first.- //- // The 401 Unauthorized can only arise from the collection pull- // since we already handle that separately for the files pull.- if (- isHTTPErrorWithStatus(e, 401) ||- isHTTPErrorWithStatus(e, 410) ||- isHTTPErrorWithStatus(e, 429)- ) {- const [- { removePublicCollectionFileData },- { removePublicCollectionByKey },- ] = await Promise.all([- loadPublicCollectionService(),- loadPublicAlbumsFDB(),- ]);- setErrorMessage(- isHTTPErrorWithStatus(e, 429)- ? t("link_request_limit_exceeded")- : t("link_expired_message"),- );- // Sharing has been disabled. Clear out local cache.- await removePublicCollectionFileData(accessToken);- await removePublicCollectionByKey(collectionKey.current!);- setPublicCollection(undefined);- setPublicFiles(undefined);- } else {- log.error("Public album remote pull failed", e);- // Don't use the `setErrorMessage`, show a dialog instead,- // because this might be a transient network error.- onGenericError(e);- }- } finally {- hideLoadingBar();- if (!isRedirectingToAlbumsAppRef.current) {- setLoading(false);- }- }- }, [showLoadingBar, hideLoadingBar, onGenericError]);-- // See: [Note: Visual feedback to acknowledge user actions]- const handleVisualFeedback = useCallback(() => {- showLoadingBar();- setTimeout(hideLoadingBar, 0);- }, [showLoadingBar, hideLoadingBar]);-- const handleJoinAlbum = useCallback(() => {- const accessToken = credentials.current?.accessToken;- const currentCollectionKey = collectionKey.current;-- if (!publicCollection || !accessToken || !currentCollectionKey) {- return;- }-- void loadJoinPublicAlbumRedirect().then(- ({ joinPublicAlbumViaRedirect }) =>- joinPublicAlbumViaRedirect({- publicCollection,- accessToken,- collectionKey: currentCollectionKey,- credentials,- }),- );- }, [publicCollection]);-- const handleSubmitPassword: PasswordUnlockScreenProps["onSubmit"] = async (- password,- setFieldError,- ) => {- try {- const accessToken = credentials.current!.accessToken;- const [- { verifyPublicAlbumPassword },- { savePublicCollectionAccessTokenJWT },- ] = await Promise.all([- import("@/public-album/services/verify-public-album-password"),- loadPublicAlbumsFDB(),- ]);- const accessTokenJWT = await verifyPublicAlbumPassword(- publicCollection!.publicURLs[0]!,- password,- accessToken,- );- credentials.current!.accessTokenJWT = accessTokenJWT;- setPublicAlbumsCredentials(credentials.current);- await savePublicCollectionAccessTokenJWT(- accessToken,- accessTokenJWT,- );- } catch (e) {- log.error("Failed to verifyLinkPassword", e);- if (isHTTP401Error(e)) {- setFieldError(t("incorrect_password"));- return;- }- throw e;- }-- await publicAlbumsRemotePull();- };-- const clearSelection = () => {- if (!selected.count) {- return;- }- setSelected({ count: 0 });- };-- const handleUploadFile = (file: EnteFile) =>- setPublicFiles(- sortFilesForCollection([...publicFiles!, file], publicCollection),- );-- const downloadFilesHelper = async () => {- try {- const { downloadAndSaveFiles } = await import(- "@/gallery/services/save"- );- const selectedFiles = getSelectedFiles(selected, publicFiles!);- const singleFile =- selectedFiles.length === 1 ? selectedFiles[0] : undefined;- const title =- singleFile?.metadata.fileType === FileType.livePhoto- ? fileFileName(singleFile)- : t("files_count", { count: selectedFiles.length });- await downloadAndSaveFiles(selectedFiles, title, onAddSaveGroup);- clearSelection();- } catch (e) {- log.error("failed to download selected files", e);- }- };-- const onAddPhotos = useMemo(() => {- if (!collectEnabled) return undefined;- return () => {- setShouldRenderUpload(true);- setUploadTypeSelectorView(true);- };- }, [collectEnabled]);-- const closeUploadTypeSelectorView = () => {- setUploadTypeSelectorView(false);- };-- const commentsEnabled =- publicCollection?.publicURLs[0]?.enableComment ?? false;- const joinEnabled = publicCollection?.publicURLs[0]?.enableJoin ?? false;- const addPhotosEnabled = collectEnabled;- const handleDrop = useCallback((files: FileWithPath[]) => {- setShouldRenderUpload(true);- setDragAndDropFiles(files);- }, []);-- const hasSelection = selected.count > 0;- const isMobileHeaderLayout = useMediaQuery("(width < 720px)");- const fileListHeaderHeightForViewport = isMobileHeaderLayout- ? fileListHeaderHeightMobile- : fileListHeaderHeight;-- const fileListHeader = useMemo<FileListHeaderOrFooter | undefined>(- () =>- publicCollection && publicFiles- ? {- component: (- <FileListHeader- {...{- publicCollection,- publicFiles,- downloadEnabled,- onAddSaveGroup,- onAddPhotos,- onShowFeed: commentsEnabled- ? showPublicFeed- : undefined,- addPhotosDisabled: isUploadInProgress,- hasSelection,- }}- />- ),- height: fileListHeaderHeightForViewport,- }- : undefined,- [- onAddSaveGroup,- publicCollection,- publicFiles,- downloadEnabled,- showPublicFeed,- commentsEnabled,- onAddPhotos,- isUploadInProgress,- hasSelection,- fileListHeaderHeightForViewport,- ],- );-- const fileListFooter = useMemo<FileListHeaderOrFooter>(- () => ({- component: <FileListFooter />,- height: fileListFooterHeight,- extendToInlineEdges: true,- }),- [],- );-- if (loading && (!publicFiles || !credentials.current)) {- return <LoadingIndicator />;- } else if (errorMessage) {- return (- <Stack100vhCenter>- <Typography- sx={{- color: "critical.main",- px: { xs: 2, sm: 0 },- textAlign: { xs: "center", sm: "inherit" },- }}- >- {errorMessage}- </Typography>- </Stack100vhCenter>- );- } else if (isPasswordProtected && !credentials.current?.accessTokenJWT) {- return <LazyPasswordUnlockScreen onSubmit={handleSubmitPassword} />;- } else if (!publicFiles || !credentials.current) {- return (- <Stack100vhCenter>- <Typography>{t("not_found")}</Typography>- </Stack100vhCenter>- );- }-- const layout = normalizedPublicAlbumLayout(- publicCollection?.pubMagicMetadata?.data.layout,- );- const quickLinkDateRange = quickLinkDateRangeForFiles(publicFiles);- const isQuickLinkAlbum =- quickLinkDateRange !== undefined &&- publicCollection?.name === quickLinkDateRange;- const isSingleFileAlbum = publicFiles.length === 1;- const shouldShowSingleFileViewer = isQuickLinkAlbum && isSingleFileAlbum;-- if (shouldShowSingleFileViewer) {- return (- <>- <LazyPublicAlbumSingleFileViewer- file={publicFiles[0]!}- publicAlbumsCredentials={credentials.current}- collectionKey={collectionKey.current!}- enableDownload={downloadEnabled}- enableComment={commentsEnabled}- enableJoin={publicCollection.publicURLs[0]?.enableJoin}- onJoinAlbum={handleJoinAlbum}- onVisualFeedback={handleVisualFeedback}- onAddSaveGroup={onAddSaveGroup}- />- {blockingLoad && <TranslucentLoadingOverlay />}- <ActiveDownloadStatusNotifications fullWidthOnMobile />- </>- );- }-- const content = (- <>- {layout === "trip" ? (- <LazyTripLayout- files={publicFiles}- collection={publicCollection}- onAddPhotos={onAddPhotos}- enableDownload={downloadEnabled}- accessToken={credentials.current.accessToken}- collectionKey={collectionKey.current}- credentials={credentials}- enableComment={commentsEnabled}- enableJoin={publicCollection?.publicURLs[0]?.enableJoin}- />- ) : (- <>- <NavbarBase- sx={[- {- flex: "0 0 60px",- px: "24px",- "@media (width < 720px)": { px: "4px" },- },- selected.count > 0 && {- borderColor: "accent.main",- overflowX: "hidden",- },- ]}- >- {selected.count > 0 ? (- <SelectedFileOptions- count={selected.count}- clearSelection={clearSelection}- downloadFilesHelper={downloadFilesHelper}- />- ) : (- <SpacedRow sx={{ flex: 1 }}>- <EnteLogoLink href="https://ente.com">- <EnteLogo height={15} />- </EnteLogoLink>- <Stack direction="row" spacing={2}>- <SecondaryActionButton- onAddPhotos={onAddPhotos}- addPhotosDisabled={isUploadInProgress}- enableJoin={joinEnabled}- onJoinAlbum={handleJoinAlbum}- />- <PrimaryActionButton- showJoinAsPrimary={- addPhotosEnabled && joinEnabled- }- onJoinAlbum={handleJoinAlbum}- />- </Stack>- </SpacedRow>- )}- </NavbarBase>- <FileListWithViewer- files={publicFiles}- layout={layout === "masonry" ? "masonry" : "grid"}- header={fileListHeader}- footer={fileListFooter}- enableDownload={downloadEnabled}- enableSelect={downloadEnabled}- selected={selected}- setSelected={setSelected}- activeCollectionID={publicAlbumAllFilesCollectionID}- onAddSaveGroup={onAddSaveGroup}- publicAlbumsCredentials={credentials.current}- collectionKey={collectionKey.current}- onJoinAlbum={handleJoinAlbum}- enableComment={commentsEnabled}- enableJoin={publicCollection?.publicURLs[0]?.enableJoin}- pendingFileIndex={pendingFileNavigation?.fileIndex}- pendingFileSidebar={pendingFileNavigation?.sidebar}- pendingHighlightCommentID={- pendingFileNavigation?.commentID- }- onPendingNavigationConsumed={() =>- setPendingFileNavigation(undefined)- }- />- </>- )}- {blockingLoad && <TranslucentLoadingOverlay />}- {collectEnabled && shouldRenderUpload && (- <LazyUpload- publicAlbumsCredentials={credentials.current}- uploadCollection={publicCollection}- setLoading={setBlockingLoad}- setShouldDisableDropzone={setShouldDisableDropzone}- uploadTypeSelectorView={uploadTypeSelectorView}- onRemotePull={publicAlbumsRemotePull}- onUploadFile={handleUploadFile}- closeUploadTypeSelector={closeUploadTypeSelectorView}- onShowSessionExpiredDialog={showPublicLinkExpiredMessage}- onUploadInProgressChange={setIsUploadInProgress}- {...{ dragAndDropFiles }}- />- )}- <ActiveDownloadStatusNotifications fullWidthOnMobile />- {publicFeedVisibilityProps.open &&- publicCollection &&- collectionKey.current && (- <LazyPublicFeedSidebar- {...publicFeedVisibilityProps}- files={publicFiles}- credentials={credentials.current}- collectionKey={collectionKey.current}- onItemClick={handleFeedItemClick}- />- )}- </>- );-- return (- <LazyCollectDropZone- enabled={collectEnabled}- disabled={shouldDisableDropzone}- onDrop={handleDrop}- message={t("upload_dropzone_hint_public_album")}- >- {content}- </LazyCollectDropZone>- );-}--/**- * Sort the given {@link files} using {@link sortFiles}, using the ascending- * ordering preference if specified in the given {@link collection}'s metadata.- */-const sortFilesForCollection = (files: EnteFile[], collection?: Collection) =>- sortFiles(files, collection?.pubMagicMetadata?.data.asc ?? false);--const normalizedPublicAlbumLayout = (layout: string | undefined) => {- if (layout === "continuous") {- return "masonry";- }- if (layout === "grouped" || layout === "trip" || layout === "masonry") {- return layout;- }- return "masonry";-};--type LazyCollectDropZoneProps = PropsWithChildren<- { enabled: boolean } & Pick<- FullScreenDropZoneProps,- "disabled" | "message" | "onDrop"- >->;--const LazyCollectDropZone: React.FC<LazyCollectDropZoneProps> = ({- enabled,- children,- ...props-}) => {- const [DropZoneComponent, setDropZoneComponent] = useState<ComponentType<- PropsWithChildren<FullScreenDropZoneProps>- > | null>(null);-- useEffect(() => {- if (!enabled || DropZoneComponent) return;-- let isCancelled = false;- void import("@/gallery/components/FullScreenDropZone").then(- ({ FullScreenDropZone }) => {- if (isCancelled) return;- setDropZoneComponent(() => FullScreenDropZone);- },- );-- return () => {- isCancelled = true;- };- }, [DropZoneComponent, enabled]);-- if (!enabled || !DropZoneComponent) {- return <>{children}</>;- }-- return <DropZoneComponent {...props}>{children}</DropZoneComponent>;-};--const EnteLogoLink = styled("a")(({ theme }) => ({- // Remove the excess space at the top.- svg: { verticalAlign: "middle" },- color: theme.vars.palette.text.base,- ":hover": { color: theme.vars.palette.accent.main },-}));--const GreenButton = styled(Button)(() => ({- backgroundColor: "#08C225",- borderRadius: "16px",- paddingBlock: "11px",- paddingInline: "20px",- "&:hover": { backgroundColor: "#07A820" },-}));--const navbarActionButtonSx = { borderRadius: "16px", paddingBlock: "11px" };--type AddPhotosButtonProps = ButtonishProps & { disabled?: boolean };--const AddPhotosButton: React.FC<AddPhotosButtonProps> = ({- onClick,- disabled,-}) => {- const isSmallWidth = useIsSmallWidth();-- return (- <FocusVisibleButton- color="secondary"- startIcon={- isSmallWidth ? undefined : (- <HugeiconsIcon- icon={ImageAdd02Icon}- size={20}- strokeWidth={1.8}- />- )- }- sx={navbarActionButtonSx}- {...{ onClick, disabled }}- >- {t("add_photos")}- </FocusVisibleButton>- );-};--interface PrimaryActionButtonProps {- /** If true, shows "Join Album" as the primary action */- showJoinAsPrimary?: boolean;- onJoinAlbum?: () => void;-}--const PrimaryActionButton: React.FC<PrimaryActionButtonProps> = ({- showJoinAsPrimary,- onJoinAlbum,-}) => {- if (showJoinAsPrimary) {- return (- <GreenButton color="accent" onClick={onJoinAlbum}>- {t("join_album")}- </GreenButton>- );- }-- const handleGetEnte = () => {- window.location.href = getEnteURL();- };-- return (- <GreenButton color="accent" onClick={handleGetEnte}>- {t("try_ente")}- </GreenButton>- );-};--interface SecondaryActionButtonProps {- onAddPhotos?: () => void;- addPhotosDisabled?: boolean;- enableJoin?: boolean;- onJoinAlbum?: () => void;-}--const SecondaryActionButton: React.FC<SecondaryActionButtonProps> = ({- onAddPhotos,- addPhotosDisabled,- enableJoin,- onJoinAlbum,-}) => {- if (onAddPhotos) {- return (- <AddPhotosButton- onClick={onAddPhotos}- disabled={addPhotosDisabled}- />- );- }-- if (enableJoin) {- return (- <FocusVisibleButton- color="secondary"- sx={navbarActionButtonSx}- onClick={onJoinAlbum}- >- {t("join_album")}- </FocusVisibleButton>- );- }-- return null;-};--interface SelectedFileOptionsProps {- count: number;- clearSelection: () => void;- downloadFilesHelper: () => void;-}--const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({- count,- clearSelection,- downloadFilesHelper,-}) => (- <Stack- direction="row"- sx={{- flex: 1,- minWidth: 0,- gap: 1,- alignItems: "center",- width: "100%",- }}- >- <IconButton- onClick={clearSelection}- sx={{ flexShrink: 0, ml: "-15px" }}- >- <CloseIcon />- </IconButton>- <Typography- sx={{- mr: "auto",- minWidth: 0,- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- }}- >- {t("selected_count", { selected: count })}- </Typography>- <Tooltip title={t("download")}>- <IconButton- onClick={downloadFilesHelper}- sx={{ flexShrink: 0, mr: "-15px" }}- >- <HugeiconsIcon icon={Download01Icon} strokeWidth={1.6} />- </IconButton>- </Tooltip>- </Stack>-);--interface FileListHeaderProps {- publicCollection: Collection;- publicFiles: EnteFile[];- downloadEnabled: boolean;- onAddSaveGroup: AddSaveGroup;- onAddPhotos?: () => void;- onShowFeed?: () => void;- addPhotosDisabled: boolean;- hasSelection: boolean;-}--/**- * The fixed height (in px) of {@link FileListHeader}.- */-const fileListHeaderHeight = 84;--/**- * The height (in px) of {@link FileListHeader} on mobile.- *- * Keep this fixed so the virtualized list has a stable header row height.- */-const fileListHeaderHeightMobile = 132;--/**- * A header shown before the listing of files.- *- * It scrolls along with the content. It has a fixed height,- * {@link fileListHeaderHeight}.- */-const FileListHeader: React.FC<FileListHeaderProps> = ({- publicCollection,- publicFiles,- downloadEnabled,- onAddSaveGroup,- onAddPhotos,- onShowFeed,- addPhotosDisabled,- hasSelection,-}) => {- const [showCopiedMessage, setShowCopiedMessage] = useState(false);-- const memoriesDateRange = useMemo(() => {- return quickLinkDateRangeForFiles(publicFiles);- }, [publicFiles]);-- const isQuickLinkAlbum =- memoriesDateRange !== undefined &&- publicCollection.name === memoriesDateRange;-- const downloadAllFiles = () => {- void import("@/gallery/services/save").then(- ({ downloadAndSaveCollectionFiles }) =>- downloadAndSaveCollectionFiles(- publicCollection.name,- publicCollection.id,- publicFiles,- undefined,- onAddSaveGroup,- ),- );- };-- const handleShare = async () => {- if (typeof window === "undefined") return;-- const shareUrl = window.location.href;- const shareText = `${publicCollection.name}\n${shareUrl}`;- const isMobile = window.matchMedia("(width < 720px)").matches;-- if (isMobile && typeof navigator.share === "function") {- try {- await navigator.share({ text: shareText });- return;- } catch (error) {- if (error instanceof Error && error.name === "AbortError") {- return;- }- }- }-- void navigator.clipboard.writeText(isMobile ? shareText : shareUrl);- setShowCopiedMessage(true);- setTimeout(() => setShowCopiedMessage(false), 2000);- };-- return (- <>- <GalleryItemsHeaderAdapter sx={{ pt: "16px" }}>- <SpacedRow- sx={{- width: "100%",- "@media (width < 720px)": {- flexDirection: "column",- alignItems: "flex-start",- gap: 1,- },- }}- >- <Box- sx={{- minWidth: 0,- flex: 1,- "@media (width < 720px)": { width: "100%" },- }}- >- <GalleryItemsSummary- name={publicCollection.name}- fileCount={publicFiles.length}- endIcon={- !isQuickLinkAlbum && memoriesDateRange ? (- <Typography- variant="small"- sx={{ color: "text.muted", ml: "-6px" }}- >- <Box- component="span"- sx={{ mr: "6px" }}- >- {"\u00b7"}- </Box>- {memoriesDateRange}- </Typography>- ) : undefined- }- nameProps={{- noWrap: true,- sx: { width: "100%", maxWidth: "100%" },- }}- />- </Box>- <Stack- direction="row"- spacing={0}- sx={{- alignItems: "center",- "@media (width > 720px)": { mr: -1.5 },- "@media (width < 720px)": { ml: -1.5 },- }}- >- {onShowFeed && (- <IconButton- onClick={onShowFeed}- disabled={hasSelection}- >- <Box- sx={{- width: 24,- height: 24,- display: "flex",- alignItems: "center",- justifyContent: "center",- }}- >- <FeedIcon />- </Box>- </IconButton>- )}- {downloadEnabled && (- <IconButton- onClick={downloadAllFiles}- disabled={hasSelection}- >- <HugeiconsIcon- icon={Download01Icon}- strokeWidth={1.6}- />- </IconButton>- )}- {onAddPhotos && (- <IconButton- onClick={onAddPhotos}- disabled={addPhotosDisabled || hasSelection}- >- <HugeiconsIcon- icon={ImageAdd02Icon}- strokeWidth={1.8}- />- </IconButton>- )}- <IconButton- onClick={handleShare}- disabled={hasSelection}- >- <HugeiconsIcon- icon={Share08Icon}- strokeWidth={1.6}- />- </IconButton>- </Stack>- </SpacedRow>- </GalleryItemsHeaderAdapter>- {showCopiedMessage && (- <LazyNotification- open={showCopiedMessage}- onClose={() => setShowCopiedMessage(false)}- horizontal="left"- attributes={{- color: "secondary",- startIcon: <CheckIcon />,- title: "Copied!",- }}- />- )}- </>- );-};--/**- * The fixed height (in px) of {@link FileListFooter}.- */-const fileListFooterHeight = 24;--/**- * A footer shown after the listing of files.- *- * It scrolls along with the content. It has a fixed height,- * {@link fileListFooterHeight}.- */-const FileListFooter: React.FC = () => (- <Box sx={{ height: fileListFooterHeight }} />-);+export { default } from "@/public-album/page/PublicAlbumPage";diff --git a/web/apps/albums/src/public-album/components/PasswordUnlockScreen.tsx b/web/apps/albums/src/public-album/access/components/PasswordUnlockScreen.tsxsimilarity index 77%rename from web/apps/albums/src/public-album/components/PasswordUnlockScreen.tsxrename to web/apps/albums/src/public-album/access/components/PasswordUnlockScreen.tsxindex 373f6cca10..cf1321b2bb 100644--- a/web/apps/albums/src/public-album/components/PasswordUnlockScreen.tsx+++ b/web/apps/albums/src/public-album/access/components/PasswordUnlockScreen.tsx@@ -1,7 +1,7 @@import {- PublicAccessPageContents,- PublicAccessPageTitle,-} from "@/public-album/components/PublicAccessPage";+ PublicAccessLayout,+ PublicAccessLayoutTitle,+} from "@/public-album/access/components/PublicAccessLayout";import { Stack, Typography } from "@mui/material";import {SingleInputForm,@@ -16,8 +16,8 @@ export interface PasswordUnlockScreenProps {export const PasswordUnlockScreen: React.FC<PasswordUnlockScreenProps> = ({onSubmit,}) => (- <PublicAccessPageContents>- <PublicAccessPageTitle>{t("password")}</PublicAccessPageTitle>+ <PublicAccessLayout>+ <PublicAccessLayoutTitle>{t("password")}</PublicAccessLayoutTitle><Stack><Typography variant="small" sx={{ color: "text.muted", mb: 2 }}>{t("link_password_description")}@@ -30,5 +30,5 @@ export const PasswordUnlockScreen: React.FC<PasswordUnlockScreenProps> = ({onSubmit={onSubmit}/></Stack>- </PublicAccessPageContents>+ </PublicAccessLayout>);diff --git a/web/apps/albums/src/public-album/components/PublicAccessPage.tsx b/web/apps/albums/src/public-album/access/components/PublicAccessLayout.tsxsimilarity index 91%rename from web/apps/albums/src/public-album/components/PublicAccessPage.tsxrename to web/apps/albums/src/public-album/access/components/PublicAccessLayout.tsxindex 67b37b48b4..ba304f70f5 100644--- a/web/apps/albums/src/public-album/components/PublicAccessPage.tsx+++ b/web/apps/albums/src/public-album/access/components/PublicAccessLayout.tsx@@ -3,7 +3,7 @@ import { CenteredFill } from "ente-base/components/containers";import { EnteLogo } from "ente-base/components/EnteLogo";import { NavbarBase } from "ente-base/components/Navbar";-export const PublicAccessPageContents: React.FC<React.PropsWithChildren> = ({+export const PublicAccessLayout: React.FC<React.PropsWithChildren> = ({children,}) => (<Stack@@ -49,7 +49,7 @@ const PublicAccessPagePaper = styled(Paper)(({ theme }) => ({borderRadius: "20px",}));-export const PublicAccessPageTitle: React.FC<React.PropsWithChildren> = ({+export const PublicAccessLayoutTitle: React.FC<React.PropsWithChildren> = ({children,}) => (<Typography variant="h3" sx={{ flex: 1 }}>diff --git a/web/apps/albums/src/public-album/hooks/useJoinAlbum.ts b/web/apps/albums/src/public-album/access/hooks/useJoinAlbum.tssimilarity index 91%rename from web/apps/albums/src/public-album/hooks/useJoinAlbum.tsrename to web/apps/albums/src/public-album/access/hooks/useJoinAlbum.tsindex 3fb2900dd6..f8564c60eb 100644--- a/web/apps/albums/src/public-album/hooks/useJoinAlbum.ts+++ b/web/apps/albums/src/public-album/access/hooks/useJoinAlbum.ts@@ -1,4 +1,4 @@-import { joinPublicAlbumViaRedirect } from "@/public-album/services/join-public-album-redirect";+import { joinPublicAlbumViaRedirect } from "@/public-album/access/services/join-public-album-redirect";import type { PublicAlbumsCredentials } from "ente-base/http";import type { Collection } from "ente-media/collection";import type { RefObject } from "react";diff --git a/web/apps/albums/src/gallery/services/share.ts b/web/apps/albums/src/public-album/access/services/extract-collection-key.tssimilarity index 100%rename from web/apps/albums/src/gallery/services/share.tsrename to web/apps/albums/src/public-album/access/services/extract-collection-key.tsdiff --git a/web/apps/albums/src/public-album/services/join-public-album-redirect.ts b/web/apps/albums/src/public-album/access/services/join-public-album-redirect.tssimilarity index 100%rename from web/apps/albums/src/public-album/services/join-public-album-redirect.tsrename to web/apps/albums/src/public-album/access/services/join-public-album-redirect.tsdiff --git a/web/apps/albums/src/public-album/services/verify-public-album-password.ts b/web/apps/albums/src/public-album/access/services/verify-public-album-password.tssimilarity index 100%rename from web/apps/albums/src/public-album/services/verify-public-album-password.tsrename to web/apps/albums/src/public-album/access/services/verify-public-album-password.tsdiff --git a/web/apps/albums/src/public-album/utils/public-album.ts b/web/apps/albums/src/public-album/access/utils/external-links.tssimilarity index 100%rename from web/apps/albums/src/public-album/utils/public-album.tsrename to web/apps/albums/src/public-album/access/utils/external-links.tsdiff --git a/web/apps/albums/src/public-album/components/FileList.tsx b/web/apps/albums/src/public-album/components/FileList.tsxindex 0b2ae64d1a..ddeefd83ce 100644--- a/web/apps/albums/src/public-album/components/FileList.tsx+++ b/web/apps/albums/src/public-album/components/FileList.tsx@@ -1,13 +1,13 @@-import { thumbnailManager } from "@/gallery/services/thumbnail-manager";+import { thumbnailManager } from "@/public-album/media/thumbnails/thumbnail-manager";import {LoadingThumbnail,StaticThumbnail,-} from "@/photos/components/PlaceholderThumbnails";+} from "@/shared/ui/media/PlaceholderThumbnails";import {computeThumbnailGridLayoutParams,thumbnailGap,type ThumbnailGridLayoutParams,-} from "@/photos/components/utils/thumbnail-grid-layout";+} from "@/shared/utils/thumbnail-grid-layout";import { type SelectedState } from "@/public-album/utils/file";import {handleSelectCreator,diff --git a/web/apps/albums/src/public-album/components/FileListWithViewer.tsx b/web/apps/albums/src/public-album/components/FileListWithViewer.tsxindex ce205a2a59..2c452e72dc 100644--- a/web/apps/albums/src/public-album/components/FileListWithViewer.tsx+++ b/web/apps/albums/src/public-album/components/FileListWithViewer.tsx@@ -1,12 +1,12 @@-import type { AddSaveGroup } from "@/gallery/components/utils/save-groups";+import type { AddSaveGroup } from "@/shared/state/save-groups";import {type FileViewerInitialSidebar,type FileViewerProps,-} from "@/gallery/components/viewer/FileViewer";+} from "@/public-album/viewer/components/FileViewer";import {LazyFileViewer,scheduleFileViewerPreload,-} from "@/gallery/components/viewer/lazy";+} from "@/public-album/viewer/lib/lazy";import { styled } from "@mui/material";import { isSameDay } from "ente-base/date";import { formattedDate } from "ente-base/i18n-date";@@ -148,7 +148,7 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({const handleDownload = useCallback(async (file: EnteFile) => {const { downloadAndSaveFiles } = await import(- "@/gallery/services/save"+ "@/public-album/download/services/save");return downloadAndSaveFiles([file],diff --git a/web/apps/albums/src/public-album/components/TripLayout/MobileNavBar.tsx b/web/apps/albums/src/public-album/components/TripLayout/MobileNavBar.tsxindex 517f678afb..7cd5365d3f 100644--- a/web/apps/albums/src/public-album/components/TripLayout/MobileNavBar.tsx+++ b/web/apps/albums/src/public-album/components/TripLayout/MobileNavBar.tsx@@ -1,7 +1,7 @@-import { FeedIcon } from "@/public-album/components/Collections/FeedIcon";-import { LazyNotification } from "@/public-album/components/lazy-ui";-import { useJoinAlbum } from "@/public-album/hooks/useJoinAlbum";-import { getEnteURL } from "@/public-album/utils/public-album";+import { FeedIcon } from "@/public-album/social/components/FeedIcon";+import { LazyNotification } from "@/app/lazy/global-ui";+import { useJoinAlbum } from "@/public-album/access/hooks/useJoinAlbum";+import { getEnteURL } from "@/public-album/access/utils/external-links";import AddPhotoAlternateOutlinedIcon from "@mui/icons-material/AddPhotoAlternateOutlined";import CheckIcon from "@mui/icons-material/Check";import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";diff --git a/web/apps/albums/src/public-album/components/TripLayout/TopNavButtons.tsx b/web/apps/albums/src/public-album/components/TripLayout/TopNavButtons.tsxindex 696ad51f8c..30f59b8f58 100644--- a/web/apps/albums/src/public-album/components/TripLayout/TopNavButtons.tsx+++ b/web/apps/albums/src/public-album/components/TripLayout/TopNavButtons.tsx@@ -1,7 +1,7 @@-import { FeedIcon } from "@/public-album/components/Collections/FeedIcon";-import { LazyNotification } from "@/public-album/components/lazy-ui";-import { useJoinAlbum } from "@/public-album/hooks/useJoinAlbum";-import { getEnteURL } from "@/public-album/utils/public-album";+import { FeedIcon } from "@/public-album/social/components/FeedIcon";+import { LazyNotification } from "@/app/lazy/global-ui";+import { useJoinAlbum } from "@/public-album/access/hooks/useJoinAlbum";+import { getEnteURL } from "@/public-album/access/utils/external-links";import AddPhotoAlternateOutlinedIcon from "@mui/icons-material/AddPhotoAlternateOutlined";import CheckIcon from "@mui/icons-material/Check";import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";diff --git a/web/apps/albums/src/public-album/components/TripLayout/index.tsx b/web/apps/albums/src/public-album/components/TripLayout/index.tsxindex 67f318b1b8..7a214e840a 100644--- a/web/apps/albums/src/public-album/components/TripLayout/index.tsx+++ b/web/apps/albums/src/public-album/components/TripLayout/index.tsx@@ -1,13 +1,13 @@-import { useSaveGroupsActions } from "@/gallery/components/utils/save-groups";-import { type FileViewerInitialSidebar } from "@/gallery/components/viewer/FileViewer";-import { type PublicFeedItemClickInfo } from "@/gallery/components/viewer/PublicFeedSidebar";+import { useSaveGroupsActions } from "@/shared/state/save-groups";+import { type FileViewerInitialSidebar } from "@/public-album/viewer/components/FileViewer";+import { type PublicFeedItemClickInfo } from "@/public-album/viewer/components/PublicFeedSidebar";import {LazyFileViewer,LazyPublicFeedSidebar,scheduleFileViewerPreload,-} from "@/gallery/components/viewer/lazy";-import { ActiveDownloadStatusNotifications } from "@/public-album/components/ActiveDownloadStatusNotifications";-import { useJoinAlbum } from "@/public-album/hooks/useJoinAlbum";+} from "@/public-album/viewer/lib/lazy";+import { ActiveDownloadStatusNotifications } from "@/public-album/download/components/ActiveDownloadStatusNotifications";+import { useJoinAlbum } from "@/public-album/access/hooks/useJoinAlbum";import { Box, styled, useMediaQuery, useTheme } from "@mui/material";import { useModalVisibility } from "ente-base/components/utils/modal";import type { PublicAlbumsCredentials } from "ente-base/http";@@ -153,7 +153,7 @@ export const TripLayout: React.FC<TripLayoutProps> = ({// Download all files functionalityconst downloadAllFiles = () => {if (!collection) return;- void import("@/gallery/services/save").then(+ void import("@/public-album/download/services/save").then(({ downloadAndSaveCollectionFiles }) =>downloadAndSaveCollectionFiles(collectionTitle,diff --git a/web/apps/albums/src/public-album/components/TripLayout/utils/dataProcessing.ts b/web/apps/albums/src/public-album/components/TripLayout/utils/dataProcessing.tsindex 28cdc43701..7e38cade1a 100644--- a/web/apps/albums/src/public-album/components/TripLayout/utils/dataProcessing.ts+++ b/web/apps/albums/src/public-album/components/TripLayout/utils/dataProcessing.ts@@ -1,4 +1,4 @@-import { downloadManager } from "@/gallery/services/download";+import { downloadManager } from "@/public-album/download/services/download-manager";import { type EnteFile } from "ente-media/file";import {fileCreationTime,diff --git a/web/apps/albums/src/albums/services/public-collection.ts b/web/apps/albums/src/public-album/data/api/public-collection.tssimilarity index 99%rename from web/apps/albums/src/albums/services/public-collection.tsrename to web/apps/albums/src/public-album/data/api/public-collection.tsindex a6af813495..c544d22896 100644--- a/web/apps/albums/src/albums/services/public-collection.ts+++ b/web/apps/albums/src/public-album/data/api/public-collection.ts@@ -27,7 +27,7 @@ import {savePublicCollection,savePublicCollectionFiles,savePublicCollectionLastSyncTime,-} from "./public-albums-fdb";+} from "../storage/public-albums-fdb";/*** Verify with remote that the password entered by the user is the same as thediff --git a/web/apps/albums/src/gallery/services/file-data.ts b/web/apps/albums/src/public-album/data/api/public-file-data.tssimilarity index 98%rename from web/apps/albums/src/gallery/services/file-data.tsrename to web/apps/albums/src/public-album/data/api/public-file-data.tsindex 6407e7b0ae..04d083d6cb 100644--- a/web/apps/albums/src/gallery/services/file-data.ts+++ b/web/apps/albums/src/public-album/data/api/public-file-data.ts@@ -6,7 +6,7 @@ import {import { apiURL } from "ente-base/origins";import { nullToUndefined } from "ente-utils/transform";import { z } from "zod";-import { requirePublicAlbumsCredentials } from "./public-albums-credentials";+import { requirePublicAlbumsCredentials } from "@/public-album/data/auth/public-link-credentials";/*** [Note: File data APIs]diff --git a/web/apps/albums/src/gallery/services/public-albums-credentials.ts b/web/apps/albums/src/public-album/data/auth/public-link-credentials.tssimilarity index 100%rename from web/apps/albums/src/gallery/services/public-albums-credentials.tsrename to web/apps/albums/src/public-album/data/auth/public-link-credentials.tsdiff --git a/web/apps/albums/src/albums/services/public-albums-fdb.ts b/web/apps/albums/src/public-album/data/storage/public-albums-fdb.tssimilarity index 100%rename from web/apps/albums/src/albums/services/public-albums-fdb.tsrename to web/apps/albums/src/public-album/data/storage/public-albums-fdb.tsdiff --git a/web/apps/albums/src/public-album/utils/quick-link.ts b/web/apps/albums/src/public-album/data/utils/quick-link.tssimilarity index 100%rename from web/apps/albums/src/public-album/utils/quick-link.tsrename to web/apps/albums/src/public-album/data/utils/quick-link.tsdiff --git a/web/apps/albums/src/public-album/components/ActiveDownloadStatusNotifications.tsx b/web/apps/albums/src/public-album/download/components/ActiveDownloadStatusNotifications.tsxsimilarity index 93%rename from web/apps/albums/src/public-album/components/ActiveDownloadStatusNotifications.tsxrename to web/apps/albums/src/public-album/download/components/ActiveDownloadStatusNotifications.tsxindex e61cc28f07..f73fbcdd14 100644--- a/web/apps/albums/src/public-album/components/ActiveDownloadStatusNotifications.tsx+++ b/web/apps/albums/src/public-album/download/components/ActiveDownloadStatusNotifications.tsx@@ -1,4 +1,4 @@-import { useSaveGroups } from "@/gallery/components/utils/save-groups";+import { useSaveGroups } from "@/shared/state/save-groups";import dynamic from "next/dynamic";import { type DownloadStatusNotificationsProps } from "./DownloadStatusNotifications";diff --git a/web/apps/albums/src/public-album/components/DownloadStatusNotifications.tsx b/web/apps/albums/src/public-album/download/components/DownloadStatusNotifications.tsxsimilarity index 99%rename from web/apps/albums/src/public-album/components/DownloadStatusNotifications.tsxrename to web/apps/albums/src/public-album/download/components/DownloadStatusNotifications.tsxindex 6ef829963b..3d22e4c01b 100644--- a/web/apps/albums/src/public-album/components/DownloadStatusNotifications.tsx+++ b/web/apps/albums/src/public-album/download/components/DownloadStatusNotifications.tsx@@ -2,8 +2,8 @@ import {isSaveComplete,isSaveCompleteWithErrors,type SaveGroup,-} from "@/gallery/components/utils/save-groups";-import { Notification } from "@/photos/components/Notification";+} from "@/shared/state/save-groups";+import { Notification } from "@/shared/ui/feedback/Notification";import {Download01Icon,Loading03Icon,diff --git a/web/apps/albums/src/gallery/services/download.ts b/web/apps/albums/src/public-album/download/services/download-manager.tssimilarity index 99%rename from web/apps/albums/src/gallery/services/download.tsrename to web/apps/albums/src/public-album/download/services/download-manager.tsindex 8a061e027a..dbd2690f78 100644--- a/web/apps/albums/src/gallery/services/download.ts+++ b/web/apps/albums/src/public-album/download/services/download-manager.ts@@ -17,13 +17,16 @@ import type { EnteFile } from "ente-media/file";import { fileFileName } from "ente-media/file-metadata";import { FileType } from "ente-media/file-type";import { decodeLivePhoto } from "ente-media/live-photo";-import { detectFileTypeInfoFromChunk } from "../utils/detect-type";-import { playableVideoURL, renderableImageBlob } from "./convert";import {getPublicAlbumsCredentials,requirePublicAlbumsCredentials,setPublicAlbumsCredentials,-} from "./public-albums-credentials";+} from "@/public-album/data/auth/public-link-credentials";+import {+ playableVideoURL,+ renderableImageBlob,+} from "@/public-album/media/processing/convert";+import { detectFileTypeInfoFromChunk } from "@/public-album/media/utils/detect-type";/*** URL(s) for the original image or video, alongwith with potential conversionsdiff --git a/web/apps/albums/src/gallery/services/save.ts b/web/apps/albums/src/public-album/download/services/save.tssimilarity index 99%rename from web/apps/albums/src/gallery/services/save.tsrename to web/apps/albums/src/public-album/download/services/save.tsindex cd8041ea4c..58bada8f9c 100644--- a/web/apps/albums/src/gallery/services/save.ts+++ b/web/apps/albums/src/public-album/download/services/save.ts@@ -1,4 +1,8 @@-import { downloadManager } from "@/gallery/services/download";+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";@@ -8,10 +12,6 @@ import { fileFileName } from "ente-media/file-metadata";import { FileType } from "ente-media/file-type";import { decodeLivePhoto } from "ente-media/live-photo";import type JSZip from "jszip";-import type {- AddSaveGroup,- UpdateSaveGroup,-} from "../components/utils/save-groups";/*** Download limits optimized for different devices and browsers.diff --git a/web/apps/albums/src/gallery/services/exif.ts b/web/apps/albums/src/public-album/media/metadata/exif.tssimilarity index 100%rename from web/apps/albums/src/gallery/services/exif.tsrename to web/apps/albums/src/public-album/media/metadata/exif.tsdiff --git a/web/apps/albums/src/gallery/services/convert.ts b/web/apps/albums/src/public-album/media/processing/convert.tssimilarity index 100%rename from web/apps/albums/src/gallery/services/convert.tsrename to web/apps/albums/src/public-album/media/processing/convert.tsdiff --git a/web/apps/albums/src/gallery/services/ffmpeg/constants.ts b/web/apps/albums/src/public-album/media/processing/ffmpeg/constants.tssimilarity index 100%rename from web/apps/albums/src/gallery/services/ffmpeg/constants.tsrename to web/apps/albums/src/public-album/media/processing/ffmpeg/constants.tsdiff --git a/web/apps/albums/src/gallery/services/ffmpeg/index.ts b/web/apps/albums/src/public-album/media/processing/ffmpeg/index.tssimilarity index 100%rename from web/apps/albums/src/gallery/services/ffmpeg/index.tsrename to web/apps/albums/src/public-album/media/processing/ffmpeg/index.tsdiff --git a/web/apps/albums/src/gallery/services/ffmpeg/web.ts b/web/apps/albums/src/public-album/media/processing/ffmpeg/web.tssimilarity index 100%rename from web/apps/albums/src/gallery/services/ffmpeg/web.tsrename to web/apps/albums/src/public-album/media/processing/ffmpeg/web.tsdiff --git a/web/apps/albums/src/gallery/services/thumbnail-crypto.ts b/web/apps/albums/src/public-album/media/thumbnails/thumbnail-crypto.tssimilarity index 100%rename from web/apps/albums/src/gallery/services/thumbnail-crypto.tsrename to web/apps/albums/src/public-album/media/thumbnails/thumbnail-crypto.tsdiff --git a/web/apps/albums/src/gallery/services/thumbnail-crypto.worker.ts b/web/apps/albums/src/public-album/media/thumbnails/thumbnail-crypto.worker.tssimilarity index 100%rename from web/apps/albums/src/gallery/services/thumbnail-crypto.worker.tsrename to web/apps/albums/src/public-album/media/thumbnails/thumbnail-crypto.worker.tsdiff --git a/web/apps/albums/src/gallery/services/thumbnail-manager.ts b/web/apps/albums/src/public-album/media/thumbnails/thumbnail-manager.tssimilarity index 98%rename from web/apps/albums/src/gallery/services/thumbnail-manager.tsrename to web/apps/albums/src/public-album/media/thumbnails/thumbnail-manager.tsindex 0b3c49781f..5da63dfebc 100644--- a/web/apps/albums/src/gallery/services/thumbnail-manager.ts+++ b/web/apps/albums/src/public-album/media/thumbnails/thumbnail-manager.ts@@ -12,7 +12,7 @@ import {getPublicAlbumsCredentials,requirePublicAlbumsCredentials,setPublicAlbumsCredentials,-} from "./public-albums-credentials";+} from "@/public-album/data/auth/public-link-credentials";import { decryptThumbnailBlobBytes } from "./thumbnail-crypto";class ThumbnailManager {diff --git a/web/apps/albums/src/gallery/utils/detect-type.ts b/web/apps/albums/src/public-album/media/utils/detect-type.tssimilarity index 100%rename from web/apps/albums/src/gallery/utils/detect-type.tsrename to web/apps/albums/src/public-album/media/utils/detect-type.tsdiff --git a/web/apps/albums/src/gallery/utils/file.ts b/web/apps/albums/src/public-album/media/utils/sort-files.tssimilarity index 100%rename from web/apps/albums/src/gallery/utils/file.tsrename to web/apps/albums/src/public-album/media/utils/sort-files.tsdiff --git a/web/apps/albums/src/gallery/services/video.ts b/web/apps/albums/src/public-album/media/video/preview.tssimilarity index 96%rename from web/apps/albums/src/gallery/services/video.tsrename to web/apps/albums/src/public-album/media/video/preview.tsindex 05b4acbfec..ee71eea8a5 100644--- a/web/apps/albums/src/gallery/services/video.ts+++ b/web/apps/albums/src/public-album/media/video/preview.ts@@ -6,7 +6,10 @@ import { fileLogID, type EnteFile } from "ente-media/file";import { FileType } from "ente-media/file-type";import { ensurePrecondition } from "ente-utils/ensure";import { z } from "zod";-import { fetchFileData, fetchFilePreviewData } from "./file-data";+import {+ fetchFileData,+ fetchFilePreviewData,+} from "@/public-album/data/api/public-file-data";export interface HLSPlaylistData {playlistURL: string;diff --git a/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx b/web/apps/albums/src/public-album/page/PublicAlbumPage.tsxnew file mode 100644index 0000000000..070ae9df5a--- /dev/null+++ b/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx@@ -0,0 +1,1245 @@+// TODO: Audit this file (too many null assertions + other issues)+/* eslint-disable @typescript-eslint/no-floating-promises */+import type { FullScreenDropZoneProps } from "@/public-album/upload/components/CollectDropZone";+import {+ useSaveGroupsActions,+ type AddSaveGroup,+} from "@/shared/state/save-groups";+import { type FileViewerInitialSidebar } from "@/public-album/viewer/components/FileViewer";+import { LazyPublicFeedSidebar } from "@/public-album/viewer/lib/lazy";+import { type PublicFeedItemClickInfo } from "@/public-album/viewer/components/PublicFeedSidebar";+import { sortFiles } from "@/public-album/media/utils/sort-files";+import { useAlbumsAppContext } from "@/app/context/albums-app-context";+import { LazyNotification } from "@/app/lazy/global-ui";+import {+ PasswordUnlockScreen,+ type PasswordUnlockScreenProps,+} from "@/public-album/access/components/PasswordUnlockScreen";+import { getEnteURL } from "@/public-album/access/utils/external-links";+import { setPublicAlbumsCredentials } from "@/public-album/data/auth/public-link-credentials";+import { quickLinkDateRangeForFiles } from "@/public-album/data/utils/quick-link";+import {+ GalleryItemsHeaderAdapter,+ GalleryItemsSummary,+} from "@/shared/ui/gallery/GalleryItemsHeader";+import { ActiveDownloadStatusNotifications } from "@/public-album/download/components/ActiveDownloadStatusNotifications";+import { FeedIcon } from "@/public-album/social/components/FeedIcon";+import { type FileListHeaderOrFooter } from "@/public-album/components/FileList";+import { FileListWithViewer } from "@/public-album/components/FileListWithViewer";+import type { PublicAlbumSingleFileViewerProps } from "@/public-album/viewer/components/PublicAlbumSingleFileViewer";+import type { TripLayoutProps } from "@/public-album/components/TripLayout";+import type { UploadProps } from "@/public-album/upload/components/Upload";+import {+ getSelectedFiles,+ type SelectedState,+} from "@/public-album/utils/file";+import {+ Download01Icon,+ ImageAdd02Icon,+ Share08Icon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import CheckIcon from "@mui/icons-material/Check";+import CloseIcon from "@mui/icons-material/Close";+import {+ Box,+ Button,+ IconButton,+ Stack,+ styled,+ Tooltip,+ useMediaQuery,+} from "@mui/material";+import Typography from "@mui/material/Typography";+import { SpacedRow, Stack100vhCenter } from "ente-base/components/containers";+import { EnteLogo } from "ente-base/components/EnteLogo";+import {+ LoadingIndicator,+ TranslucentLoadingOverlay,+} from "ente-base/components/loaders";+import type { ButtonishProps } from "ente-base/components/mui";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { NavbarBase } from "ente-base/components/Navbar";+import { useIsSmallWidth } from "ente-base/components/utils/hooks";+import { useModalVisibility } from "ente-base/components/utils/modal";+import { useBaseContext } from "ente-base/context";+import {+ isHTTP401Error,+ isHTTPErrorWithStatus,+ type PublicAlbumsCredentials,+} from "ente-base/http";+import log from "ente-base/log";+import {+ albumsAppOrigin,+ isCustomAlbumsAppOrigin,+ isOfficialAlbumsApp,+ photosAppOrigin,+} from "ente-base/origins";+import type { Collection } from "ente-media/collection";+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 dynamic from "next/dynamic";+import { useRouter } from "next/router";+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type ComponentType,+ type PropsWithChildren,+} from "react";+import { type FileWithPath } from "react-dropzone";++const LazyPublicAlbumSingleFileViewer =+ dynamic<PublicAlbumSingleFileViewerProps>(+ () =>+ import(+ "@/public-album/viewer/components/PublicAlbumSingleFileViewer"+ ).then(+ ({ PublicAlbumSingleFileViewer }) =>+ PublicAlbumSingleFileViewer,+ ),+ { ssr: false, loading: () => <LoadingIndicator /> },+ );++const LazyTripLayout = dynamic<TripLayoutProps>(+ () =>+ import("@/public-album/components/TripLayout").then(+ ({ TripLayout }) => TripLayout,+ ),+ { ssr: false, loading: () => <LoadingIndicator /> },+);++const LazyUpload = dynamic<UploadProps>(+ () =>+ import("@/public-album/upload/components/Upload").then(+ ({ Upload }) => Upload,+ ),+ { ssr: false },+);++const loadPublicAlbumsFDB = () =>+ import("@/public-album/data/storage/public-albums-fdb");++const loadPublicCollectionService = () =>+ import("@/public-album/data/api/public-collection");++const loadShareService = () =>+ import("@/public-album/access/services/extract-collection-key");++const loadJoinPublicAlbumRedirect = () =>+ import("@/public-album/access/services/join-public-album-redirect");++const publicAlbumAllFilesCollectionID = 0;++export default function PublicAlbumPage() {+ const { showMiniDialog, onGenericError } = useBaseContext();+ const { showLoadingBar, hideLoadingBar } = useAlbumsAppContext();++ const [publicCollection, setPublicCollection] = useState<+ Collection | undefined+ >(undefined);+ const [publicFiles, setPublicFiles] = useState<EnteFile[] | undefined>(+ undefined,+ );+ const [errorMessage, setErrorMessage] = useState<string>("");+ const [loading, setLoading] = useState(true);+ const [isPasswordProtected, setIsPasswordProtected] = useState(false);+ const [uploadTypeSelectorView, setUploadTypeSelectorView] = useState(false);+ const [blockingLoad, setBlockingLoad] = useState(false);+ const [shouldDisableDropzone, setShouldDisableDropzone] = useState(false);+ const [isUploadInProgress, setIsUploadInProgress] = useState(false);+ const [shouldRenderUpload, setShouldRenderUpload] = useState(false);+ const [dragAndDropFiles, setDragAndDropFiles] = useState<FileWithPath[]>(+ [],+ );+ const [selected, setSelected] = useState<SelectedState>({ count: 0 });++ // TODO: Can we convert these to state+ const credentials = useRef<PublicAlbumsCredentials | undefined>(undefined);+ const collectionKey = useRef<string | undefined>(undefined);++ const isRedirectingToAlbumsAppRef = useRef<boolean>(false);++ const { onAddSaveGroup } = useSaveGroupsActions();+ const { show: showPublicFeed, props: publicFeedVisibilityProps } =+ useModalVisibility();++ // Pending navigation from feed item click+ const [pendingFileNavigation, setPendingFileNavigation] = useState<{+ fileIndex: number;+ sidebar?: FileViewerInitialSidebar;+ commentID?: string;+ }>();++ /**+ * Handle clicks on feed items to navigate to the file and open sidebar.+ */+ const handleFeedItemClick = (info: PublicFeedItemClickInfo) => {+ if (!publicFiles) return;++ // Find the file index in publicFiles+ const fileIndex = publicFiles.findIndex((f) => f.id === info.fileID);+ if (fileIndex === -1) return;++ // Close the feed sidebar+ publicFeedVisibilityProps.onClose();++ // Determine which sidebar to open+ const sidebar: FileViewerInitialSidebar =+ info.type === "liked_photo" || info.type === "liked_video"+ ? "likes"+ : "comments";++ // Set navigation state+ setPendingFileNavigation({+ fileIndex,+ sidebar,+ commentID: info.commentID,+ });+ };++ const router = useRouter();++ const showPublicLinkExpiredMessage = () =>+ showMiniDialog({+ title: t("link_expired"),+ message: t("link_expired_message"),+ nonClosable: true,+ continue: {+ text: t("login"),+ action: async () => {+ if (isOfficialAlbumsApp) {+ window.location.href = photosAppOrigin();+ return;+ }+ await router.push("/");+ },+ },+ cancel: false,+ });++ /**+ * Check if we need to redirect Trip albums from custom domains to albums.ente.io+ * Returns true if a redirect was initiated, false otherwise.+ * Reason: custom domains do not support the Trip layout fully+ */+ const checkAndRedirectForTripAlbum = (collection: Collection): boolean => {+ if (+ collection.pubMagicMetadata?.data.layout === "trip" &&+ isOfficialAlbumsApp+ ) {+ const currentURL = new URL(window.location.href);+ const albumsURL = new URL(albumsAppOrigin());++ if (currentURL.host !== albumsURL.host) {+ isRedirectingToAlbumsAppRef.current = true;++ albumsURL.search = currentURL.search;+ albumsURL.hash = currentURL.hash;++ window.location.href = albumsURL.href;+ return true;+ }+ }+ return false;+ };++ useEffect(() => {+ /**+ * Determine credentials, read the locally cached state, then start+ * pulling the latest from remote.+ */+ const main = async () => {+ let redirectingToWebsite = false;+ try {+ const currentURL = new URL(window.location.href);+ const t = currentURL.searchParams.get("t");+ const [+ { extractCollectionKeyFromShareURL },+ {+ savedPublicCollectionAccessTokenJWT,+ savedPublicCollectionByKey,+ savedPublicCollectionFiles,+ },+ ] = await Promise.all([+ loadShareService(),+ loadPublicAlbumsFDB(),+ ]);+ const ck = await extractCollectionKeyFromShareURL(currentURL);+ if (!t && !ck) {+ // Only redirect to ente.com if this is NOT a custom/self-hosted instance+ if (!isCustomAlbumsAppOrigin) {+ window.location.href = "https://ente.com";+ redirectingToWebsite = true;+ }+ }+ if (!t || !ck) {+ return;+ }+ collectionKey.current = ck;+ const collection = await savedPublicCollectionByKey(ck);+ const accessToken = t;+ let accessTokenJWT: string | undefined;+ if (collection) {+ setPublicCollection(collection);+ setIsPasswordProtected(+ !!collection.publicURLs[0]?.passwordEnabled,+ );+ setPublicFiles(+ sortFilesForCollection(+ await savedPublicCollectionFiles(accessToken),+ collection,+ ),+ );+ accessTokenJWT =+ await savedPublicCollectionAccessTokenJWT(accessToken);+ }+ credentials.current = { accessToken, accessTokenJWT };+ setPublicAlbumsCredentials(credentials.current);+ await publicAlbumsRemotePull();+ } finally {+ if (+ !redirectingToWebsite &&+ !isRedirectingToAlbumsAppRef.current+ ) {+ setLoading(false);+ }+ }+ };+ main();+ // TODO:+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const downloadEnabled =+ publicCollection?.publicURLs[0]?.enableDownload ?? true;+ const collectEnabled =+ publicCollection?.publicURLs[0]?.enableCollect ?? false;++ useEffect(() => {+ if (!collectEnabled) return;+ void import("@/public-album/upload/pipeline").then(+ ({ updateShouldDisableCFUploadProxy }) =>+ updateShouldDisableCFUploadProxy(),+ );+ }, [collectEnabled]);++ useEffect(() => {+ if (+ uploadTypeSelectorView ||+ dragAndDropFiles.length > 0 ||+ isUploadInProgress+ ) {+ setShouldRenderUpload(true);+ }+ }, [dragAndDropFiles.length, isUploadInProgress, uploadTypeSelectorView]);++ /**+ * Pull the latest data related to the public album from remote, updating+ * both our local database and component state.+ */+ const publicAlbumsRemotePull = useCallback(async () => {+ const accessToken = credentials.current!.accessToken;+ showLoadingBar();+ setLoading(true);+ try {+ const [+ {+ pullCollection,+ pullPublicCollectionFiles,+ removePublicCollectionFileData,+ },+ { removePublicCollectionAccessTokenJWT },+ ] = await Promise.all([+ loadPublicCollectionService(),+ loadPublicAlbumsFDB(),+ ]);+ const { collection } = await pullCollection(+ accessToken,+ collectionKey.current!,+ );++ if (checkAndRedirectForTripAlbum(collection)) {+ return;+ }++ setPublicCollection(collection);+ const isPasswordProtected =+ !!collection.publicURLs[0]?.passwordEnabled;+ setIsPasswordProtected(isPasswordProtected);+ setErrorMessage("");++ // Remove the locally cached accessTokenJWT if the sharer has+ // disabled password protection on the link.+ if (!isPasswordProtected && credentials.current?.accessTokenJWT) {+ credentials.current.accessTokenJWT = undefined;+ setPublicAlbumsCredentials(credentials.current);+ removePublicCollectionAccessTokenJWT(accessToken);+ }++ if (isPasswordProtected && !credentials.current?.accessTokenJWT) {+ await removePublicCollectionFileData(accessToken);+ } else {+ try {+ await pullPublicCollectionFiles(+ credentials.current!,+ collection,+ (files) =>+ setPublicFiles(+ sortFilesForCollection(files, collection),+ ),+ );+ } catch (e) {+ // If we reached the try block and attempted to pull files,+ // it means the accessToken itself is very likely valid+ // (since the `pullCollection` succeeded just a moment ago).+ //+ // So a 401 Unauthorized now indicates that the+ // accessTokenJWT is no longer valid since the sharer has+ // changed the password.+ //+ // Clear the locally cached accessTokenJWT and ask the user+ // to reenter the password.+ if (isHTTP401Error(e)) {+ credentials.current!.accessTokenJWT = undefined;+ setPublicAlbumsCredentials(credentials.current);+ } else {+ throw e;+ }+ }+ }+ } catch (e) {+ // The 410 Gone or 429 Rate limited can arise from either the+ // collection pull or the files pull since they're part of the+ // remote's access token check sequence.+ //+ // In practice, it almost always will be a consequence of the+ // collection pull since it happens first.+ //+ // The 401 Unauthorized can only arise from the collection pull+ // since we already handle that separately for the files pull.+ if (+ isHTTPErrorWithStatus(e, 401) ||+ isHTTPErrorWithStatus(e, 410) ||+ isHTTPErrorWithStatus(e, 429)+ ) {+ const [+ { removePublicCollectionFileData },+ { removePublicCollectionByKey },+ ] = await Promise.all([+ loadPublicCollectionService(),+ loadPublicAlbumsFDB(),+ ]);+ setErrorMessage(+ isHTTPErrorWithStatus(e, 429)+ ? t("link_request_limit_exceeded")+ : t("link_expired_message"),+ );+ // Sharing has been disabled. Clear out local cache.+ await removePublicCollectionFileData(accessToken);+ await removePublicCollectionByKey(collectionKey.current!);+ setPublicCollection(undefined);+ setPublicFiles(undefined);+ } else {+ log.error("Public album remote pull failed", e);+ // Don't use the `setErrorMessage`, show a dialog instead,+ // because this might be a transient network error.+ onGenericError(e);+ }+ } finally {+ hideLoadingBar();+ if (!isRedirectingToAlbumsAppRef.current) {+ setLoading(false);+ }+ }+ }, [showLoadingBar, hideLoadingBar, onGenericError]);++ // See: [Note: Visual feedback to acknowledge user actions]+ const handleVisualFeedback = useCallback(() => {+ showLoadingBar();+ setTimeout(hideLoadingBar, 0);+ }, [showLoadingBar, hideLoadingBar]);++ const handleJoinAlbum = useCallback(() => {+ const accessToken = credentials.current?.accessToken;+ const currentCollectionKey = collectionKey.current;++ if (!publicCollection || !accessToken || !currentCollectionKey) {+ return;+ }++ void loadJoinPublicAlbumRedirect().then(+ ({ joinPublicAlbumViaRedirect }) =>+ joinPublicAlbumViaRedirect({+ publicCollection,+ accessToken,+ collectionKey: currentCollectionKey,+ credentials,+ }),+ );+ }, [publicCollection]);++ const handleSubmitPassword: PasswordUnlockScreenProps["onSubmit"] = async (+ password,+ setFieldError,+ ) => {+ try {+ const accessToken = credentials.current!.accessToken;+ const [+ { verifyPublicAlbumPassword },+ { savePublicCollectionAccessTokenJWT },+ ] = await Promise.all([+ import("@/public-album/access/services/verify-public-album-password"),+ loadPublicAlbumsFDB(),+ ]);+ const accessTokenJWT = await verifyPublicAlbumPassword(+ publicCollection!.publicURLs[0]!,+ password,+ accessToken,+ );+ credentials.current!.accessTokenJWT = accessTokenJWT;+ setPublicAlbumsCredentials(credentials.current);+ await savePublicCollectionAccessTokenJWT(+ accessToken,+ accessTokenJWT,+ );+ } catch (e) {+ log.error("Failed to verifyLinkPassword", e);+ if (isHTTP401Error(e)) {+ setFieldError(t("incorrect_password"));+ return;+ }+ throw e;+ }++ await publicAlbumsRemotePull();+ };++ const clearSelection = () => {+ if (!selected.count) {+ return;+ }+ setSelected({ count: 0 });+ };++ const handleUploadFile = (file: EnteFile) =>+ setPublicFiles(+ sortFilesForCollection([...publicFiles!, file], publicCollection),+ );++ const downloadFilesHelper = async () => {+ try {+ const { downloadAndSaveFiles } = await import(+ "@/public-album/download/services/save"+ );+ const selectedFiles = getSelectedFiles(selected, publicFiles!);+ const singleFile =+ selectedFiles.length === 1 ? selectedFiles[0] : undefined;+ const title =+ singleFile?.metadata.fileType === FileType.livePhoto+ ? fileFileName(singleFile)+ : t("files_count", { count: selectedFiles.length });+ await downloadAndSaveFiles(selectedFiles, title, onAddSaveGroup);+ clearSelection();+ } catch (e) {+ log.error("failed to download selected files", e);+ }+ };++ const onAddPhotos = useMemo(() => {+ if (!collectEnabled) return undefined;+ return () => {+ setShouldRenderUpload(true);+ setUploadTypeSelectorView(true);+ };+ }, [collectEnabled]);++ const closeUploadTypeSelectorView = () => {+ setUploadTypeSelectorView(false);+ };++ const commentsEnabled =+ publicCollection?.publicURLs[0]?.enableComment ?? false;+ const joinEnabled = publicCollection?.publicURLs[0]?.enableJoin ?? false;+ const addPhotosEnabled = collectEnabled;+ const handleDrop = useCallback((files: FileWithPath[]) => {+ setShouldRenderUpload(true);+ setDragAndDropFiles(files);+ }, []);++ const hasSelection = selected.count > 0;+ const isMobileHeaderLayout = useMediaQuery("(width < 720px)");+ const fileListHeaderHeightForViewport = isMobileHeaderLayout+ ? fileListHeaderHeightMobile+ : fileListHeaderHeight;++ const fileListHeader = useMemo<FileListHeaderOrFooter | undefined>(+ () =>+ publicCollection && publicFiles+ ? {+ component: (+ <FileListHeader+ {...{+ publicCollection,+ publicFiles,+ downloadEnabled,+ onAddSaveGroup,+ onAddPhotos,+ onShowFeed: commentsEnabled+ ? showPublicFeed+ : undefined,+ addPhotosDisabled: isUploadInProgress,+ hasSelection,+ }}+ />+ ),+ height: fileListHeaderHeightForViewport,+ }+ : undefined,+ [+ onAddSaveGroup,+ publicCollection,+ publicFiles,+ downloadEnabled,+ showPublicFeed,+ commentsEnabled,+ onAddPhotos,+ isUploadInProgress,+ hasSelection,+ fileListHeaderHeightForViewport,+ ],+ );++ const fileListFooter = useMemo<FileListHeaderOrFooter>(+ () => ({+ component: <FileListFooter />,+ height: fileListFooterHeight,+ extendToInlineEdges: true,+ }),+ [],+ );++ if (loading && (!publicFiles || !credentials.current)) {+ return <LoadingIndicator />;+ } else if (errorMessage) {+ return (+ <Stack100vhCenter>+ <Typography+ sx={{+ color: "critical.main",+ px: { xs: 2, sm: 0 },+ textAlign: { xs: "center", sm: "inherit" },+ }}+ >+ {errorMessage}+ </Typography>+ </Stack100vhCenter>+ );+ } else if (isPasswordProtected && !credentials.current?.accessTokenJWT) {+ return <PasswordUnlockScreen onSubmit={handleSubmitPassword} />;+ } else if (!publicFiles || !credentials.current) {+ return (+ <Stack100vhCenter>+ <Typography>{t("not_found")}</Typography>+ </Stack100vhCenter>+ );+ }++ const layout = normalizedPublicAlbumLayout(+ publicCollection?.pubMagicMetadata?.data.layout,+ );+ const quickLinkDateRange = quickLinkDateRangeForFiles(publicFiles);+ const isQuickLinkAlbum =+ quickLinkDateRange !== undefined &&+ publicCollection?.name === quickLinkDateRange;+ const isSingleFileAlbum = publicFiles.length === 1;+ const shouldShowSingleFileViewer = isQuickLinkAlbum && isSingleFileAlbum;++ if (shouldShowSingleFileViewer) {+ return (+ <>+ <LazyPublicAlbumSingleFileViewer+ file={publicFiles[0]!}+ publicAlbumsCredentials={credentials.current}+ collectionKey={collectionKey.current!}+ enableDownload={downloadEnabled}+ enableComment={commentsEnabled}+ enableJoin={publicCollection.publicURLs[0]?.enableJoin}+ onJoinAlbum={handleJoinAlbum}+ onVisualFeedback={handleVisualFeedback}+ onAddSaveGroup={onAddSaveGroup}+ />+ {blockingLoad && <TranslucentLoadingOverlay />}+ <ActiveDownloadStatusNotifications fullWidthOnMobile />+ </>+ );+ }++ const content = (+ <>+ {layout === "trip" ? (+ <LazyTripLayout+ files={publicFiles}+ collection={publicCollection}+ onAddPhotos={onAddPhotos}+ enableDownload={downloadEnabled}+ accessToken={credentials.current.accessToken}+ collectionKey={collectionKey.current}+ credentials={credentials}+ enableComment={commentsEnabled}+ enableJoin={publicCollection?.publicURLs[0]?.enableJoin}+ />+ ) : (+ <>+ <NavbarBase+ sx={[+ {+ flex: "0 0 60px",+ px: "24px",+ "@media (width < 720px)": { px: "4px" },+ },+ selected.count > 0 && {+ borderColor: "accent.main",+ overflowX: "hidden",+ },+ ]}+ >+ {selected.count > 0 ? (+ <SelectedFileOptions+ count={selected.count}+ clearSelection={clearSelection}+ downloadFilesHelper={downloadFilesHelper}+ />+ ) : (+ <SpacedRow sx={{ flex: 1 }}>+ <EnteLogoLink href="https://ente.com">+ <EnteLogo height={15} />+ </EnteLogoLink>+ <Stack direction="row" spacing={2}>+ <SecondaryActionButton+ onAddPhotos={onAddPhotos}+ addPhotosDisabled={isUploadInProgress}+ enableJoin={joinEnabled}+ onJoinAlbum={handleJoinAlbum}+ />+ <PrimaryActionButton+ showJoinAsPrimary={+ addPhotosEnabled && joinEnabled+ }+ onJoinAlbum={handleJoinAlbum}+ />+ </Stack>+ </SpacedRow>+ )}+ </NavbarBase>+ <FileListWithViewer+ files={publicFiles}+ layout={layout === "masonry" ? "masonry" : "grid"}+ header={fileListHeader}+ footer={fileListFooter}+ enableDownload={downloadEnabled}+ enableSelect={downloadEnabled}+ selected={selected}+ setSelected={setSelected}+ activeCollectionID={publicAlbumAllFilesCollectionID}+ onAddSaveGroup={onAddSaveGroup}+ publicAlbumsCredentials={credentials.current}+ collectionKey={collectionKey.current}+ onJoinAlbum={handleJoinAlbum}+ enableComment={commentsEnabled}+ enableJoin={publicCollection?.publicURLs[0]?.enableJoin}+ pendingFileIndex={pendingFileNavigation?.fileIndex}+ pendingFileSidebar={pendingFileNavigation?.sidebar}+ pendingHighlightCommentID={+ pendingFileNavigation?.commentID+ }+ onPendingNavigationConsumed={() =>+ setPendingFileNavigation(undefined)+ }+ />+ </>+ )}+ {blockingLoad && <TranslucentLoadingOverlay />}+ {collectEnabled && shouldRenderUpload && (+ <LazyUpload+ publicAlbumsCredentials={credentials.current}+ uploadCollection={publicCollection}+ setLoading={setBlockingLoad}+ setShouldDisableDropzone={setShouldDisableDropzone}+ uploadTypeSelectorView={uploadTypeSelectorView}+ onRemotePull={publicAlbumsRemotePull}+ onUploadFile={handleUploadFile}+ closeUploadTypeSelector={closeUploadTypeSelectorView}+ onShowSessionExpiredDialog={showPublicLinkExpiredMessage}+ onUploadInProgressChange={setIsUploadInProgress}+ {...{ dragAndDropFiles }}+ />+ )}+ <ActiveDownloadStatusNotifications fullWidthOnMobile />+ {publicFeedVisibilityProps.open &&+ publicCollection &&+ collectionKey.current && (+ <LazyPublicFeedSidebar+ {...publicFeedVisibilityProps}+ files={publicFiles}+ credentials={credentials.current}+ collectionKey={collectionKey.current}+ onItemClick={handleFeedItemClick}+ />+ )}+ </>+ );++ return (+ <LazyCollectDropZone+ enabled={collectEnabled}+ disabled={shouldDisableDropzone}+ onDrop={handleDrop}+ message={t("upload_dropzone_hint_public_album")}+ >+ {content}+ </LazyCollectDropZone>+ );+}++/**+ * Sort the given {@link files} using {@link sortFiles}, using the ascending+ * ordering preference if specified in the given {@link collection}'s metadata.+ */+const sortFilesForCollection = (files: EnteFile[], collection?: Collection) =>+ sortFiles(files, collection?.pubMagicMetadata?.data.asc ?? false);++const normalizedPublicAlbumLayout = (layout: string | undefined) => {+ if (layout === "continuous") {+ return "masonry";+ }+ if (layout === "grouped" || layout === "trip" || layout === "masonry") {+ return layout;+ }+ return "masonry";+};++type LazyCollectDropZoneProps = PropsWithChildren<+ { enabled: boolean } & Pick<+ FullScreenDropZoneProps,+ "disabled" | "message" | "onDrop"+ >+>;++const LazyCollectDropZone: React.FC<LazyCollectDropZoneProps> = ({+ enabled,+ children,+ ...props+}) => {+ const [DropZoneComponent, setDropZoneComponent] = useState<ComponentType<+ PropsWithChildren<FullScreenDropZoneProps>+ > | null>(null);++ useEffect(() => {+ if (!enabled || DropZoneComponent) return;++ let isCancelled = false;+ void import("@/public-album/upload/components/CollectDropZone").then(+ ({ FullScreenDropZone }) => {+ if (isCancelled) return;+ setDropZoneComponent(() => FullScreenDropZone);+ },+ );++ return () => {+ isCancelled = true;+ };+ }, [DropZoneComponent, enabled]);++ if (!enabled || !DropZoneComponent) {+ return <>{children}</>;+ }++ return <DropZoneComponent {...props}>{children}</DropZoneComponent>;+};++const EnteLogoLink = styled("a")(({ theme }) => ({+ // Remove the excess space at the top.+ svg: { verticalAlign: "middle" },+ color: theme.vars.palette.text.base,+ ":hover": { color: theme.vars.palette.accent.main },+}));++const GreenButton = styled(Button)(() => ({+ backgroundColor: "#08C225",+ borderRadius: "16px",+ paddingBlock: "11px",+ paddingInline: "20px",+ "&:hover": { backgroundColor: "#07A820" },+}));++const navbarActionButtonSx = { borderRadius: "16px", paddingBlock: "11px" };++type AddPhotosButtonProps = ButtonishProps & { disabled?: boolean };++const AddPhotosButton: React.FC<AddPhotosButtonProps> = ({+ onClick,+ disabled,+}) => {+ const isSmallWidth = useIsSmallWidth();++ return (+ <FocusVisibleButton+ color="secondary"+ startIcon={+ isSmallWidth ? undefined : (+ <HugeiconsIcon+ icon={ImageAdd02Icon}+ size={20}+ strokeWidth={1.8}+ />+ )+ }+ sx={navbarActionButtonSx}+ {...{ onClick, disabled }}+ >+ {t("add_photos")}+ </FocusVisibleButton>+ );+};++interface PrimaryActionButtonProps {+ /** If true, shows "Join Album" as the primary action */+ showJoinAsPrimary?: boolean;+ onJoinAlbum?: () => void;+}++const PrimaryActionButton: React.FC<PrimaryActionButtonProps> = ({+ showJoinAsPrimary,+ onJoinAlbum,+}) => {+ if (showJoinAsPrimary) {+ return (+ <GreenButton color="accent" onClick={onJoinAlbum}>+ {t("join_album")}+ </GreenButton>+ );+ }++ const handleGetEnte = () => {+ window.location.href = getEnteURL();+ };++ return (+ <GreenButton color="accent" onClick={handleGetEnte}>+ {t("try_ente")}+ </GreenButton>+ );+};++interface SecondaryActionButtonProps {+ onAddPhotos?: () => void;+ addPhotosDisabled?: boolean;+ enableJoin?: boolean;+ onJoinAlbum?: () => void;+}++const SecondaryActionButton: React.FC<SecondaryActionButtonProps> = ({+ onAddPhotos,+ addPhotosDisabled,+ enableJoin,+ onJoinAlbum,+}) => {+ if (onAddPhotos) {+ return (+ <AddPhotosButton+ onClick={onAddPhotos}+ disabled={addPhotosDisabled}+ />+ );+ }++ if (enableJoin) {+ return (+ <FocusVisibleButton+ color="secondary"+ sx={navbarActionButtonSx}+ onClick={onJoinAlbum}+ >+ {t("join_album")}+ </FocusVisibleButton>+ );+ }++ return null;+};++interface SelectedFileOptionsProps {+ count: number;+ clearSelection: () => void;+ downloadFilesHelper: () => void;+}++const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({+ count,+ clearSelection,+ downloadFilesHelper,+}) => (+ <Stack+ direction="row"+ sx={{+ flex: 1,+ minWidth: 0,+ gap: 1,+ alignItems: "center",+ width: "100%",+ }}+ >+ <IconButton+ onClick={clearSelection}+ sx={{ flexShrink: 0, ml: "-15px" }}+ >+ <CloseIcon />+ </IconButton>+ <Typography+ sx={{+ mr: "auto",+ minWidth: 0,+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ }}+ >+ {t("selected_count", { selected: count })}+ </Typography>+ <Tooltip title={t("download")}>+ <IconButton+ onClick={downloadFilesHelper}+ sx={{ flexShrink: 0, mr: "-15px" }}+ >+ <HugeiconsIcon icon={Download01Icon} strokeWidth={1.6} />+ </IconButton>+ </Tooltip>+ </Stack>+);++interface FileListHeaderProps {+ publicCollection: Collection;+ publicFiles: EnteFile[];+ downloadEnabled: boolean;+ onAddSaveGroup: AddSaveGroup;+ onAddPhotos?: () => void;+ onShowFeed?: () => void;+ addPhotosDisabled: boolean;+ hasSelection: boolean;+}++/**+ * The fixed height (in px) of {@link FileListHeader}.+ */+const fileListHeaderHeight = 84;++/**+ * The height (in px) of {@link FileListHeader} on mobile.+ *+ * Keep this fixed so the virtualized list has a stable header row height.+ */+const fileListHeaderHeightMobile = 132;++/**+ * A header shown before the listing of files.+ *+ * It scrolls along with the content. It has a fixed height,+ * {@link fileListHeaderHeight}.+ */+const FileListHeader: React.FC<FileListHeaderProps> = ({+ publicCollection,+ publicFiles,+ downloadEnabled,+ onAddSaveGroup,+ onAddPhotos,+ onShowFeed,+ addPhotosDisabled,+ hasSelection,+}) => {+ const [showCopiedMessage, setShowCopiedMessage] = useState(false);++ const memoriesDateRange = useMemo(() => {+ return quickLinkDateRangeForFiles(publicFiles);+ }, [publicFiles]);++ const isQuickLinkAlbum =+ memoriesDateRange !== undefined &&+ publicCollection.name === memoriesDateRange;++ const downloadAllFiles = () => {+ void import("@/public-album/download/services/save").then(+ ({ downloadAndSaveCollectionFiles }) =>+ downloadAndSaveCollectionFiles(+ publicCollection.name,+ publicCollection.id,+ publicFiles,+ undefined,+ onAddSaveGroup,+ ),+ );+ };++ const handleShare = async () => {+ if (typeof window === "undefined") return;++ const shareUrl = window.location.href;+ const shareText = `${publicCollection.name}\n${shareUrl}`;+ const isMobile = window.matchMedia("(width < 720px)").matches;++ if (isMobile && typeof navigator.share === "function") {+ try {+ await navigator.share({ text: shareText });+ return;+ } catch (error) {+ if (error instanceof Error && error.name === "AbortError") {+ return;+ }+ }+ }++ void navigator.clipboard.writeText(isMobile ? shareText : shareUrl);+ setShowCopiedMessage(true);+ setTimeout(() => setShowCopiedMessage(false), 2000);+ };++ return (+ <>+ <GalleryItemsHeaderAdapter sx={{ pt: "16px" }}>+ <SpacedRow+ sx={{+ width: "100%",+ "@media (width < 720px)": {+ flexDirection: "column",+ alignItems: "flex-start",+ gap: 1,+ },+ }}+ >+ <Box+ sx={{+ minWidth: 0,+ flex: 1,+ "@media (width < 720px)": { width: "100%" },+ }}+ >+ <GalleryItemsSummary+ name={publicCollection.name}+ fileCount={publicFiles.length}+ endIcon={+ !isQuickLinkAlbum && memoriesDateRange ? (+ <Typography+ variant="small"+ sx={{ color: "text.muted", ml: "-6px" }}+ >+ <Box+ component="span"+ sx={{ mr: "6px" }}+ >+ {"\u00b7"}+ </Box>+ {memoriesDateRange}+ </Typography>+ ) : undefined+ }+ nameProps={{+ noWrap: true,+ sx: { width: "100%", maxWidth: "100%" },+ }}+ />+ </Box>+ <Stack+ direction="row"+ spacing={0}+ sx={{+ alignItems: "center",+ "@media (width > 720px)": { mr: -1.5 },+ "@media (width < 720px)": { ml: -1.5 },+ }}+ >+ {onShowFeed && (+ <IconButton+ onClick={onShowFeed}+ disabled={hasSelection}+ >+ <Box+ sx={{+ width: 24,+ height: 24,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ <FeedIcon />+ </Box>+ </IconButton>+ )}+ {downloadEnabled && (+ <IconButton+ onClick={downloadAllFiles}+ disabled={hasSelection}+ >+ <HugeiconsIcon+ icon={Download01Icon}+ strokeWidth={1.6}+ />+ </IconButton>+ )}+ {onAddPhotos && (+ <IconButton+ onClick={onAddPhotos}+ disabled={addPhotosDisabled || hasSelection}+ >+ <HugeiconsIcon+ icon={ImageAdd02Icon}+ strokeWidth={1.8}+ />+ </IconButton>+ )}+ <IconButton+ onClick={handleShare}+ disabled={hasSelection}+ >+ <HugeiconsIcon+ icon={Share08Icon}+ strokeWidth={1.6}+ />+ </IconButton>+ </Stack>+ </SpacedRow>+ </GalleryItemsHeaderAdapter>+ {showCopiedMessage && (+ <LazyNotification+ open={showCopiedMessage}+ onClose={() => setShowCopiedMessage(false)}+ horizontal="left"+ attributes={{+ color: "secondary",+ startIcon: <CheckIcon />,+ title: "Copied!",+ }}+ />+ )}+ </>+ );+};++/**+ * The fixed height (in px) of {@link FileListFooter}.+ */+const fileListFooterHeight = 24;++/**+ * A footer shown after the listing of files.+ *+ * It scrolls along with the content. It has a fixed height,+ * {@link fileListFooterHeight}.+ */+const FileListFooter: React.FC = () => (+ <Box sx={{ height: fileListFooterHeight }} />+);diff --git a/web/apps/albums/src/albums/services/public-comment.ts b/web/apps/albums/src/public-album/social/api/public-comment.tssimilarity index 100%rename from web/apps/albums/src/albums/services/public-comment.tsrename to web/apps/albums/src/public-album/social/api/public-comment.tsdiff --git a/web/apps/albums/src/albums/services/public-reaction.ts b/web/apps/albums/src/public-album/social/api/public-reaction.tssimilarity index 100%rename from web/apps/albums/src/albums/services/public-reaction.tsrename to web/apps/albums/src/public-album/social/api/public-reaction.tsdiff --git a/web/apps/albums/src/public-album/components/Collections/FeedIcon.tsx b/web/apps/albums/src/public-album/social/components/FeedIcon.tsxsimilarity index 100%rename from web/apps/albums/src/public-album/components/Collections/FeedIcon.tsxrename to web/apps/albums/src/public-album/social/components/FeedIcon.tsxdiff --git a/web/apps/albums/src/public-album/components/CanvasReadbackBlockedDialog.tsx b/web/apps/albums/src/public-album/upload/components/CanvasReadbackBlockedDialog.tsxsimilarity index 100%rename from web/apps/albums/src/public-album/components/CanvasReadbackBlockedDialog.tsxrename to web/apps/albums/src/public-album/upload/components/CanvasReadbackBlockedDialog.tsxdiff --git a/web/apps/albums/src/gallery/components/FullScreenDropZone.tsx b/web/apps/albums/src/public-album/upload/components/CollectDropZone.tsxsimilarity index 100%rename from web/apps/albums/src/gallery/components/FullScreenDropZone.tsxrename to web/apps/albums/src/public-album/upload/components/CollectDropZone.tsxdiff --git a/web/apps/albums/src/public-album/components/Upload.tsx b/web/apps/albums/src/public-album/upload/components/Upload.tsxsimilarity index 96%rename from web/apps/albums/src/public-album/components/Upload.tsxrename to web/apps/albums/src/public-album/upload/components/Upload.tsxindex 32a7e5e8dd..a8c7c43d7a 100644--- a/web/apps/albums/src/public-album/components/Upload.tsx+++ b/web/apps/albums/src/public-album/upload/components/Upload.tsx@@ -1,29 +1,32 @@// TODO: Audit this file// TODO: Too many null assertions in this file. The types need reworking./* eslint-disable react-hooks/exhaustive-deps */-import { UploaderNameInput } from "@/albums/components/UploaderNameInput";+import { UploaderNameInput } from "@/public-album/upload/components/UploaderNameInput";import {savedPublicCollectionUploaderName,savePublicCollectionUploaderName,-} from "@/albums/services/public-albums-fdb";-import { useFileInput } from "@/gallery/components/utils/use-file-input";-import { uploadPathPrefix, type UploadPhase } from "@/gallery/services/upload";-import type { ParsedMetadataJSON } from "@/gallery/services/upload/metadata-json";+} from "@/public-album/data/storage/public-albums-fdb";+import { useFileInput } from "@/shared/hooks/useFileInput";+import {+ uploadPathPrefix,+ type UploadPhase,+} from "@/public-album/upload/pipeline";+import type { ParsedMetadataJSON } from "@/public-album/upload/pipeline/metadata-json";import {sessionExpiredErrorMessage,storageLimitExceededErrorMessage,subscriptionExpiredErrorMessage,-} from "@/gallery/services/upload/upload-service";-import { usePhotosAppContext } from "@/photos/types/context";+} from "@/public-album/upload/pipeline/upload-service";+import { useAlbumsAppContext } from "@/app/context/albums-app-context";import type {InProgressUpload,SegregatedFinishedUploads,UploadCounter,UploadFileNames,UploadItemWithCollection,-} from "@/public-album/services/upload-manager";-import { uploadManager } from "@/public-album/services/upload-manager";-import { hasReliableCanvasReadback } from "@/public-album/utils/canvas-integrity";+} 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 ChevronRightIcon from "@mui/icons-material/ChevronRight";import ImageOutlinedIcon from "@mui/icons-material/ImageOutlined";import PermMediaOutlinedIcon from "@mui/icons-material/PermMediaOutlined";@@ -100,7 +103,7 @@ export const Upload: React.FC<UploadProps> = ({...props}) => {const { onGenericError } = useBaseContext();- const { showNotification } = usePhotosAppContext();+ const { showNotification } = useAlbumsAppContext();const [uploadProgressView, setUploadProgressView] = useState(false);const [diff --git a/web/apps/albums/src/public-album/components/UploadProgress.tsx b/web/apps/albums/src/public-album/upload/components/UploadProgress.tsxsimilarity index 99%rename from web/apps/albums/src/public-album/components/UploadProgress.tsxrename to web/apps/albums/src/public-album/upload/components/UploadProgress.tsxindex c19af3fddb..0cd8b4b373 100644--- a/web/apps/albums/src/public-album/components/UploadProgress.tsx+++ b/web/apps/albums/src/public-album/upload/components/UploadProgress.tsx@@ -1,13 +1,13 @@// TODO: Audit this file/* eslint-disable @typescript-eslint/no-unsafe-argument */-import { type UploadPhase } from "@/gallery/services/upload";+import { type UploadPhase } from "@/public-album/upload/pipeline";import type {FinishedUploadType,InProgressUpload,SegregatedFinishedUploads,UploadCounter,UploadFileNames,-} from "@/public-album/services/upload-manager";+} from "@/public-album/upload/services/upload-manager";import CloseIcon from "@mui/icons-material/Close";import ExpandMoreIcon from "@mui/icons-material/ExpandMore";import UnfoldLessIcon from "@mui/icons-material/UnfoldLess";diff --git a/web/apps/albums/src/albums/components/UploaderNameInput.tsx b/web/apps/albums/src/public-album/upload/components/UploaderNameInput.tsxsimilarity index 100%rename from web/apps/albums/src/albums/components/UploaderNameInput.tsxrename to web/apps/albums/src/public-album/upload/components/UploaderNameInput.tsxdiff --git a/web/apps/albums/src/gallery/services/upload/date.ts b/web/apps/albums/src/public-album/upload/pipeline/date.tssimilarity index 100%rename from web/apps/albums/src/gallery/services/upload/date.tsrename to web/apps/albums/src/public-album/upload/pipeline/date.tsdiff --git a/web/apps/albums/src/gallery/export-dirs.ts b/web/apps/albums/src/public-album/upload/pipeline/export-dirs.tssimilarity index 100%rename from web/apps/albums/src/gallery/export-dirs.tsrename to web/apps/albums/src/public-album/upload/pipeline/export-dirs.tsdiff --git a/web/apps/albums/src/gallery/services/upload/index.ts b/web/apps/albums/src/public-album/upload/pipeline/index.tssimilarity index 96%rename from web/apps/albums/src/gallery/services/upload/index.tsrename to web/apps/albums/src/public-album/upload/pipeline/index.tsindex e33351998e..b023844956 100644--- a/web/apps/albums/src/gallery/services/upload/index.ts+++ b/web/apps/albums/src/public-album/upload/pipeline/index.ts@@ -1,4 +1,4 @@-import { exportMetadataDirectoryName } from "@/gallery/export-dirs";+import { exportMetadataDirectoryName } from "@/public-album/upload/pipeline/export-dirs";import { basename, dirname } from "ente-base/file-name";import log from "ente-base/log";import { customAPIOrigin } from "ente-base/origins";diff --git a/web/apps/albums/src/gallery/services/upload/md5.ts b/web/apps/albums/src/public-album/upload/pipeline/md5.tssimilarity index 100%rename from web/apps/albums/src/gallery/services/upload/md5.tsrename to web/apps/albums/src/public-album/upload/pipeline/md5.tsdiff --git a/web/apps/albums/src/gallery/services/upload/metadata-json.ts b/web/apps/albums/src/public-album/upload/pipeline/metadata-json.tssimilarity index 99%rename from web/apps/albums/src/gallery/services/upload/metadata-json.tsrename to web/apps/albums/src/public-album/upload/pipeline/metadata-json.tsindex 8ccb2f9fa9..27908cab87 100644--- a/web/apps/albums/src/gallery/services/upload/metadata-json.ts+++ b/web/apps/albums/src/public-album/upload/pipeline/metadata-json.ts@@ -1,6 +1,6 @@/** @file Dealing with the JSON metadata sidecar files */-import type { UploadItem, UploadPathPrefix } from "@/gallery/services/upload";+import type { UploadItem, UploadPathPrefix } from "@/public-album/upload/pipeline";import { nameAndExtension } from "ente-base/file-name";import log from "ente-base/log";import { type Location } from "ente-base/types";diff --git a/web/apps/albums/src/gallery/services/upload/remote.ts b/web/apps/albums/src/public-album/upload/pipeline/remote.tssimilarity index 100%rename from web/apps/albums/src/gallery/services/upload/remote.tsrename to web/apps/albums/src/public-album/upload/pipeline/remote.tsdiff --git a/web/apps/albums/src/gallery/services/upload/thumbnail.ts b/web/apps/albums/src/public-album/upload/pipeline/thumbnail.tssimilarity index 99%rename from web/apps/albums/src/gallery/services/upload/thumbnail.tsrename to web/apps/albums/src/public-album/upload/pipeline/thumbnail.tsindex 508d9a452d..03223331d9 100644--- a/web/apps/albums/src/gallery/services/upload/thumbnail.ts+++ b/web/apps/albums/src/public-album/upload/pipeline/thumbnail.ts@@ -1,4 +1,4 @@-import * as ffmpeg from "@/gallery/services/ffmpeg";+import * as ffmpeg from "@/public-album/media/processing/ffmpeg";import log from "ente-base/log";import { FileType, type FileTypeInfo } from "ente-media/file-type";import { isHEICExtension } from "ente-media/formats";diff --git a/web/apps/albums/src/gallery/services/upload/upload-service.ts b/web/apps/albums/src/public-album/upload/pipeline/upload-service.tssimilarity index 99%rename from web/apps/albums/src/gallery/services/upload/upload-service.tsrename to web/apps/albums/src/public-album/upload/pipeline/upload-service.tsindex b9fb4a1784..3d9f5cef5a 100644--- a/web/apps/albums/src/gallery/services/upload/upload-service.ts+++ b/web/apps/albums/src/public-album/upload/pipeline/upload-service.ts@@ -1,15 +1,15 @@// TODO: Audit this file/* eslint-disable @typescript-eslint/ban-ts-comment */-import { extractExif } from "@/gallery/services/exif";+import { extractExif } from "@/public-album/media/metadata/exif";import {determineVideoDuration,extractVideoMetadata,-} from "@/gallery/services/ffmpeg";+} from "@/public-album/media/processing/ffmpeg";import {detectFileTypeInfoFromChunk,isFileTypeNotSupportedError,-} from "@/gallery/utils/detect-type";+} 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";diff --git a/web/apps/albums/src/public-album/services/upload-manager.ts b/web/apps/albums/src/public-album/upload/services/upload-manager.tssimilarity index 98%rename from web/apps/albums/src/public-album/services/upload-manager.tsrename to web/apps/albums/src/public-album/upload/services/upload-manager.tsindex f187c25c16..583bb452ec 100644--- a/web/apps/albums/src/public-album/services/upload-manager.ts+++ b/web/apps/albums/src/public-album/upload/services/upload-manager.ts@@ -1,18 +1,18 @@// TODO: Audit this file// TODO: Too many null assertions in this file. The types need reworking.-import { savedPublicCollectionFiles } from "@/albums/services/public-albums-fdb";+import { savedPublicCollectionFiles } from "@/public-album/data/storage/public-albums-fdb";import {shouldDisableCFUploadProxy,type ClusteredUploadItem,type UploadPhase,type UploadResult,type UploadableUploadItem,-} from "@/gallery/services/upload";+} from "@/public-album/upload/pipeline";import {metadataJSONMapKeyForJSON,tryParseTakeoutMetadataJSON,type ParsedMetadataJSON,-} from "@/gallery/services/upload/metadata-json";+} from "@/public-album/upload/pipeline/metadata-json";import UploadService, {areLivePhotoAssets,isUploadCancelledError,@@ -21,7 +21,7 @@ import UploadService, {uploadItemFileName,type PotentialLivePhotoAsset,type UploadAsset,-} from "@/gallery/services/upload/upload-service";+} from "@/public-album/upload/pipeline/upload-service";import { createComlinkCryptoWorker } from "ente-base/crypto";import { type CryptoWorker } from "ente-base/crypto/worker";import { lowercaseExtension, nameAndExtension } from "ente-base/file-name";diff --git a/web/apps/albums/src/public-album/utils/canvas-integrity.ts b/web/apps/albums/src/public-album/upload/utils/canvas-integrity.tssimilarity index 100%rename from web/apps/albums/src/public-album/utils/canvas-integrity.tsrename to web/apps/albums/src/public-album/upload/utils/canvas-integrity.tsdiff --git a/web/apps/albums/src/gallery/components/viewer/AddNameModal.tsx b/web/apps/albums/src/public-album/viewer/components/AddNameModal.tsxsimilarity index 100%rename from web/apps/albums/src/gallery/components/viewer/AddNameModal.tsxrename to web/apps/albums/src/public-album/viewer/components/AddNameModal.tsxdiff --git a/web/apps/albums/src/gallery/components/viewer/CommentsSidebar.tsx b/web/apps/albums/src/public-album/viewer/components/CommentsSidebar.tsxsimilarity index 99%rename from web/apps/albums/src/gallery/components/viewer/CommentsSidebar.tsxrename to web/apps/albums/src/public-album/viewer/components/CommentsSidebar.tsxindex 98cdbcf74b..2a1af4bcbf 100644--- a/web/apps/albums/src/gallery/components/viewer/CommentsSidebar.tsx+++ b/web/apps/albums/src/public-album/viewer/components/CommentsSidebar.tsx@@ -1,15 +1,15 @@import {addPublicComment,deletePublicComment,-} from "@/albums/services/public-comment";+} from "@/public-album/social/api/public-comment";import {addPublicCommentReaction,createAnonIdentity,deletePublicReaction,getStoredAnonIdentity,-} from "@/albums/services/public-reaction";-import { downloadManager } from "@/gallery/services/download";-import { getAvatarColor } from "@/gallery/utils/avatar-colors";+} from "@/public-album/social/api/public-reaction";+import { downloadManager } from "@/public-album/download/services/download-manager";+import { getAvatarColor } from "@/shared/utils/avatar-colors";import CloseIcon from "@mui/icons-material/Close";import {Avatar,@@ -36,10 +36,10 @@ import React, {useRef,useState,} from "react";+import { type Comment, type UnifiedReaction } from "../lib/social-types";import { AddNameModal } from "./AddNameModal";import { PublicCommentModal } from "./PublicCommentModal";import { PublicLikeModal } from "./PublicLikeModal";-import { type Comment, type UnifiedReaction } from "./social-types";// =============================================================================// Iconsdiff --git a/web/apps/albums/src/gallery/components/FileInfo.tsx b/web/apps/albums/src/public-album/viewer/components/FileInfo.tsxsimilarity index 98%rename from web/apps/albums/src/gallery/components/FileInfo.tsxrename to web/apps/albums/src/public-album/viewer/components/FileInfo.tsxindex eca960bd95..6b93b84c14 100644--- a/web/apps/albums/src/gallery/components/FileInfo.tsx+++ b/web/apps/albums/src/public-album/viewer/components/FileInfo.tsx@@ -1,6 +1,5 @@-import { CopyButton } from "@/gallery/components/FileInfoComponents";-import { tagNumericValue, type RawExifTags } from "@/gallery/services/exif";-import { formattedByteSize } from "@/gallery/utils/units";+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";@@ -38,6 +37,7 @@ 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/gallery/components/FileInfoComponents.tsx b/web/apps/albums/src/public-album/viewer/components/FileInfoComponents.tsxsimilarity index 100%rename from web/apps/albums/src/gallery/components/FileInfoComponents.tsxrename to web/apps/albums/src/public-album/viewer/components/FileInfoComponents.tsxdiff --git a/web/apps/albums/src/gallery/components/viewer/FileViewer.tsx b/web/apps/albums/src/public-album/viewer/components/FileViewer.tsxsimilarity index 99%rename from web/apps/albums/src/gallery/components/viewer/FileViewer.tsxrename to web/apps/albums/src/public-album/viewer/components/FileViewer.tsxindex 03287b10e6..9b84ef6bc0 100644--- a/web/apps/albums/src/gallery/components/viewer/FileViewer.tsx+++ b/web/apps/albums/src/public-album/viewer/components/FileViewer.tsx@@ -6,8 +6,17 @@ import {getPublicParticipantsMaskedEmails,getPublicSocialDiff,getStoredAnonIdentity,-} from "@/albums/services/public-reaction";-import { FileInfo, type FileInfoExif } from "@/gallery/components/FileInfo";+} from "@/public-album/social/api/public-reaction";+import { type Comment, type UnifiedReaction } from "../lib/social-types";+import { fileInfoExifForFile, type ItemData } from "../lib/data-source";+import {+ FileViewerPhotoSwipe,+ moreButtonID,+ moreMenuID,+ resetMoreMenuButtonOnMenuClose,+ type FileViewerPhotoSwipeDelegate,+} from "../lib/photoswipe";+import { FileInfo, type FileInfoExif } from "./FileInfo";import ContentCopyIcon from "@mui/icons-material/ContentCopy";import FullscreenExitOutlinedIcon from "@mui/icons-material/FullscreenExitOutlined";import FullscreenOutlinedIcon from "@mui/icons-material/FullscreenOutlined";@@ -34,17 +43,8 @@ import { t } from "i18next";import React, { useCallback, useEffect, useRef, useState } from "react";import { AddNameModal } from "./AddNameModal";import { CommentsSidebar } from "./CommentsSidebar";-import { fileInfoExifForFile, type ItemData } from "./data-source";import { LikesSidebar } from "./LikesSidebar";-import {- FileViewerPhotoSwipe,- moreButtonID,- moreMenuID,- resetMoreMenuButtonOnMenuClose,- type FileViewerPhotoSwipeDelegate,-} from "./photoswipe";import { PublicLikeModal } from "./PublicLikeModal";-import { type Comment, type UnifiedReaction } from "./social-types";const fileViewerBackStateKey = "__enteFileViewerBackState";diff --git a/web/apps/albums/src/gallery/components/viewer/LikesSidebar.tsx b/web/apps/albums/src/public-album/viewer/components/LikesSidebar.tsxsimilarity index 98%rename from web/apps/albums/src/gallery/components/viewer/LikesSidebar.tsxrename to web/apps/albums/src/public-album/viewer/components/LikesSidebar.tsxindex 6c1c327f38..d7b5ae9925 100644--- a/web/apps/albums/src/gallery/components/viewer/LikesSidebar.tsx+++ b/web/apps/albums/src/public-album/viewer/components/LikesSidebar.tsx@@ -1,6 +1,6 @@-import { getStoredAnonIdentity } from "@/albums/services/public-reaction";-import { downloadManager } from "@/gallery/services/download";-import { getAvatarColor } from "@/gallery/utils/avatar-colors";+import { getStoredAnonIdentity } from "@/public-album/social/api/public-reaction";+import { downloadManager } from "@/public-album/download/services/download-manager";+import { getAvatarColor } from "@/shared/utils/avatar-colors";import CloseIcon from "@mui/icons-material/Close";import {Avatar,@@ -23,7 +23,7 @@ import React, {useRef,useState,} from "react";-import { type UnifiedReaction } from "./social-types";+import { type UnifiedReaction } from "../lib/social-types";// =============================================================================// Iconsdiff --git a/web/apps/albums/src/public-album/components/PublicAlbumSingleFileViewer.tsx b/web/apps/albums/src/public-album/viewer/components/PublicAlbumSingleFileViewer.tsxsimilarity index 98%rename from web/apps/albums/src/public-album/components/PublicAlbumSingleFileViewer.tsxrename to web/apps/albums/src/public-album/viewer/components/PublicAlbumSingleFileViewer.tsxindex cdba01a7ce..8c5b181e28 100644--- a/web/apps/albums/src/public-album/components/PublicAlbumSingleFileViewer.tsx+++ b/web/apps/albums/src/public-album/viewer/components/PublicAlbumSingleFileViewer.tsx@@ -1,9 +1,7 @@-import type { AddSaveGroup } from "@/gallery/components/utils/save-groups";-import { FileViewer } from "@/gallery/components/viewer/FileViewer";-import { createPSRegisterElementIconHTML } from "@/gallery/components/viewer/icons";-import { downloadManager } from "@/gallery/services/download";-import { LazyNotification } from "@/public-album/components/lazy-ui";-import { getEnteURL } from "@/public-album/utils/public-album";+import { LazyNotification } from "@/app/lazy/global-ui";+import { downloadManager } from "@/public-album/download/services/download-manager";+import { getEnteURL } from "@/public-album/access/utils/external-links";+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";@@ -33,6 +31,8 @@ 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 {file: EnteFile;@@ -354,7 +354,7 @@ export const PublicAlbumSingleFileViewer: React.FC<const handleDownload = useCallback(async (targetFile: EnteFile) => {const { downloadAndSaveFiles } = await import(- "@/gallery/services/save"+ "@/public-album/download/services/save");return downloadAndSaveFiles([targetFile],diff --git a/web/apps/albums/src/gallery/components/viewer/PublicCommentModal.tsx b/web/apps/albums/src/public-album/viewer/components/PublicCommentModal.tsxsimilarity index 100%rename from web/apps/albums/src/gallery/components/viewer/PublicCommentModal.tsxrename to web/apps/albums/src/public-album/viewer/components/PublicCommentModal.tsxdiff --git a/web/apps/albums/src/gallery/components/viewer/PublicFeedSidebar.tsx b/web/apps/albums/src/public-album/viewer/components/PublicFeedSidebar.tsxsimilarity index 99%rename from web/apps/albums/src/gallery/components/viewer/PublicFeedSidebar.tsxrename to web/apps/albums/src/public-album/viewer/components/PublicFeedSidebar.tsxindex b811b5c9f7..13288689af 100644--- a/web/apps/albums/src/gallery/components/viewer/PublicFeedSidebar.tsx+++ b/web/apps/albums/src/public-album/viewer/components/PublicFeedSidebar.tsx@@ -4,9 +4,9 @@ import {getPublicParticipantsMaskedEmails,type PublicFeedComment,type PublicFeedReaction,-} from "@/albums/services/public-reaction";-import { downloadManager } from "@/gallery/services/download";-import { getAvatarColor } from "@/gallery/utils/avatar-colors";+} from "@/public-album/social/api/public-reaction";+import { downloadManager } from "@/public-album/download/services/download-manager";+import { getAvatarColor } from "@/shared/utils/avatar-colors";import CloseIcon from "@mui/icons-material/Close";import {Avatar,diff --git a/web/apps/albums/src/gallery/components/viewer/PublicLikeModal.tsx b/web/apps/albums/src/public-album/viewer/components/PublicLikeModal.tsxsimilarity index 100%rename from web/apps/albums/src/gallery/components/viewer/PublicLikeModal.tsxrename to web/apps/albums/src/public-album/viewer/components/PublicLikeModal.tsxdiff --git a/web/apps/albums/src/gallery/components/viewer/data-source.ts b/web/apps/albums/src/public-album/viewer/lib/data-source.tssimilarity index 98%rename from web/apps/albums/src/gallery/components/viewer/data-source.tsrename to web/apps/albums/src/public-album/viewer/lib/data-source.tsindex 78c3c3d542..8a951cf5b5 100644--- a/web/apps/albums/src/gallery/components/viewer/data-source.ts+++ b/web/apps/albums/src/public-album/viewer/lib/data-source.ts@@ -1,10 +1,10 @@-import type { FileInfoExif } from "@/gallery/components/FileInfo";-import { downloadManager } from "@/gallery/services/download";-import { extractRawExif, parseExif } from "@/gallery/services/exif";+import { downloadManager } from "@/public-album/download/services/download-manager";+import { extractRawExif, parseExif } from "@/public-album/media/metadata/exif";import {hlsPlaylistDataForFile,type HLSPlaylistDataForFile,-} from "@/gallery/services/video";+} from "@/public-album/media/video/preview";+import type { FileInfoExif } from "@/public-album/viewer/components/FileInfo";import log from "ente-base/log";import type { EnteFile } from "ente-media/file";import { FileType } from "ente-media/file-type";diff --git a/web/apps/albums/src/gallery/components/viewer/icons.tsx b/web/apps/albums/src/public-album/viewer/lib/icons.tsxsimilarity index 100%rename from web/apps/albums/src/gallery/components/viewer/icons.tsxrename to web/apps/albums/src/public-album/viewer/lib/icons.tsxdiff --git a/web/apps/albums/src/gallery/components/viewer/lazy.ts b/web/apps/albums/src/public-album/viewer/lib/lazy.tssimilarity index 86%rename from web/apps/albums/src/gallery/components/viewer/lazy.tsrename to web/apps/albums/src/public-album/viewer/lib/lazy.tsindex 5f4f78ab0c..44248f6cf3 100644--- a/web/apps/albums/src/gallery/components/viewer/lazy.ts+++ b/web/apps/albums/src/public-album/viewer/lib/lazy.ts@@ -1,9 +1,9 @@import dynamic from "next/dynamic";-import type { FileViewerProps } from "./FileViewer";-import type { PublicFeedSidebarProps } from "./PublicFeedSidebar";+import type { FileViewerProps } from "../components/FileViewer";+import type { PublicFeedSidebarProps } from "../components/PublicFeedSidebar";-const loadFileViewer = () => import("./FileViewer");-const loadPublicFeedSidebar = () => import("./PublicFeedSidebar");+const loadFileViewer = () => import("../components/FileViewer");+const loadPublicFeedSidebar = () => import("../components/PublicFeedSidebar");export const LazyFileViewer = dynamic<FileViewerProps>(() => loadFileViewer().then(({ FileViewer }) => FileViewer),diff --git a/web/apps/albums/src/gallery/components/viewer/photoswipe.ts b/web/apps/albums/src/public-album/viewer/lib/photoswipe.tssimilarity index 99%rename from web/apps/albums/src/gallery/components/viewer/photoswipe.tsrename to web/apps/albums/src/public-album/viewer/lib/photoswipe.tsindex 3cda405e47..22e16786e9 100644--- a/web/apps/albums/src/gallery/components/viewer/photoswipe.ts+++ b/web/apps/albums/src/public-album/viewer/lib/photoswipe.ts@@ -21,7 +21,7 @@ import {import {type FileViewerAnnotatedFile,type FileViewerProps,-} from "./FileViewer";+} from "../components/FileViewer";import {commentSVGPath,createPSRegisterElementIconHTML,diff --git a/web/apps/albums/src/gallery/components/viewer/social-types.ts b/web/apps/albums/src/public-album/viewer/lib/social-types.tssimilarity index 100%rename from web/apps/albums/src/gallery/components/viewer/social-types.tsrename to web/apps/albums/src/public-album/viewer/lib/social-types.tsdiff --git a/web/apps/albums/src/gallery/components/utils/use-file-input.ts b/web/apps/albums/src/shared/hooks/useFileInput.tssimilarity index 100%rename from web/apps/albums/src/gallery/components/utils/use-file-input.tsrename to web/apps/albums/src/shared/hooks/useFileInput.tsdiff --git a/web/apps/albums/src/photos/components/utils/use-loading-bar.ts b/web/apps/albums/src/shared/hooks/useLoadingBar.tssimilarity index 100%rename from web/apps/albums/src/photos/components/utils/use-loading-bar.tsrename to web/apps/albums/src/shared/hooks/useLoadingBar.tsdiff --git a/web/apps/albums/src/gallery/components/utils/save-groups.ts b/web/apps/albums/src/shared/state/save-groups.tssimilarity index 100%rename from web/apps/albums/src/gallery/components/utils/save-groups.tsrename to web/apps/albums/src/shared/state/save-groups.tsdiff --git a/web/apps/albums/src/photos/components/Notification.tsx b/web/apps/albums/src/shared/ui/feedback/Notification.tsxsimilarity index 100%rename from web/apps/albums/src/photos/components/Notification.tsxrename to web/apps/albums/src/shared/ui/feedback/Notification.tsxdiff --git a/web/apps/albums/src/photos/components/ThemedLoadingBar.tsx b/web/apps/albums/src/shared/ui/feedback/ThemedLoadingBar.tsxsimilarity index 100%rename from web/apps/albums/src/photos/components/ThemedLoadingBar.tsxrename to web/apps/albums/src/shared/ui/feedback/ThemedLoadingBar.tsxdiff --git a/web/apps/albums/src/photos/components/gallery/ListHeader.tsx b/web/apps/albums/src/shared/ui/gallery/GalleryItemsHeader.tsxsimilarity index 100%rename from web/apps/albums/src/photos/components/gallery/ListHeader.tsxrename to web/apps/albums/src/shared/ui/gallery/GalleryItemsHeader.tsxdiff --git a/web/apps/albums/src/photos/components/PlaceholderThumbnails.tsx b/web/apps/albums/src/shared/ui/media/PlaceholderThumbnails.tsxsimilarity index 100%rename from web/apps/albums/src/photos/components/PlaceholderThumbnails.tsxrename to web/apps/albums/src/shared/ui/media/PlaceholderThumbnails.tsxdiff --git a/web/apps/albums/src/gallery/utils/avatar-colors.ts b/web/apps/albums/src/shared/utils/avatar-colors.tssimilarity index 100%rename from web/apps/albums/src/gallery/utils/avatar-colors.tsrename to web/apps/albums/src/shared/utils/avatar-colors.tsdiff --git a/web/apps/albums/src/gallery/utils/units.ts b/web/apps/albums/src/shared/utils/byte-size.tssimilarity index 100%rename from web/apps/albums/src/gallery/utils/units.tsrename to web/apps/albums/src/shared/utils/byte-size.tsdiff --git a/web/apps/albums/src/photos/components/utils/thumbnail-grid-layout.ts b/web/apps/albums/src/shared/utils/thumbnail-grid-layout.tssimilarity index 100%rename from web/apps/albums/src/photos/components/utils/thumbnail-grid-layout.tsrename to web/apps/albums/src/shared/utils/thumbnail-grid-layout.ts