π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Make albums app self-contained
Anand Baburajanfd5c382946eb
diff --git a/web/apps/albums/package.json b/web/apps/albums/package.jsonindex 2fec424474..7d1dfb8b05 100644--- a/web/apps/albums/package.json+++ b/web/apps/albums/package.json@@ -18,7 +18,6 @@"debounce": "^2.2.0","ente-base": "*","ente-media": "*",- "ente-new": "*","ente-utils": "*","exifreader": "^4.32.0","file-type": "21.3.1",diff --git a/web/apps/albums/src/albums/components/UploaderNameInput.tsx b/web/apps/albums/src/albums/components/UploaderNameInput.tsxnew file mode 100644index 0000000000..78cf0a94e2--- /dev/null+++ b/web/apps/albums/src/albums/components/UploaderNameInput.tsx@@ -0,0 +1,381 @@+import { User03Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import CloseIcon from "@mui/icons-material/Close";+import {+ Box,+ Button,+ Dialog,+ IconButton,+ styled,+ TextField,+ Typography,+} from "@mui/material";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import log from "ente-base/log";+import { useFormik } from "formik";+import { t } from "i18next";+import React from "react";++// =============================================================================+// Sparkle Icons+// =============================================================================++const SparkleTopRight: React.FC = () => (+ <svg+ width="14"+ height="16"+ viewBox="0 0 20 22"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ style={{ position: "absolute", top: 0, right: 8 }}+ >+ <path+ d="M19.728 9.21189C15.334 9.91374 11.912 12.6353 11.37 16.3181C11.912 12.6353 9.421 9.04853 5.4114 7.10627C9.806 6.40442 13.228 3.68284 13.77 7.55054e-05C13.228 3.68284 15.719 7.26962 19.728 9.21189Z"+ fill="#08C225"+ />+ </svg>+);++const SparkleBottomRight: React.FC = () => (+ <svg+ width="22"+ height="26"+ viewBox="0 0 32 36"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ style={{ position: "absolute", bottom: 0, right: -8 }}+ >+ <path+ d="M31.579 17.9746C23.591 18.7003 17.114 23.1692 15.689 29.722C17.114 23.1692 13.077 16.4145 6.1117 12.438C14.099 11.7122 20.576 7.2434 22.001 0.6902C20.576 7.2434 24.613 13.9981 31.579 17.9746Z"+ fill="#08C225"+ />+ </svg>+);++const SparkleBottomLeft: React.FC = () => (+ <svg+ width="18"+ height="16"+ viewBox="0 0 26 22"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ style={{ position: "absolute", bottom: 8, left: -8 }}+ >+ <path+ d="M25.9639 10.8477C19.9399 13.182 15.9104 18.0874 16.263 23.48C15.9104 18.0874 11.2832 13.7544 4.99991 12.2184C11.0238 9.884 15.0533 4.9787 14.7007 -0.4139C15.0533 4.9787 19.6805 9.3117 25.9639 10.8477Z"+ fill="#08C225"+ />+ </svg>+);++// =============================================================================+// Types+// =============================================================================++type UploaderNameInputProps = ModalVisibilityProps & {+ /**+ * The existing uploader name to prefill.+ */+ uploaderName: string;+ /**+ * Count of the number of files that the uploader is trying to upload.+ */+ uploadFileCount: number;+ /**+ * Callback invoked when the user presses submit after entering a name.+ */+ onSubmit: (name: string) => void | Promise<void>;+};++/**+ * A dialog asking the uploader to a public album to provide their name so that+ * other folks can know who uploaded a given photo in the shared album.+ */+export const UploaderNameInput: React.FC<UploaderNameInputProps> = ({+ open,+ onClose,+ uploaderName,+ uploadFileCount,+ onSubmit,+}) => {+ return (+ <StyledDialog open={open} onClose={onClose}>+ <DialogWrapper>+ <CloseButton onClick={onClose}>+ <CloseIcon sx={{ fontSize: 20 }} />+ </CloseButton>++ <ContentContainer>+ <IllustrationContainer>+ <SparkleTopRight />+ <SparkleBottomRight />+ <SparkleBottomLeft />+ <IllustrationWrapper>+ <HugeiconsIcon+ icon={User03Icon}+ size={28}+ color="#fff"+ strokeWidth={1.8}+ />+ </IllustrationWrapper>+ </IllustrationContainer>++ <TitleSection>+ <Title>{t("enter_name")}</Title>+ <Subtitle>{t("uploader_name_hint")}</Subtitle>+ </TitleSection>++ <UploaderNameInputForm+ {...{+ onClose,+ uploaderName,+ uploadFileCount,+ onSubmit,+ }}+ />+ </ContentContainer>+ </DialogWrapper>+ </StyledDialog>+ );+};++/**+ * The form that obtains the textual input of the uploader name.+ *+ * It is kept as a separate component so that it gets recreated on prop changes+ * (e.g. uploaderName changes).+ */+export const UploaderNameInputForm: React.FC<+ Omit<UploaderNameInputProps, "open">+> = ({ onClose, uploaderName, uploadFileCount, onSubmit }) => {+ const formik = useFormik({+ initialValues: { value: uploaderName },+ onSubmit: async (values, { setFieldError }) => {+ const value = values.value;+ const setValueFieldError = (message: string) =>+ setFieldError("value", message);++ if (!value) {+ setValueFieldError(t("required"));+ return;+ }+ try {+ await onSubmit(value);+ onClose();+ } catch (e) {+ log.error(`Failed to submit input ${value}`, e);+ setValueFieldError(t("generic_error"));+ }+ },+ });++ return (+ <FormContainer onSubmit={formik.handleSubmit}>+ <StyledTextField+ name="value"+ value={formik.values.value}+ onChange={formik.handleChange}+ type="text"+ variant="standard"+ fullWidth+ autoFocus+ hiddenLabel+ aria-label={t("name")}+ placeholder={t("name_placeholder")}+ disabled={formik.isSubmitting}+ error={!!formik.errors.value}+ helperText={formik.errors.value}+ />+ <ButtonsSection>+ <SubmitButton+ type="submit"+ variant="contained"+ disabled={+ formik.isSubmitting || !formik.values.value.trim()+ }+ hasName={!!formik.values.value.trim()}+ >+ {formik.isSubmitting+ ? t("loading")+ : t("add_photos_count", { count: uploadFileCount })}+ </SubmitButton>+ </ButtonsSection>+ </FormContainer>+ );+};++// =============================================================================+// Styled Components+// =============================================================================++const StyledDialog = styled(Dialog)(({ theme }) => ({+ "& .MuiDialog-paper": {+ width: 381,+ maxWidth: "calc(100% - 32px)",+ borderRadius: 28,+ backgroundColor: "#fff",+ padding: 0,+ margin: 16,+ overflow: "visible",+ boxShadow: "none",+ border: "1px solid #E0E0E0",+ ...theme.applyStyles("dark", {+ backgroundColor: "#1b1b1b",+ border: "1px solid rgba(255, 255, 255, 0.18)",+ }),+ },+ "& .MuiBackdrop-root": { backgroundColor: "rgba(0, 0, 0, 0.5)" },+}));++const DialogWrapper = styled(Box)(() => ({+ position: "relative",+ padding: "48px 16px 16px 16px",+}));++const CloseButton = styled(IconButton)(({ theme }) => ({+ position: "absolute",+ top: 11,+ right: 12,+ backgroundColor: "#FAFAFA",+ color: "#000",+ padding: 10,+ "&:hover": { backgroundColor: "#F0F0F0" },+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.12)",+ color: "#fff",+ "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.16)" },+ }),+}));++const ContentContainer = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 16,+}));++const IllustrationContainer = styled(Box)(() => ({+ position: "relative",+ width: 100,+ height: 70,+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ marginBottom: 8,+}));++const IllustrationWrapper = styled(Box)(() => ({+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ width: 52,+ height: 52,+ borderRadius: "50%",+ backgroundColor: "#08C225",+}));++const TitleSection = styled(Box)(() => ({+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 9,+ textAlign: "center",+ marginBottom: 8,+}));++const Title = styled(Typography)(({ theme }) => ({+ fontWeight: 600,+ fontSize: 24,+ lineHeight: "28px",+ letterSpacing: "-0.48px",+ color: "#000",+ ...theme.applyStyles("dark", { color: "#fff" }),+}));++const Subtitle = styled(Typography)(({ theme }) => ({+ fontWeight: 500,+ fontSize: 14,+ lineHeight: "20px",+ color: "#666666",+ maxWidth: "75%",+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.7)" }),+}));++const FormContainer = styled("form")(() => ({+ width: "100%",+ display: "flex",+ flexDirection: "column",+ gap: 16,+}));++const StyledTextField = styled(TextField)(({ theme }) => ({+ "& .MuiInput-root": {+ height: 54,+ backgroundColor: "#FAFAFA",+ borderRadius: 12,+ "&::before": { borderBottom: "1px solid #E0E0E0" },+ "&::after": { borderBottom: "2px solid #08C225" },+ "&:hover:not(.Mui-disabled)::before": {+ borderBottom: "1px solid #BDBDBD",+ },+ },+ "& .MuiInputBase-input": {+ padding: "0 16px",+ height: "100%",+ boxSizing: "border-box",+ fontSize: 16,+ color: "#000",+ "&::placeholder": { color: "#999", opacity: 1 },+ },+ ...theme.applyStyles("dark", {+ "& .MuiInput-root": {+ backgroundColor: "rgba(255, 255, 255, 0.08)",+ "&::before": { borderBottom: "1px solid rgba(255, 255, 255, 0.3)" },+ "&:hover:not(.Mui-disabled)::before": {+ borderBottom: "1px solid rgba(255, 255, 255, 0.5)",+ },+ },+ "& .MuiInputBase-input": {+ color: "#fff",+ "&::placeholder": { color: "rgba(255, 255, 255, 0.5)" },+ },+ }),+}));++const ButtonsSection = styled(Box)(() => ({+ width: "100%",+ display: "flex",+ flexDirection: "row",+ gap: 12,+}));++const SubmitButton = styled(Button)<{ hasName: boolean }>(+ ({ hasName, theme }) => ({+ display: "flex",+ padding: "16px",+ justifyContent: "center",+ alignItems: "center",+ gap: 8,+ flex: 1,+ borderRadius: 20,+ backgroundColor: hasName ? "#08C225" : "rgba(0, 0, 0, 0.04)",+ fontSize: 16,+ fontWeight: 500,+ textTransform: "none",+ color: hasName ? "#fff" : "#999",+ boxShadow: "none",+ "&:hover": {+ backgroundColor: hasName ? "#07A820" : "rgba(0, 0, 0, 0.08)",+ boxShadow: "none",+ },+ ...theme.applyStyles("dark", {+ backgroundColor: hasName ? "#08C225" : "rgba(255, 255, 255, 0.08)",+ color: hasName ? "#fff" : "rgba(255, 255, 255, 0.5)",+ "&:hover": {+ backgroundColor: hasName+ ? "#07A820"+ : "rgba(255, 255, 255, 0.12)",+ },+ }),+ }),+);diff --git a/web/apps/albums/src/albums/services/public-albums-fdb.ts b/web/apps/albums/src/albums/services/public-albums-fdb.tsnew file mode 100644index 0000000000..82b6ff5e13--- /dev/null+++ b/web/apps/albums/src/albums/services/public-albums-fdb.ts@@ -0,0 +1,306 @@+/**+ * @file Public albums app specific files DB. See: [Note: Files DB].+ */++import {+ LocalCollections,+ LocalEnteFiles,+ localForage,+ LocalTimestamp,+ transformFilesIfNeeded,+} from "ente-gallery/services/files-db";+import { type Collection } from "ente-media/collection";+import type { EnteFile } from "ente-media/file";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";++/**+ * Return all public collections present in our local database.+ *+ * Use {@link savePublicCollections} to update the database.+ */+const savedPublicCollections = async (): Promise<Collection[]> =>+ LocalCollections.parse(+ (await localForage.getItem("public-collections")) ?? [],+ );++/**+ * Replace the list of public collections stored in our local database.+ *+ * This is the setter corresponding to {@link savedPublicCollections}.+ */+const savePublicCollections = (collections: Collection[]) =>+ localForage.setItem("public-collections", collections);++/**+ * Return the saved public collection with the given {@link key} if present in+ * our local database.+ *+ * Use {@link savePublicCollection} to save collections in our local database.+ *+ * @param key The collection key that can be used to identify the public album+ * we want from amongst all the locally saved public albums.+ */+export const savedPublicCollectionByKey = async (+ collectionKey: string,+): Promise<Collection | undefined> =>+ savedPublicCollections().then((cs) =>+ cs.find((c) => c.key == collectionKey),+ );++/**+ * Save a public collection to our local database.+ *+ * The collection can later be retrieved using {@link savedPublicCollection}.+ * The collection can be removed using {@link removePublicCollection}.+ */+export const savePublicCollection = async (collection: Collection) => {+ const collections = await savedPublicCollections();+ await savePublicCollections([+ collection,+ ...collections.filter((c) => c.id != collection.id),+ ]);+};++/**+ * Remove a public collection, identified using its collection key, from our+ * local database.+ *+ * @param key The collection key that can be used to identify the public album+ * we want to remove.+ */+export const removePublicCollectionByKey = async (collectionKey: string) => {+ const collections = await savedPublicCollections();+ await savePublicCollections([+ ...collections.filter((c) => c.key != collectionKey),+ ]);+};++/**+ * Zod schema for a nullish string, with `null` transformed to `undefined`.+ */+const LocalString = z.string().nullish().transform(nullToUndefined);++/**+ * Return the last saved referral code present in our local database.+ *+ * See: [Note: Public albums referral code]. A few more details specific to the+ * persistence of the referral code:+ *+ * 1. The public albums app persists only the referral code for the latest+ * public album that was fetched.+ *+ * 2. This saved value can be read by+ * {@link savedLastPublicCollectionReferralCode}.+ *+ * 3. It gets updated as part of {@link publicAlbumsRemotePull}, which writes+ * out a new value using {@link saveLastPublicCollectionReferralCode}.+ */+export const savedLastPublicCollectionReferralCode = async () =>+ LocalString.parse(await localForage.getItem("public-referral-code"));++/**+ * Update the referral code present in our local database.+ *+ * This is the setter corresponding to+ * {@link savedLastPublicCollectionReferralCode}.+ */+export const saveLastPublicCollectionReferralCode = async (+ referralCode: string,+) => {+ await localForage.setItem("public-referral-code", referralCode);+};++const LocalSavedPublicCollectionFilesEntry = z.object({+ /**+ * The collection, identified by its access token.+ *+ * See: [Note: Public album access token]+ */+ collectionUID: z.string(),+ files: LocalEnteFiles,+});++type LocalSavedPublicCollectionFilesEntry = z.infer<+ typeof LocalSavedPublicCollectionFilesEntry+>;++/**+ * Return all files for a public collection present in our local database.+ *+ * Use {@link savePublicCollectionFiles} to update the list of files in the+ * database, and {@link removePublicCollectionFiles} to remove them.+ *+ * @param accessToken The access token that identifies the public album whose+ * files we want.+ */+export const savedPublicCollectionFiles = async (+ accessToken: string,+): Promise<EnteFile[]> => {+ const entry = (await pcfEntries()).find(+ (e) => e.collectionUID == accessToken,+ );+ return transformFilesIfNeeded(entry ? entry.files : []);+};++/**+ * A convenience routine to read the DB entries for "public-collection-files".+ */+const pcfEntries = async () => {+ // A local alias to avoid the code from looking scary.+ type ES = LocalSavedPublicCollectionFilesEntry[];++ // See: [Note: Avoiding Zod parsing for large DB arrays] for why we use an+ // (implied) cast here instead of parsing using the Zod schema.+ const entries = await localForage.getItem<ES>("public-collection-files");+ return entries ?? [];+};++/**+ * Replace the list of files for a public collection in our local database.+ *+ * This is the setter corresponding to {@link savedPublicCollectionFiles}.+ *+ * @param accessToken The access token that identifies the public album whose+ * files we want to update.+ *+ * @param files The files to save.+ */+export const savePublicCollectionFiles = async (+ accessToken: string,+ files: EnteFile[],+): Promise<void> => {+ await localForage.setItem("public-collection-files", [+ { collectionUID: accessToken, files },+ ...(await pcfEntries()).filter((e) => e.collectionUID != accessToken),+ ]);+};++/**+ * Remove the list of files, in any, in our local database for the given+ * collection (identified by its {@link accessToken}).+ */+export const removePublicCollectionFiles = async (+ accessToken: string,+): Promise<void> => {+ await localForage.setItem("public-collection-files", [+ ...(await pcfEntries()).filter((e) => e.collectionUID != accessToken),+ ]);+};++/**+ * Return the locally persisted "last sync time" for a public collection that we+ * have pulled from remote. This can be used to perform a paginated delta pull+ * from the saved time onwards.+ *+ * Use {@link savePublic CollectionLastSyncTime} to update the value saved in+ * the database, and {@link removePublicCollectionLastSyncTime} to remove the+ * saved value from the database.+ *+ * @param accessToken The access token that identifies the public album whose+ * last sync time we want.+ */+export const savedPublicCollectionLastSyncTime = async (accessToken: string) =>+ LocalTimestamp.parse(+ await localForage.getItem(`public-${accessToken}-time`),+ );++/**+ * Update the locally persisted timestamp that will be returned by subsequent+ * calls to {@link savedPublicCollectionLastSyncTime}.+ */+export const savePublicCollectionLastSyncTime = async (+ accessToken: string,+ time: number,+) => {+ await localForage.setItem(`public-${accessToken}-time`, time);+};++/**+ * Remove the locally persisted timestamp, if any, previously saved for a+ * collection using {@link savedPublicCollectionLastSyncTime}.+ */+export const removePublicCollectionLastSyncTime = async (+ accessToken: string,+) => {+ await localForage.removeItem(`public-${accessToken}-time`);+};++/**+ * Return the access token JWT, if any, present in our local database for the+ * given public collection (as identified by its {@link accessToken}).+ *+ * Use {@link savePublicCollectionAccessTokenJWT} to save the value, and+ * {@link removePublicCollectionAccessTokenJWT} to remove it.+ */+export const savedPublicCollectionAccessTokenJWT = async (+ accessToken: string,+) =>+ LocalString.parse(+ await localForage.getItem(`public-${accessToken}-passkey`),+ );++/**+ * Update the access token JWT in our local database for the given public+ * collection (as identified by its {@link accessToken}).+ *+ * This is the setter corresponding to+ * {@link savedPublicCollectionAccessTokenJWT}.+ */+export const savePublicCollectionAccessTokenJWT = async (+ accessToken: string,+ passwordJWT: string,+) => {+ await localForage.setItem(`public-${accessToken}-passkey`, passwordJWT);+};++/**+ * Remove the access token JWT in our local database for the given public+ * collection (as identified by its {@link accessToken}).+ */+export const removePublicCollectionAccessTokenJWT = async (+ accessToken: string,+) => {+ await localForage.removeItem(`public-${accessToken}-passkey`);+};++/**+ * Return the previously saved uploader name, if any, present in our local+ * database corresponding to a public collection.+ *+ * Use {@link savePublicCollectionUploaderName} to update the persisted value.+ *+ * [Note: Public albums uploader name]+ *+ * Whenever there is an upload to a public album, we ask the person doing the+ * upload for their name. This uploader name is attached as part of the public+ * magic metadata of the file so that other people know who uploaded the file.+ *+ * The public albums app also saves this value, keyed by an identifier for the+ * public collection, in the local database so that it can prefill it the next+ * time there is an upload from the same client.+ *+ * @param accessToken The access token that identifies the public album whose+ * saved uploader name we want.+ */+export const savedPublicCollectionUploaderName = async (accessToken: string) =>+ LocalString.parse(+ await localForage.getItem(`public-${accessToken}-uploaderName`),+ );++/**+ * Update the uploader name present in our local database corresponding to a+ * public collection.+ *+ * This is the setter corresponding to+ * {@link savedPublicCollectionUploaderName}.+ */+export const savePublicCollectionUploaderName = async (+ accessToken: string,+ uploaderName: string,+) => {+ await localForage.setItem(+ `public-${accessToken}-uploaderName`,+ uploaderName,+ );+};diff --git a/web/apps/albums/src/albums/services/public-collection.ts b/web/apps/albums/src/albums/services/public-collection.tsnew file mode 100644index 0000000000..a6af813495--- /dev/null+++ b/web/apps/albums/src/albums/services/public-collection.ts@@ -0,0 +1,265 @@+import { deriveKey } from "ente-base/crypto";+import {+ authenticatedPublicAlbumsRequestHeaders,+ ensureOk,+ type PublicAlbumsCredentials,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import {+ decryptRemoteCollection,+ RemoteCollection,+ type Collection,+ type PublicURL,+} from "ente-media/collection";+import {+ decryptRemoteFile,+ FileDiffResponse,+ type EnteFile,+} from "ente-media/file";+import { z } from "zod";+import {+ removePublicCollectionAccessTokenJWT,+ removePublicCollectionFiles,+ removePublicCollectionLastSyncTime,+ savedPublicCollectionFiles,+ savedPublicCollectionLastSyncTime,+ saveLastPublicCollectionReferralCode,+ savePublicCollection,+ savePublicCollectionFiles,+ savePublicCollectionLastSyncTime,+} from "./public-albums-fdb";++/**+ * Verify with remote that the password entered by the user is the same as the+ * password that was set by the person who shared the public album.+ *+ * The verification is done on a password hash that we check with remote. If+ * they match, remote will provide us with another token that can be used to+ * make API calls for this password protected public album.+ *+ * If they don't match, or if {@link accessToken} itself has expired, then+ * remote will return a HTTP 401.+ *+ * @param publicURL Data about the public album.+ *+ * @param password The password entered by the user.+ *+ * @param token The access token to make API requests for a particular public+ * album.+ *+ * @returns A accessTokenJWT.+ *+ * See [Note: Password token for public albums requests]+ */+export const verifyPublicAlbumPassword = async (+ publicURL: PublicURL,+ password: string,+ accessToken: string,+) => {+ const passwordHash = await deriveKey(+ password,+ // TODO: Fix the types to not require the bang.+ publicURL.nonce!,+ publicURL.opsLimit!,+ publicURL.memLimit!,+ );++ const res = await fetch(+ await apiURL("/public-collection/verify-password"),+ {+ method: "POST",+ headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),+ body: JSON.stringify({ passHash: passwordHash }),+ },+ );+ ensureOk(res);+ return z.object({ jwtToken: z.string() }).parse(await res.json()).jwtToken;+};++/**+ * Fetch a public collection from remote using its access key, decrypt it using+ * the provided key, save the collection in our local database for subsequent+ * use, and return it.+ *+ * This function modifies local state.+ *+ * @param accessToken A public collection access key obtained from the "t="+ * query parameter of the public URL.+ *+ * The access key serves to both identify the public collection, and also+ * authenticate the request. See: [Note: Public album access token].+ *+ * @param collectionKey The base64 encoded key that can be used to decrypt the+ * collection obtained from remote.+ *+ * The collection key is obtained from the fragment portion of the public URL+ * (the fragment is a client side only portion that can be used to have local+ * secrets that are not sent by the browser to the server).+ */+export const pullCollection = async (+ accessToken: string,+ collectionKey: string,+): Promise<{ collection: Collection; referralCode: string }> => {+ const { collection: remoteCollection, referralCode } =+ await getPublicCollectionInfo(accessToken);++ const collection = await decryptRemoteCollection(+ remoteCollection,+ collectionKey,+ );++ await savePublicCollection(collection);+ await saveLastPublicCollectionReferralCode(referralCode);++ return { collection, referralCode };+};++const PublicCollectionInfo = z.object({+ collection: RemoteCollection,+ /**+ * A referral code of the owner of the public album.+ *+ * [Note: Public albums referral code]+ *+ * The information of a public collection contains the referral code of the+ * person who shared the album. This allows both the viewer and the sharer+ * to gain storage bonus.+ */+ referralCode: z.string(),+});++/**+ * Fetch information from remote about a public collection using its access key.+ *+ * Remote only, does not modify local state.+ *+ * @param accessToken A public collection access key.+ */+const getPublicCollectionInfo = async (accessToken: string) => {+ const res = await fetch(await apiURL("/public-collection/info"), {+ headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),+ });+ ensureOk(res);+ return PublicCollectionInfo.parse(await res.json());+};++/**+ * Pull any changes to the files belonging to the given collection, updating our+ * local database and also calling the provided callback.+ *+ * This function modifies local state.+ *+ * The pull uses a persisted timestamp for the most recent change we've already+ * fetched, and will be only fetch the delta of changes since the last pull. The+ * files are fetched in a paginated manner, so the provided callback can get+ * called multiple times during the pull (one for each page).+ *+ * @param credentials A public collection access key and an optional password+ * unlocked access token JWT. The credentials serve to both identify the+ * collection, and authenticate the request.+ *+ * @param collection The public collection corresponding to the credentials.+ *+ * This function assumes that collection has already been pulled from remote and+ * is at its latest, remote, value. This assumption is used to skip fetching+ * files if the collection has not changed on remote (any updates to the files+ * will also increase the updation time of the collection that contains them).+ *+ * @param onSetFiles A callback that is invoked with the consolidated list of+ * files after processing each batch of updates.+ *+ * The provided files are in an arbitrary order, and must be sorted before use.+ *+ * When called:+ * - At least once if there are remote changes to fetch (may be called multiple+ * times if changes span multiple pages)+ * - Once with cached files if the diff is empty on first iteration (handles+ * empty albums on initial load)+ * - Not called if collection is already synced and no updates are needed+ * (updationTime equals last sync time)+ */+export const pullPublicCollectionFiles = async (+ credentials: PublicAlbumsCredentials,+ collection: Collection,+ onSetFiles: (files: EnteFile[]) => void,+) => {+ const { accessToken } = credentials;++ let sinceTime = (await savedPublicCollectionLastSyncTime(accessToken)) ?? 0;++ // Prior to reaching here, we would've already fetched the latest+ // collection. If the updation time of the collection is the same as the+ // last sync time, then we know there were no new updates (since updates to+ // files also increase the updation time of their containing collection).+ if (sinceTime == collection.updationTime) return;++ const files = await savedPublicCollectionFiles(accessToken);+ const filesByID = new Map(files.map((f) => [f.id, f]));+ let callbackInvoked = false;++ while (true) {+ const { diff, hasMore } = await getPublicCollectionDiff(+ credentials,+ sinceTime,+ );+ if (!diff.length) {+ // If the diff is empty on the first iteration, ensure we still+ // notify the caller with the cached state (e.g., empty albums)+ if (!callbackInvoked) {+ onSetFiles(files);+ }+ break;+ }+ for (const change of diff) {+ sinceTime = Math.max(sinceTime, change.updationTime);+ if (change.isDeleted) {+ filesByID.delete(change.id);+ } else {+ filesByID.set(+ change.id,+ await decryptRemoteFile(change, collection.key),+ );+ }+ }++ const updatedFiles = [...filesByID.values()];+ await savePublicCollectionFiles(accessToken, updatedFiles);+ await savePublicCollectionLastSyncTime(accessToken, sinceTime);+ onSetFiles(updatedFiles);+ callbackInvoked = true;++ if (!hasMore) break;+ }+};++/**+ * Fetch the public collection diff to obtain updates to the collection+ * (identified by its {@link credentials}) since {@link sinceTime}.+ *+ * Remote only, does not modify local state.+ */+const getPublicCollectionDiff = async (+ credentials: PublicAlbumsCredentials,+ sinceTime: number,+) => {+ const res = await fetch(+ await apiURL("/public-collection/diff", { sinceTime }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ return FileDiffResponse.parse(await res.json());+};++/**+ * Remove the files, sync time and accessTokenJWT associated with the given+ * collection (identified by its {@link accessToken}).+ *+ * This function modifies local state.+ */+export const removePublicCollectionFileData = async (accessToken: string) => {+ await Promise.all([+ removePublicCollectionAccessTokenJWT(accessToken),+ removePublicCollectionLastSyncTime(accessToken),+ removePublicCollectionFiles(accessToken),+ ]);+};diff --git a/web/apps/albums/src/albums/services/public-comment.ts b/web/apps/albums/src/albums/services/public-comment.tsnew file mode 100644index 0000000000..8fbbfde51b--- /dev/null+++ b/web/apps/albums/src/albums/services/public-comment.ts@@ -0,0 +1,203 @@+import { decryptBox, encryptBox } from "ente-base/crypto";+import {+ authenticatedPublicAlbumsRequestHeaders,+ ensureOk,+ type PublicAlbumsCredentials,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { z } from "zod";+import { type AnonIdentity, getStoredAnonIdentity } from "./public-reaction";++/**+ * A decrypted public comment.+ */+export interface PublicComment {+ id: string;+ collectionID: number;+ fileID?: number;+ parentCommentID?: string;+ userID: number;+ anonUserID?: string;+ /** The decrypted comment text. */+ text: string;+ isDeleted: boolean;+ createdAt: number;+ updatedAt: number;+}++/**+ * Add a comment to a file in a public album (as an anonymous user).+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID for looking up stored identity.+ * @param fileID The ID of the file to comment on.+ * @param text The comment text.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @param parentCommentID Optional parent comment ID for replies.+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.+ * @returns The ID of the created comment.+ */+export const addPublicComment = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ fileID: number,+ text: string,+ collectionKey: string,+ parentCommentID?: string,+ anonIdentity?: AnonIdentity,+): Promise<string> => {+ const identity = anonIdentity ?? getStoredAnonIdentity(collectionID);+ if (!identity) {+ throw new Error("No anonymous identity available");+ }++ const { encryptedData: cipher, nonce } = await encryptBox(+ new TextEncoder().encode(text),+ collectionKey,+ );++ const res = await fetch(await apiURL("/public-collection/comments"), {+ method: "POST",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ fileID,+ cipher,+ nonce,+ parentCommentID,+ anonUserID: identity.anonUserID,+ anonToken: identity.token,+ }),+ });+ ensureOk(res);+ const { id } = CreateCommentResponse.parse(await res.json());+ return id;+};++/**+ * Delete a comment from a public album (as an anonymous user).+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID for looking up stored identity.+ * @param commentID The ID of the comment to delete.+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.+ */+export const deletePublicComment = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ commentID: string,+ anonIdentity?: AnonIdentity,+): Promise<void> => {+ const identity = anonIdentity ?? getStoredAnonIdentity(collectionID);+ if (!identity) {+ throw new Error("No anonymous identity available");+ }++ const res = await fetch(+ await apiURL(`/public-collection/comments/${commentID}`),+ {+ method: "DELETE",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ anonUserID: identity.anonUserID,+ anonToken: identity.token,+ }),+ },+ );+ ensureOk(res);+};++/**+ * Get comments for a file in a public album.+ *+ * @param credentials Public album credentials (access token).+ * @param fileID The ID of the file to get comments for.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Array of decrypted comments for the file.+ */+export const getPublicFileComments = async (+ credentials: PublicAlbumsCredentials,+ fileID: number,+ collectionKey: string,+): Promise<PublicComment[]> => {+ const res = await fetch(+ await apiURL("/public-collection/comments/diff", {+ fileID,+ sinceTime: 0,+ limit: 1000,+ }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ const { comments } = GetPublicCommentsResponse.parse(await res.json());++ const decryptedComments: PublicComment[] = [];+ for (const comment of comments) {+ // Include deleted comments with empty text+ if (comment.isDeleted || !comment.cipher || !comment.nonce) {+ decryptedComments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text: "",+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ });+ continue;+ }+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: comment.cipher, nonce: comment.nonce },+ collectionKey,+ );+ const text = new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ );+ decryptedComments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text,+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ });+ } catch {+ // Skip comments that fail to decrypt+ }+ }+ return decryptedComments;+};++const CreateCommentResponse = z.object({ id: z.string() });++const RemotePublicComment = z.object({+ id: z.string(),+ collectionID: z.number(),+ fileID: z.number().nullish(),+ parentCommentID: z.string().nullish(),+ userID: z.number(),+ anonUserID: z.string().nullish(),+ cipher: z.string().nullish(),+ nonce: z.string().nullish(),+ isDeleted: z.boolean(),+ createdAt: z.number(),+ updatedAt: z.number(),+});++const GetPublicCommentsResponse = z.object({+ comments: z.array(RemotePublicComment),+ hasMore: z.boolean(),+});diff --git a/web/apps/albums/src/albums/services/public-reaction.ts b/web/apps/albums/src/albums/services/public-reaction.tsnew file mode 100644index 0000000000..3eaffec009--- /dev/null+++ b/web/apps/albums/src/albums/services/public-reaction.ts@@ -0,0 +1,781 @@+import { decryptBox, encryptBox } from "ente-base/crypto";+import {+ authenticatedPublicAlbumsRequestHeaders,+ ensureOk,+ type PublicAlbumsCredentials,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { z } from "zod";++/**+ * Fixed length for padded reaction types.+ * All reactions are padded to this length before encryption to prevent+ * length-based analysis of the ciphertext.+ * Max emoji name is ~70 chars, so 100 provides a safe buffer.+ */+const paddedReactionLength = 100;++/**+ * Pad a reaction type to a fixed length using null bytes.+ */+const padReaction = (reactionType: string): string =>+ reactionType.padEnd(paddedReactionLength, "\0");++/**+ * Remove null byte padding from a decrypted reaction type.+ */+const unpadReaction = (paddedReaction: string): string =>+ paddedReaction.replace(/\0+$/, "");++/**+ * Anonymous user identity returned when creating an anon identity.+ */+export interface AnonIdentity {+ anonUserID: string;+ token: string;+ expiresAt: number;+}++/**+ * Storage key prefix for anonymous identity in local storage.+ * The full key is `${prefix}_${collectionID}`.+ */+const ANON_IDENTITY_STORAGE_KEY_PREFIX = "ente_anon_identity";++/**+ * Get the storage key for a specific collection's anonymous identity.+ */+const getStorageKey = (collectionID: number): string =>+ `${ANON_IDENTITY_STORAGE_KEY_PREFIX}_${collectionID}`;++/**+ * Get the stored anonymous identity for a specific collection from local storage.+ *+ * Returns undefined if no identity is stored or if the stored identity has expired.+ * Expired identities are automatically cleared from storage.+ *+ * @param collectionID The collection ID to get the identity for.+ */+export const getStoredAnonIdentity = (+ collectionID: number,+): AnonIdentity | undefined => {+ if (typeof window === "undefined") return undefined;+ const stored = localStorage.getItem(getStorageKey(collectionID));+ if (!stored) return undefined;+ try {+ const identity = JSON.parse(stored) as AnonIdentity;+ // Check if the identity has expired.+ // Server returns expiresAt in microseconds, Date.now() returns milliseconds.+ const nowMicroseconds = Date.now() * 1000;+ if (identity.expiresAt && nowMicroseconds > identity.expiresAt) {+ // Clear expired identity so user can create a fresh one+ clearAnonIdentity(collectionID);+ return undefined;+ }+ return identity;+ } catch {+ return undefined;+ }+};++/**+ * Store the anonymous identity for a specific collection in local storage.+ *+ * @param collectionID The collection ID to store the identity for.+ * @param identity The anonymous identity to store.+ */+export const storeAnonIdentity = (+ collectionID: number,+ identity: AnonIdentity,+): void => {+ if (typeof window === "undefined") return;+ localStorage.setItem(getStorageKey(collectionID), JSON.stringify(identity));+};++/**+ * Clear the stored anonymous identity for a specific collection from local storage.+ *+ * @param collectionID The collection ID to clear the identity for.+ */+export const clearAnonIdentity = (collectionID: number): void => {+ if (typeof window === "undefined") return;+ localStorage.removeItem(getStorageKey(collectionID));+};++/**+ * Create an anonymous identity for a public album.+ *+ * The server will return a unique anonymous user ID and a token that can be+ * used to authenticate future requests (reactions, comments) from this+ * anonymous user.+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID this identity is for.+ * @param userName The name entered by the user.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns The anonymous identity containing anonUserID and token.+ */+export const createAnonIdentity = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ userName: string,+ collectionKey: string,+): Promise<AnonIdentity> => {+ // Encrypt the user name using the collection key+ const { encryptedData: cipher, nonce } = await encryptBox(+ new TextEncoder().encode(userName),+ collectionKey,+ );++ const res = await fetch(await apiURL("/public-collection/anon-identity"), {+ method: "POST",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ cipher, nonce }),+ });+ ensureOk(res);+ const identity = AnonIdentityResponse.parse(await res.json());++ // Store the identity for this collection+ storeAnonIdentity(collectionID, identity);++ return identity;+};++const AnonIdentityResponse = z.object({+ anonUserID: z.string(),+ token: z.string(),+ expiresAt: z.number(),+});++/**+ * Add a reaction to a file in a public album (as an anonymous user).+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID for looking up stored identity.+ * @param fileID The ID of the file to react to.+ * @param reactionType The type of reaction (e.g., "green_heart").+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.+ * @returns The ID of the created reaction.+ */+export const addPublicReaction = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ fileID: number,+ reactionType: string,+ collectionKey: string,+ anonIdentity?: AnonIdentity,+): Promise<string> => {+ const identity = anonIdentity ?? getStoredAnonIdentity(collectionID);+ if (!identity) {+ throw new Error("No anonymous identity available");+ }++ const { encryptedData: cipher, nonce } = await encryptBox(+ new TextEncoder().encode(padReaction(reactionType)),+ collectionKey,+ );++ const res = await fetch(await apiURL("/public-collection/reactions"), {+ method: "POST",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ fileID,+ cipher,+ nonce,+ anonUserID: identity.anonUserID,+ anonToken: identity.token,+ }),+ });+ ensureOk(res);+ const { id } = UpsertReactionResponse.parse(await res.json());+ return id;+};++/**+ * Add a reaction to a comment in a public album (as an anonymous user).+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID for looking up stored identity.+ * @param commentID The ID of the comment to react to.+ * @param reactionType The type of reaction (e.g., "green_heart").+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.+ * @param fileID Optional file ID, required for file-scoped comments.+ * @returns The ID of the created reaction.+ */+export const addPublicCommentReaction = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ commentID: string,+ reactionType: string,+ collectionKey: string,+ anonIdentity?: AnonIdentity,+ fileID?: number,+): Promise<string> => {+ const identity = anonIdentity ?? getStoredAnonIdentity(collectionID);+ if (!identity) {+ throw new Error("No anonymous identity available");+ }++ const { encryptedData: cipher, nonce } = await encryptBox(+ new TextEncoder().encode(padReaction(reactionType)),+ collectionKey,+ );++ const res = await fetch(await apiURL("/public-collection/reactions"), {+ method: "POST",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ commentID,+ fileID,+ cipher,+ nonce,+ anonUserID: identity.anonUserID,+ anonToken: identity.token,+ }),+ });+ ensureOk(res);+ const { id } = UpsertReactionResponse.parse(await res.json());+ return id;+};++/**+ * Delete a reaction from a public album (as an anonymous user).+ *+ * @param credentials Public album credentials (access token).+ * @param collectionID The collection ID for looking up stored identity.+ * @param reactionID The ID of the reaction to delete.+ * @param anonIdentity Optional anonymous identity. If not provided, will use stored identity.+ */+export const deletePublicReaction = async (+ credentials: PublicAlbumsCredentials,+ collectionID: number,+ reactionID: string,+ anonIdentity?: AnonIdentity,+): Promise<void> => {+ const identity = anonIdentity ?? getStoredAnonIdentity(collectionID);+ if (!identity) {+ throw new Error("No anonymous identity available");+ }++ const res = await fetch(+ await apiURL(`/public-collection/reactions/${reactionID}`),+ {+ method: "DELETE",+ headers: {+ ...authenticatedPublicAlbumsRequestHeaders(credentials),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ anonUserID: identity.anonUserID,+ anonToken: identity.token,+ }),+ },+ );+ ensureOk(res);+};++const UpsertReactionResponse = z.object({ id: z.string() });++/**+ * A decrypted public reaction.+ */+export interface PublicReaction {+ id: string;+ fileID: number;+ commentID?: string;+ reactionType: string;+ userID: number;+ anonUserID?: string;+ isDeleted: boolean;+ createdAt: number;+ updatedAt: number;+}++/**+ * Get reactions for a file in a public album.+ *+ * @param credentials Public album credentials (access token).+ * @param fileID The ID of the file to get reactions for.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Array of decrypted reactions for the file.+ */+export const getPublicFileReactions = async (+ credentials: PublicAlbumsCredentials,+ fileID: number,+ collectionKey: string,+): Promise<PublicReaction[]> => {+ const res = await fetch(+ await apiURL("/public-collection/reactions/diff", {+ fileID,+ sinceTime: 0,+ limit: 100,+ }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ const { reactions } = GetPublicReactionsResponse.parse(await res.json());++ const decryptedReactions: PublicReaction[] = [];+ for (const reaction of reactions) {+ // Skip deleted reactions (they have null cipher/nonce)+ if (reaction.isDeleted || !reaction.cipher || !reaction.nonce) continue;+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: reaction.cipher, nonce: reaction.nonce },+ collectionKey,+ );+ const reactionType = unpadReaction(+ new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ ),+ );+ decryptedReactions.push({+ id: reaction.id,+ fileID: reaction.fileID ?? fileID,+ commentID: reaction.commentID ?? undefined,+ reactionType,+ userID: reaction.userID,+ anonUserID: reaction.anonUserID ?? undefined,+ isDeleted: reaction.isDeleted,+ createdAt: reaction.createdAt,+ updatedAt: reaction.updatedAt,+ });+ } catch {+ // Skip reactions that fail to decrypt+ }+ }+ return decryptedReactions;+};++const RemotePublicReaction = z.object({+ id: z.string(),+ collectionID: z.number(),+ fileID: z.number().nullish(),+ commentID: z.string().nullish(),+ userID: z.number(),+ anonUserID: z.string().nullish(),+ cipher: z.string().nullish(),+ nonce: z.string().nullish(),+ isDeleted: z.boolean(),+ createdAt: z.number(),+ updatedAt: z.number(),+});++const GetPublicReactionsResponse = z.object({+ reactions: z.array(RemotePublicReaction),+ hasMore: z.boolean(),+});++/**+ * An anonymous user profile (encrypted).+ */+export interface AnonProfile {+ anonUserID: string;+ userName: string;+}++/**+ * Get anonymous user profiles for a public album.+ *+ * @param credentials Public album credentials (access token).+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Map of anonUserID to decrypted userName.+ */+export const getPublicAnonProfiles = async (+ credentials: PublicAlbumsCredentials,+ collectionKey: string,+): Promise<Map<string, string>> => {+ const res = await fetch(await apiURL("/public-collection/anon-profiles"), {+ headers: authenticatedPublicAlbumsRequestHeaders(credentials),+ });+ ensureOk(res);+ const { profiles } = GetAnonProfilesResponse.parse(await res.json());++ const anonUserNames = new Map<string, string>();+ for (const profile of profiles) {+ if (!profile.cipher || !profile.nonce) continue;+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: profile.cipher, nonce: profile.nonce },+ collectionKey,+ );+ const userName = new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ );+ if (userName) {+ anonUserNames.set(profile.anonUserID, userName);+ }+ } catch {+ // Skip profiles that fail to decrypt+ }+ }+ return anonUserNames;+};++const RemoteAnonProfile = z.object({+ anonUserID: z.string(),+ collectionID: z.number(),+ cipher: z.string().nullish(),+ nonce: z.string().nullish(),+ createdAt: z.number(),+ updatedAt: z.number(),+});++const GetAnonProfilesResponse = z.object({+ profiles: z+ .array(RemoteAnonProfile)+ .nullish()+ .transform((v) => v ?? []),+});++/**+ * A participant with masked email.+ */+export interface Participant {+ userID: number;+ emailMasked: string;+}++/**+ * Get registered participants' masked emails for a public album.+ *+ * This returns masked emails for registered users (album owner/collaborators)+ * who have interacted with the album (comments/reactions).+ *+ * @param credentials Public album credentials (access token).+ * @returns Map of userID to masked email.+ */+export const getPublicParticipantsMaskedEmails = async (+ credentials: PublicAlbumsCredentials,+): Promise<Map<number, string>> => {+ const res = await fetch(+ await apiURL("/public-collection/participants/masked-emails"),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ const { participants } = GetParticipantsResponse.parse(await res.json());++ const userIDToEmail = new Map<number, string>();+ for (const participant of participants) {+ userIDToEmail.set(participant.userID, participant.emailMasked);+ }+ return userIDToEmail;+};++const RemoteParticipant = z.object({+ userID: z.number(),+ emailMasked: z.string(),+});++const GetParticipantsResponse = z.object({+ participants: z.array(RemoteParticipant),+});++// =============================================================================+// Unified Social Diff+// =============================================================================++/**+ * A decrypted public comment.+ */+export interface PublicComment {+ id: string;+ collectionID: number;+ fileID?: number;+ parentCommentID?: string;+ userID: number;+ anonUserID?: string;+ text: string;+ isDeleted: boolean;+ createdAt: number;+ updatedAt: number;+}++/**+ * Result of fetching unified social diff.+ */+export interface PublicSocialDiff {+ comments: PublicComment[];+ reactions: PublicReaction[];+}++/**+ * Get both comments and reactions for a file in a public album in a single API call.+ *+ * @param credentials Public album credentials (access token).+ * @param fileID The ID of the file to get social data for.+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Object containing both decrypted comments and reactions.+ */+export const getPublicSocialDiff = async (+ credentials: PublicAlbumsCredentials,+ fileID: number,+ collectionKey: string,+): Promise<PublicSocialDiff> => {+ const res = await fetch(+ await apiURL("/public-collection/social/diff", {+ fileID,+ sinceTime: 0,+ limit: 1000,+ }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ const data = GetPublicSocialDiffResponse.parse(await res.json());++ // Decrypt comments+ const comments: PublicComment[] = [];+ for (const comment of data.comments) {+ // Include deleted comments with empty text+ if (comment.isDeleted || !comment.cipher || !comment.nonce) {+ comments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text: "",+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ });+ continue;+ }+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: comment.cipher, nonce: comment.nonce },+ collectionKey,+ );+ const text = new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ );+ comments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text,+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ });+ } catch {+ // Skip comments that fail to decrypt+ }+ }++ // Decrypt reactions+ const reactions: PublicReaction[] = [];+ for (const reaction of data.reactions) {+ // Skip deleted reactions (they have null cipher/nonce)+ if (reaction.isDeleted || !reaction.cipher || !reaction.nonce) continue;+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: reaction.cipher, nonce: reaction.nonce },+ collectionKey,+ );+ const reactionType = unpadReaction(+ new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ ),+ );+ reactions.push({+ id: reaction.id,+ fileID: reaction.fileID ?? fileID,+ commentID: reaction.commentID ?? undefined,+ reactionType,+ userID: reaction.userID,+ anonUserID: reaction.anonUserID ?? undefined,+ isDeleted: reaction.isDeleted,+ createdAt: reaction.createdAt,+ updatedAt: reaction.updatedAt,+ });+ } catch {+ // Skip reactions that fail to decrypt+ }+ }++ return { comments, reactions };+};++const RemotePublicComment = z.object({+ id: z.string(),+ collectionID: z.number(),+ fileID: z.number().nullish(),+ parentCommentID: z.string().nullish(),+ userID: z.number(),+ anonUserID: z.string().nullish(),+ cipher: z.string().nullish(),+ nonce: z.string().nullish(),+ isDeleted: z.boolean(),+ createdAt: z.number(),+ updatedAt: z.number(),+});++const GetPublicSocialDiffResponse = z.object({+ comments: z.array(RemotePublicComment),+ reactions: z.array(RemotePublicReaction),+ hasMoreComments: z.boolean(),+ hasMoreReactions: z.boolean(),+});++// =============================================================================+// Public Album Feed+// =============================================================================++/**+ * A public comment extended with isReply flag for feed processing.+ */+export interface PublicFeedComment extends PublicComment {+ /** True if this comment is a reply to another comment. */+ isReply: boolean;+}++/**+ * A public reaction extended with isCommentReply flag for feed processing.+ */+export interface PublicFeedReaction extends PublicReaction {+ /** True if this reaction is on a reply (comment with parent). */+ isCommentReply?: boolean;+}++/**+ * Result of fetching all social data for a public album feed.+ */+export interface PublicAlbumFeed {+ comments: PublicFeedComment[];+ reactions: PublicFeedReaction[];+}++/**+ * Get all comments and reactions for a public album (for the feed).+ *+ * Unlike getPublicSocialDiff which is per-file, this fetches ALL social data+ * for the entire album without filtering by file.+ *+ * @param credentials Public album credentials (access token).+ * @param collectionKey The decrypted collection key (base64 encoded).+ * @returns Object containing all decrypted comments and reactions for the album.+ */+export const getPublicAlbumFeed = async (+ credentials: PublicAlbumsCredentials,+ collectionKey: string,+): Promise<PublicAlbumFeed> => {+ // Fetch all social data without fileID filter+ const res = await fetch(+ await apiURL("/public-collection/social/diff", {+ sinceTime: 0,+ limit: 1000,+ }),+ { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },+ );+ ensureOk(res);+ const data = GetPublicSocialDiffResponse.parse(await res.json());++ // Build a map of comment IDs to their parent status for determining isCommentReply+ const commentParentMap = new Map<string, boolean>();++ // Decrypt comments+ const comments: PublicFeedComment[] = [];+ for (const comment of data.comments) {+ const isReply = !!comment.parentCommentID;+ commentParentMap.set(comment.id, isReply);++ // Include deleted comments with empty text+ if (comment.isDeleted || !comment.cipher || !comment.nonce) {+ comments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text: "",+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ isReply,+ });+ continue;+ }+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: comment.cipher, nonce: comment.nonce },+ collectionKey,+ );+ const text = new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ );+ comments.push({+ id: comment.id,+ collectionID: comment.collectionID,+ fileID: comment.fileID ?? undefined,+ parentCommentID: comment.parentCommentID ?? undefined,+ userID: comment.userID,+ anonUserID: comment.anonUserID ?? undefined,+ text,+ isDeleted: comment.isDeleted,+ createdAt: comment.createdAt,+ updatedAt: comment.updatedAt,+ isReply,+ });+ } catch {+ // Skip comments that fail to decrypt+ }+ }++ // Decrypt reactions+ const reactions: PublicFeedReaction[] = [];+ for (const reaction of data.reactions) {+ // Skip deleted reactions (they have null cipher/nonce)+ if (reaction.isDeleted || !reaction.cipher || !reaction.nonce) continue;+ try {+ const decryptedB64 = await decryptBox(+ { encryptedData: reaction.cipher, nonce: reaction.nonce },+ collectionKey,+ );+ const reactionType = unpadReaction(+ new TextDecoder().decode(+ Uint8Array.from(atob(decryptedB64), (c) => c.charCodeAt(0)),+ ),+ );++ // Determine if this reaction is on a reply by checking the comment's parent status+ let isCommentReply: boolean | undefined;+ if (reaction.commentID) {+ isCommentReply = commentParentMap.get(reaction.commentID);+ }++ reactions.push({+ id: reaction.id,+ fileID: reaction.fileID ?? 0,+ commentID: reaction.commentID ?? undefined,+ isCommentReply,+ reactionType,+ userID: reaction.userID,+ anonUserID: reaction.anonUserID ?? undefined,+ isDeleted: reaction.isDeleted,+ createdAt: reaction.createdAt,+ updatedAt: reaction.updatedAt,+ });+ } catch {+ // Skip reactions that fail to decrypt+ }+ }++ return { comments, reactions };+};diff --git a/web/apps/albums/src/gallery/components/viewer/CommentsSidebar.tsx b/web/apps/albums/src/gallery/components/viewer/CommentsSidebar.tsxindex de1d50a699..896e979826 100644--- a/web/apps/albums/src/gallery/components/viewer/CommentsSidebar.tsx+++ b/web/apps/albums/src/gallery/components/viewer/CommentsSidebar.tsx@@ -21,14 +21,14 @@ import type { EnteFile } from "ente-media/file";import {addPublicComment,deletePublicComment,-} from "ente-new/albums/services/public-comment";+} from "@/albums/services/public-comment";import {addPublicCommentReaction,createAnonIdentity,deletePublicReaction,getStoredAnonIdentity,-} from "ente-new/albums/services/public-reaction";-import type { CollectionSummaries } from "ente-new/photos/services/collection-summary";+} from "@/albums/services/public-reaction";+import type { CollectionSummaries } from "@/photos/services/collection-summary";import i18n, { t } from "i18next";import React, {useCallback,diff --git a/web/apps/albums/src/gallery/components/viewer/FileViewer.tsx b/web/apps/albums/src/gallery/components/viewer/FileViewer.tsxindex 90f74e33af..1e6dac6b8b 100644--- a/web/apps/albums/src/gallery/components/viewer/FileViewer.tsx+++ b/web/apps/albums/src/gallery/components/viewer/FileViewer.tsx@@ -32,7 +32,7 @@ import {getPublicParticipantsMaskedEmails,getPublicSocialDiff,getStoredAnonIdentity,-} from "ente-new/albums/services/public-reaction";+} from "@/albums/services/public-reaction";import { t } from "i18next";import React, {useCallback,diff --git a/web/apps/albums/src/gallery/components/viewer/LikesSidebar.tsx b/web/apps/albums/src/gallery/components/viewer/LikesSidebar.tsxindex babb37024d..7359fee740 100644--- a/web/apps/albums/src/gallery/components/viewer/LikesSidebar.tsx+++ b/web/apps/albums/src/gallery/components/viewer/LikesSidebar.tsx@@ -14,8 +14,8 @@ import log from "ente-base/log";import { downloadManager } from "@/gallery/services/download";import { getAvatarColor } from "@/gallery/utils/avatar-colors";import type { EnteFile } from "ente-media/file";-import { getStoredAnonIdentity } from "ente-new/albums/services/public-reaction";-import type { CollectionSummaries } from "ente-new/photos/services/collection-summary";+import { getStoredAnonIdentity } from "@/albums/services/public-reaction";+import type { CollectionSummaries } from "@/photos/services/collection-summary";import { t } from "i18next";import React, {useCallback,diff --git a/web/apps/albums/src/gallery/components/viewer/PublicFeedSidebar.tsx b/web/apps/albums/src/gallery/components/viewer/PublicFeedSidebar.tsxindex a8ce3abe71..74c09b72bd 100644--- a/web/apps/albums/src/gallery/components/viewer/PublicFeedSidebar.tsx+++ b/web/apps/albums/src/gallery/components/viewer/PublicFeedSidebar.tsx@@ -24,7 +24,7 @@ import {getPublicParticipantsMaskedEmails,type PublicFeedComment,type PublicFeedReaction,-} from "ente-new/albums/services/public-reaction";+} from "@/albums/services/public-reaction";import { t } from "i18next";import React, { useCallback, useEffect, useMemo, useState } from "react";diff --git a/web/apps/albums/src/pages/_app.tsx b/web/apps/albums/src/pages/_app.tsxindex 9aebfacbb5..7ee61e2aa5 100644--- a/web/apps/albums/src/pages/_app.tsx+++ b/web/apps/albums/src/pages/_app.tsx@@ -13,9 +13,9 @@ 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 { ThemedLoadingBar } from "ente-new/photos/components/ThemedLoadingBar";-import { useLoadingBar } from "ente-new/photos/components/utils/use-loading-bar";-import { PhotosAppContext } from "ente-new/photos/types/context";+import { ThemedLoadingBar } from "@/photos/components/ThemedLoadingBar";+import { useLoadingBar } from "@/photos/components/utils/use-loading-bar";+import { PhotosAppContext } from "@/photos/types/context";import { t } from "i18next";import type { AppProps } from "next/app";import { useCallback, useMemo, useState } from "react";diff --git a/web/apps/albums/src/pages/index.tsx b/web/apps/albums/src/pages/index.tsxindex 61ed105b0a..5a61cd8c7c 100644--- a/web/apps/albums/src/pages/index.tsx+++ b/web/apps/albums/src/pages/index.tsx@@ -66,9 +66,9 @@ import { FileType } from "ente-media/file-type";import {GalleryItemsHeaderAdapter,GalleryItemsSummary,-} from "ente-new/photos/components/gallery/ListHeader";-import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";-import { usePhotosAppContext } from "ente-new/photos/types/context";+} from "@/photos/components/gallery/ListHeader";+import { PseudoCollectionID } from "@/photos/services/collection-summary";+import { usePhotosAppContext } from "@/photos/types/context";import { t } from "i18next";import dynamic from "next/dynamic";import { useRouter } from "next/router";@@ -119,10 +119,10 @@ const LazyPasswordUnlockScreen = dynamic<PasswordUnlockScreenProps>();const loadPublicAlbumsFDB = () =>- import("ente-new/albums/services/public-albums-fdb");+ import("@/albums/services/public-albums-fdb");const loadPublicCollectionService = () =>- import("ente-new/albums/services/public-collection");+ import("@/albums/services/public-collection");const loadShareService = () => import("@/gallery/services/share");diff --git a/web/apps/albums/src/photos/components/Notification.tsx b/web/apps/albums/src/photos/components/Notification.tsxnew file mode 100644index 0000000000..7e4f199052--- /dev/null+++ b/web/apps/albums/src/photos/components/Notification.tsx@@ -0,0 +1,273 @@+import CloseIcon from "@mui/icons-material/Close";+import InfoIcon from "@mui/icons-material/InfoOutlined";+import {+ IconButton,+ Snackbar,+ Stack,+ Typography,+ type ButtonProps,+ type SxProps,+ type Theme,+} from "@mui/material";+import { EllipsizedTypography } from "ente-base/components/Typography";+import { RippleDisabledButton } from "ente-base/components/mui/FocusVisibleButton";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import { isSxArray } from "ente-base/components/utils/sx";+import React from "react";++/**+ * Customize the contents of an {@link Notification}.+ */+export interface NotificationAttributes {+ /**+ * If set, then the caption is shown first, then the title.+ *+ * Default is to show the title first, then the caption.+ */+ captionFirst?: boolean;+ /**+ * The color of the notification.+ */+ color: ButtonProps["color"];+ /**+ * Optional override to the default InfoIcon shown at the leading edge of+ * the notification.+ *+ * Default: InfoIcon+ */+ startIcon?: React.ReactNode;+ /**+ * The primary textual content of the notification.+ */+ title: React.ReactNode;+ /**+ * The secondary textual content of the notification.+ *+ * It will be ellipsized if it does not fit into a single line.+ */+ caption?: React.ReactNode;+ /**+ * Callback invoked (if provided) when the user clicks on the notification+ * (anywhere except the close button).+ *+ * The notification is closed when this happens, unless the+ * {@link keepOpenOnClick} property is set on the notification instance.+ */+ onClick?: () => void;+ /**+ * Optional override to the default CloseIcon shown at the trailing edge of+ * the notification.+ *+ * Unlike {@link startIcon} which is not interactable, setting this replaces+ * the close button with a icon button showing the given {@link endIcon},+ * and on clicking that icon {@link onClick} would be called instead of+ * {@link onClose} (which would've been called on clicking the default close+ * button in this position).+ */+ endIcon?: React.ReactNode;+ /**+ * Optional handler when {@link endIcon} is clicked.+ *+ * If not provided, clicks on the end icon behave the same as clicking the+ * notification body.+ */+ onEndIconClick?: () => void;+}++type NotificationProps = ModalVisibilityProps & {+ /**+ * Attributes that customize the contents of the notification, and the+ * actions that happen on clicking it.+ */+ attributes: NotificationAttributes | undefined;+ /**+ * If `true`, then the notification is not closed when it is clicked, and+ * should be closed by pressing the close icon button it contains.+ */+ keepOpenOnClick?: boolean;+ /**+ * Horizontal positioning of the notification.+ *+ * Default: "right".+ */+ horizontal?: "left" | "right";+ /**+ * Vertical positioning of the notification.+ *+ * Default: "bottom".+ */+ vertical?: "top" | "bottom";+ /**+ * Optional time in milliseconds after which the notification closes.+ */+ autoHideDuration?: number;+ /**+ * sx props to customize the appearance of the underlying MUI+ * {@link Snackbar}.+ */+ sx?: SxProps<Theme>;+};++/**+ * A small notification popup shown on some edge of the screen to notify the+ * user of some asynchronous update or error.+ *+ * In Material UI terms, this is a custom "Snackbar".+ *+ * A single Notification component can be shared by multiple sources of+ * notifications (which means that there can't be multiple of them outstanding+ * at the same time from the same source). The source can customize the actual+ * contents and appearance of this notification by providing appropriate+ * {@link NotificationAttributes}.+ */+export const Notification: React.FC<NotificationProps> = ({+ open,+ onClose,+ horizontal,+ vertical,+ autoHideDuration,+ sx,+ attributes,+ keepOpenOnClick,+}) => {+ if (!attributes) return <></>;++ const {+ captionFirst,+ color,+ startIcon,+ title,+ caption,+ endIcon,+ onClick,+ onEndIconClick,+ } = attributes;++ const handleClose: React.MouseEventHandler = (event) => {+ onClose();+ event.stopPropagation();+ };++ const handleClick = () => {+ onClick?.();+ if (!keepOpenOnClick) onClose();+ };++ const handleEndIconClick: React.MouseEventHandler = (event) => {+ event.stopPropagation();+ if (onEndIconClick) {+ onEndIconClick();+ } else {+ handleClick();+ }+ };++ return (+ <Snackbar+ open={open}+ autoHideDuration={autoHideDuration}+ onClose={(_, reason) => {+ if (reason === "timeout") onClose();+ }}+ anchorOrigin={{+ horizontal: horizontal ?? "right",+ vertical: vertical ?? "bottom",+ }}+ sx={[+ (theme) => ({+ width: "min(320px, 100vw)",+ // If the `color` of the button is a translucent one, e.g.+ // "secondary", then the notification becomes opaque, which+ // is not what we want. So give the entire snackbar a solid+ // background color.+ backgroundColor: "background.default",+ boxShadow: theme.vars.palette.boxShadow.menu,+ }),+ ...(sx ? (isSxArray(sx) ? sx : [sx]) : []),+ ]}+ >+ <RippleDisabledButton+ color={color}+ onClick={handleClick}+ sx={{+ flex: "1",+ padding: "12px 8px 12px 14px",+ borderRadius: "8px",+ }}+ >+ <Stack+ direction="row"+ sx={{+ gap: 2,+ alignItems: "center",+ // Necessary to get the ellipsizing to work.+ width: "100%",+ }}+ >+ <Stack sx={{ svg: { fontSize: "36px" } }}>+ {startIcon ?? <InfoIcon />}+ </Stack>++ <Stack+ sx={{+ flex: 1,+ gap: 0.5,+ // Undo the center alignment done by the button.+ textAlign: "left",+ // This is necessary to trigger the ellipsizing of the+ // text in children.+ overflow: "hidden",+ }}+ >+ {captionFirst ? (+ <>+ {caption && (+ <EllipsizedTypography variant="small">+ {caption}+ </EllipsizedTypography>+ )}+ <Typography sx={{ fontWeight: "medium" }}>+ {title}+ </Typography>+ </>+ ) : (+ <>+ <Typography sx={{ fontWeight: "medium" }}>+ {title}+ </Typography>+ {caption && (+ <EllipsizedTypography variant="small">+ {caption}+ </EllipsizedTypography>+ )}+ </>+ )}+ </Stack>++ {endIcon ? (+ <IconButton+ component="div"+ onClick={handleEndIconClick}+ sx={{ fontSize: "36px", bgcolor: "fill.faint" }}+ >+ {endIcon}+ </IconButton>+ ) : (+ <IconButton+ // Buttons cannot be nested in buttons, so we use a div+ // here instead.+ component="div"+ // Inherit the color of the parent button instead of+ // using the IconButton defaults.+ color="inherit"+ onClick={handleClose}+ sx={{ bgcolor: "fill.faint" }}+ >+ <CloseIcon />+ </IconButton>+ )}+ </Stack>+ </RippleDisabledButton>+ </Snackbar>+ );+};diff --git a/web/apps/albums/src/photos/components/PlaceholderThumbnails.tsx b/web/apps/albums/src/photos/components/PlaceholderThumbnails.tsxnew file mode 100644index 0000000000..cf631d541e--- /dev/null+++ b/web/apps/albums/src/photos/components/PlaceholderThumbnails.tsx@@ -0,0 +1,52 @@+import PhotoOutlinedIcon from "@mui/icons-material/PhotoOutlined";+import PlayCircleOutlineOutlinedIcon from "@mui/icons-material/PlayCircleOutlineOutlined";+import { styled } from "@mui/material";+import { Overlay } from "ente-base/components/containers";+import { FileType } from "ente-media/file-type";+import React from "react";++/**+ * A thumbnail shown when we're loading the thumbnail for a file.+ */+export const LoadingThumbnail = () => (+ <Overlay sx={{ backgroundColor: "fill.faint", borderRadius: "4px" }} />+);++interface StaticThumbnailProps {+ /**+ * The type of the file for which we're showing the placeholder thumbnail.+ *+ * Expected to be one of {@link FileType}.+ */+ fileType: number;+}++/**+ * A thumbnail shown when a file does not have a thumbnail.+ */+export const StaticThumbnail: React.FC<StaticThumbnailProps> = ({+ fileType,+}) => (+ <CenteredOverlay+ sx={{+ backgroundColor: "fill.faint",+ borderWidth: "1px",+ borderStyle: "solid",+ borderColor: "stroke.faint",+ borderRadius: "4px",+ "& > svg": { color: "stroke.muted", fontSize: "50px" },+ }}+ >+ {fileType != FileType.video ? (+ <PhotoOutlinedIcon />+ ) : (+ <PlayCircleOutlineOutlinedIcon />+ )}+ </CenteredOverlay>+);++const CenteredOverlay = styled(Overlay)`+ display: flex;+ justify-content: center;+ align-items: center;+`;diff --git a/web/apps/albums/src/photos/components/ThemedLoadingBar.tsx b/web/apps/albums/src/photos/components/ThemedLoadingBar.tsxnew file mode 100644index 0000000000..1d9b5ffa18--- /dev/null+++ b/web/apps/albums/src/photos/components/ThemedLoadingBar.tsx@@ -0,0 +1,17 @@+import { useTheme } from "@mui/material";+import React from "react";+import LoadingBar, { type LoadingBarRef } from "react-top-loading-bar";++interface ThemedLoadingBarProps {+ ref: React.Ref<LoadingBarRef>;+}++/**+ * A wrapper over the {@link LoadingBar} library component that sets it to use+ * the main accent color from the theme.+ */+export const ThemedLoadingBar: React.FC<ThemedLoadingBarProps> = ({ ref }) => {+ const theme = useTheme();++ return <LoadingBar color={theme.vars.palette.accent.main} ref={ref} />;+};diff --git a/web/apps/albums/src/photos/components/gallery/ListHeader.tsx b/web/apps/albums/src/photos/components/gallery/ListHeader.tsxnew file mode 100644index 0000000000..1979ff5fe5--- /dev/null+++ b/web/apps/albums/src/photos/components/gallery/ListHeader.tsx@@ -0,0 +1,88 @@+import {+ Box,+ Stack,+ styled,+ Typography,+ type TypographyProps,+} from "@mui/material";+import { t } from "i18next";+import React from "react";++interface GalleryItemsSummaryProps {+ /**+ * The name / title for the items that are being shown.+ */+ name: string;+ /**+ * Optional extra props to pass to the {@link Typography} component that+ * shows {@link name}+ */+ nameProps?: TypographyProps;+ /**+ * The number of items being shown.+ */+ fileCount: number;+ /**+ * An optional element, usually an icon, placed after the file count.+ */+ endIcon?: React.ReactNode;+ /**+ * An optional click handler for the name.+ *+ * Note: Do not use this as the primary / only mechanism for the+ * corresponding functionality to be invoked, since this click handler will+ * be accessible only to sighted mouse users. However, it is fine to use it+ * as an alternate means of invoking some function.+ */+ onNameClick?: () => void;+}++/**+ * A component suitable for being used as a summary displayed on top of the of a+ * list of photos (or other items) shown in the gallery.+ */+export const GalleryItemsSummary: React.FC<GalleryItemsSummaryProps> = ({+ name,+ nameProps,+ fileCount,+ endIcon,+ onNameClick,+}) => (+ <div>+ <Typography variant="h3" {...(nameProps ?? {})} onClick={onNameClick}>+ {name}+ </Typography>++ <Stack+ direction="row"+ sx={{+ gap: 1.5,+ // Keep height the same even when there is no endIcon+ minHeight: "24px",+ }}+ >+ <Typography variant="small" sx={{ color: "text.muted" }}>+ {t("photos_count", { count: fileCount })}+ </Typography>+ {endIcon && (+ <Box sx={{ svg: { fontSize: "17px", color: "text.muted" } }}>+ {endIcon}+ </Box>+ )}+ </Stack>+ </div>+);++/**+ * A component suitable for wrapping a component which is acting like a gallery+ * items header so that it fills the entire width (and acts like a "header")+ * when it is displayed in the gallery view.+ *+ * The header view (e.g. a {@link GalleryItemsSummary}) is displayed as part of+ * the gallery items list itself so that it scrolls alongwith the items. This+ * wrapper makes it take the full width of the "row" that it occupies.+ */+export const GalleryItemsHeaderAdapter = styled("div")`+ width: 100%;+ margin-bottom: 12px;+`;diff --git a/web/apps/albums/src/photos/components/utils/thumbnail-grid-layout.ts b/web/apps/albums/src/photos/components/utils/thumbnail-grid-layout.tsnew file mode 100644index 0000000000..cfc1c015cb--- /dev/null+++ b/web/apps/albums/src/photos/components/utils/thumbnail-grid-layout.ts@@ -0,0 +1,90 @@+export const thumbnailGap = 4;+export const thumbnailMaxHeight = 180;+export const thumbnailMaxWidth = 180;+export const thumbnailLayoutMinColumns = 4;++export interface ThumbnailGridLayoutParams {+ /**+ * The overall width available to us.+ *+ * This is the height that is the input to the computation, stashed here so+ * that other parts of the code downstream can also get at it if needed.+ */+ containerWidth: number;+ /**+ * `true` if the container width is classified as a smaller screen for the+ * purpose of the thumbnail grid, and some dimensions are reduced to account+ * for the lesser space available to us.+ */+ isSmallerLayout: boolean;+ /**+ * The inline padding (px) of the thumbnail grid.+ */+ paddingInline: number;+ /**+ * The number of columns in the thumbnail grid.+ */+ columns: number;+ /**+ * The width (px) of each item.+ */+ itemWidth: number;+ /**+ * The height (px) of each item.+ */+ itemHeight: number;+ /**+ * The gap (px) between each grid item.+ */+ gap: number;+}++/**+ * Determine the layout parameters for a grid of thumbnails that would best fit+ * the given width under various constraints.+ *+ * @param containerWidth The width available to the container. In our case,+ * since the thumbnail grids span the entire available width, this is the width+ * of the page itself.+ */+export const computeThumbnailGridLayoutParams = (+ containerWidth: number,+): ThumbnailGridLayoutParams => {+ const isSmallerLayout = !(+ containerWidth >+ thumbnailLayoutMinColumns * thumbnailMaxWidth+ );+ const paddingInline = getGapFromScreenEdge(containerWidth);+ const fittableColumns = getFractionFittableColumns(containerWidth);++ let columns = Math.floor(fittableColumns);+ if (columns < thumbnailLayoutMinColumns) {+ columns = thumbnailLayoutMinColumns;+ }++ const shrinkRatio = getShrinkRatio(containerWidth, columns);+ const itemHeight = thumbnailMaxHeight * shrinkRatio;+ const itemWidth = thumbnailMaxWidth * shrinkRatio;+ const gap = thumbnailGap;++ return {+ containerWidth,+ isSmallerLayout,+ paddingInline,+ columns,+ itemWidth,+ itemHeight,+ gap,+ };+};++const getFractionFittableColumns = (width: number): number =>+ (width - 2 * getGapFromScreenEdge(width) + thumbnailGap) /+ (thumbnailMaxWidth + thumbnailGap);++const getGapFromScreenEdge = (width: number) =>+ width > thumbnailLayoutMinColumns * thumbnailMaxWidth ? 24 : 4;++const getShrinkRatio = (width: number, columns: number) =>+ (width - 2 * getGapFromScreenEdge(width) - (columns - 1) * thumbnailGap) /+ (columns * thumbnailMaxWidth);diff --git a/web/apps/albums/src/photos/components/utils/use-loading-bar.ts b/web/apps/albums/src/photos/components/utils/use-loading-bar.tsnew file mode 100644index 0000000000..c5c7152fed--- /dev/null+++ b/web/apps/albums/src/photos/components/utils/use-loading-bar.ts@@ -0,0 +1,26 @@+import { useCallback, useRef } from "react";+import { type LoadingBarRef } from "react-top-loading-bar";++/**+ * A convenience hook for returning stable functions tied to a+ * {@link LoadingBar} ref.+ *+ * The {@link LoadingBar} component comes from the "react-top-loading-bar"+ * library. To control it, we keep a ref. We want to allow components in our+ * React tree to be able to also control the loading bar, but instead of+ * exposing the ref directly, we export wrapper functions to start and stop the+ * loading bar. This hook returns these functions (and the ref).+ */+export const useLoadingBar = () => {+ const loadingBarRef = useRef<LoadingBarRef | null>(null);++ const showLoadingBar = useCallback(() => {+ loadingBarRef.current?.continuousStart();+ }, []);++ const hideLoadingBar = useCallback(() => {+ loadingBarRef.current?.complete();+ }, []);++ return { loadingBarRef, showLoadingBar, hideLoadingBar };+};diff --git a/web/apps/albums/src/photos/services/collection-summary.ts b/web/apps/albums/src/photos/services/collection-summary.tsnew file mode 100644index 0000000000..0ce77e61ca--- /dev/null+++ b/web/apps/albums/src/photos/services/collection-summary.ts@@ -0,0 +1,259 @@+import type { CollectionType } from "ente-media/collection";+import type { EnteFile } from "ente-media/file";++export type CollectionSummaryType =+ | CollectionType+ | "all"+ | "hiddenItems"+ | "defaultHidden"+ | "archiveItems"+ | "trash"+ | "userFavorites"+ | "sharedIncoming";++export type CollectionSummaryAttribute =+ | CollectionSummaryType+ | "shared"+ | "sharedOutgoing"+ | "sharedIncomingViewer"+ | "sharedIncomingCollaborator"+ | "sharedIncomingAdmin"+ | "sharedOnlyViaLink"+ | "system"+ | "archived"+ | "hideFromCollectionBar"+ | "pinned"+ | "shareePinned";++/**+ * ID of the special {@link CollectionSummary} instances that are not backed by+ * a real {@link Collection}.+ */+export const PseudoCollectionID = {+ /**+ * The "All" section.+ *+ * The "All" section is the default view when the user opens the gallery,+ * showing them all of their unique non-hidden and non-archived files.+ */+ all: 0,+ /**+ * A pseudo-collection containing the individually archived files.+ *+ * The archive items is a pseudo-collection consisting of all the files+ * which have been individually archived. It is what gets shown when the+ * user navigates to the "Archive" section.+ */+ archiveItems: -1,+ /**+ * Trash.+ *+ * This pseudo-collection contains items that are in the user's trash. Each+ * items corresponds to a file that has been deleted, but has not yet been+ * deleted permanently.+ *+ * As a special case, when the trash pseudo collection is being shown, then+ * the corresponding files array will have {@link EnteTrashFile} items+ * instead of normal {@link EnteFile} ones.+ */+ trash: -2,+ /**+ * A placeholder for the uncategorized collection until the real one comes+ * into existence.+ *+ * [Note: Uncategorized placeholder]+ *+ * The user's sole "uncategorized" collection is created on demand the first+ * time we need to move a file out of the last collection it belonged to+ * (yet retain the file).+ *+ * Until the real uncategorized collection comes into existence, we use this+ * dummy placeholder collection as the {@link CollectionSummary} that gets+ * shown if the user navigates to the "Uncategorized" section in the UI.+ */+ uncategorizedPlaceholder: -3,+ /**+ * A pseudo-collection containing the individually hidden files.+ *+ * The "Hidden items" is the default pseudo-collection shown in the "Hidden"+ * section. It consists of the files that the user has individually hidden.+ *+ * It is derived by merging all of the user's "default hidden" albums (See:+ * Note: Multiple "default" hidden collections]).+ *+ * In addition to this "Hidden items" pseudo-collection, the "Hidden"+ * section also shows other albums that were hidden.+ */+ hiddenItems: -4,+} as const;++/**+ * A massaged version of a collection or a pseudo-collection suitable for being+ * directly shown in the UI.+ *+ * From one perspective, this can be thought of as a+ * "CollectionOrPseudoCollection": a group of files listed together in the UI,+ * with the files coming from a real "collection" or some special "section".+ *+ * - In the first case, the underlying listing will be backed by a+ * {@link Collection},+ *+ * - In the second case the files and other attributes comprising the listing+ * will be determined by the special case-specific rules for that particular+ * pseudo-collection.+ *+ * However, even when this is backed by a corresponding "real"+ * {@link Collection}, it adds some extra attributes that make it easier and+ * more efficient for the UI elements to render this collection summary+ * directly. So from that perspective, this can be also be thought of as a+ * "UICollection".+ */+export interface CollectionSummary {+ /**+ * The ID of the underlying {@link Collection}, or one of the predefined+ * {@link PseudoCollectionID}s.+ */+ id: number;+ /**+ * The primary "UI" type for the collection or pseudo-collection.+ *+ * For newer code consider using {@link attributes} instead.+ */+ type: CollectionSummaryType;+ /**+ * Various UI related attributes of the collection or pseudo-collection.+ *+ * This is meant to replace {@link type} gradually. It defines various+ * ad-hoc "UI" attributes which make it easier and more efficient for the UI+ * elements to render the collection summary in the UI.+ */+ attributes: Set<CollectionSummaryAttribute>;+ /**+ * The name of the collection or pseudo-collection surfaced in the UI.+ */+ name: string;+ /**+ * The newest file in the collection or pseudo-collection (if any).+ */+ latestFile: EnteFile | undefined;+ /**+ * The file to show as the cover for the collection or pseudo-collection.+ *+ * This can be one of+ * - A file explicitly chosen by the user.+ * - The latest file.+ * - The oldest file (if the user has set a reverse sort on the collection).+ */+ coverFile: EnteFile | undefined;+ /**+ * The number of files in the underlying collection, or the number of files+ * computed to belong to the pseudo-collection.+ */+ fileCount: number;+ /**+ * The time (epoch microseconds) when the collection was last updated. For+ * pseudo-collections this will (usually) be the updation time of the latest+ * file that it contains.+ */+ updationTime: number | undefined;+ sortPriority: CollectionSummarySortPriority;+ order?: number;+}++/**+ * Collection summaries, indexed by their IDs.+ */+export type CollectionSummaries = Map<number, CollectionSummary>;++/**+ * The sort schemes that can be used when we're showing list of collections+ * (e.g. in the collection bar).+ *+ * This is the list of all possible values, see {@link CollectionsSortBy} for+ * the type.+ */+export const collectionsSortBy = [+ "name-asc",+ "name-desc",+ "creation-time-asc",+ "creation-time-desc",+ "updation-time-asc",+ "updation-time-desc",+] as const;++/**+ * Type of individual {@link collectionsSortBy} values.+ */+export type CollectionsSortBy = (typeof collectionsSortBy)[number];++/**+ * An orderable set collection "priorities".+ *+ * Collection summaries that need to appear prior to other collection summaries+ * get assigned a "priority", which is an otherwise arbitrary integer that only+ * serves as a sort priority (higher being prior).+ *+ * All collections in a higher category appear together, and before collections+ * in lower categories. Within each priority, the collections are sorted by the+ * applicable {@link CollectionsSortBy}.+ */+export const CollectionSummarySortPriority = {+ /**+ * Currently: "All", "Uncategorized", "Hidden items".+ */+ system: 9,+ favorites: 8,+ pinned: 7,+ other: 0,+} as const;++/**+ * The TypeScript type that restricts the possible values to be one from amongst+ * the {@link CollectionSummarySortCategory} constants.+ */+export type CollectionSummarySortPriority =+ (typeof CollectionSummarySortPriority)[keyof typeof CollectionSummarySortPriority];++export const haveOnlySystemCollections = (+ collectionSummaries: CollectionSummaries,+) =>+ [...collectionSummaries.values()].every((cs) =>+ cs.attributes.has("system"),+ );++export const canAddToCollection = ({ attributes }: CollectionSummary) =>+ !attributes.has("system") && !attributes.has("sharedIncomingViewer");++export const canMoveToCollection = ({ attributes }: CollectionSummary) =>+ !attributes.has("system") && !attributes.has("sharedIncoming");++/**+ * Sort an array of collection summaries by the specified sort order.+ *+ * @param collectionSummaries The array of collection summaries to sort+ * @param by The sort order to apply+ * @returns A new sorted array of collection summaries+ */+export const sortCollectionSummaries = (+ collectionSummaries: CollectionSummary[],+ by: CollectionsSortBy,+): CollectionSummary[] => {+ return [...collectionSummaries].sort((a, b) => {+ switch (by) {+ case "name-asc":+ return a.name.localeCompare(b.name);+ case "name-desc":+ return b.name.localeCompare(a.name);+ case "creation-time-asc":+ // Oldest first: lower ID = created earlier.+ return a.id - b.id;+ case "creation-time-desc":+ // Newest first: higher ID = created later.+ return b.id - a.id;+ case "updation-time-asc":+ return (a.updationTime ?? 0) - (b.updationTime ?? 0);+ case "updation-time-desc":+ return (b.updationTime ?? 0) - (a.updationTime ?? 0);+ }+ });+};diff --git a/web/apps/albums/src/photos/types/context.ts b/web/apps/albums/src/photos/types/context.tsnew file mode 100644index 0000000000..a4bcc16152--- /dev/null+++ b/web/apps/albums/src/photos/types/context.ts@@ -0,0 +1,41 @@+import type { NotificationAttributes } from "../components/Notification";+import { createContext, useContext } from "react";++/**+ * The type of the React context available to all pages in the photos app.+ */+export interface PhotosAppContextT {+ /**+ * Show the global activity indicator (a loading bar at the top of the+ * page).+ */+ showLoadingBar: () => void;+ /**+ * Hide the global activity indicator bar.+ */+ hideLoadingBar: () => void;+ /**+ * Show a {@link Notification}, customizing its contents and click behaviour+ * using the provided {@link NotificationAttributes}.+ */+ showNotification: (attributes: NotificationAttributes) => void;+ watchFolderView: boolean;+ setWatchFolderView: (isOpen: boolean) => void;+}++/**+ * The React {@link Context} available to all nodes in the React tree of photos+ * app pages.+ */+export const PhotosAppContext = createContext<PhotosAppContextT | undefined>(+ undefined,+);++/**+ * Utility hook to get the photos {@link PhotosAppContextT}.+ *+ * This context is provided at the top level _app component for the photos app,+ * and thus is available to all React components in the Photos app's React tree.+ */+export const usePhotosAppContext = (): PhotosAppContextT =>+ useContext(PhotosAppContext)!;diff --git a/web/apps/albums/src/public-album/components/DownloadStatusNotifications.tsx b/web/apps/albums/src/public-album/components/DownloadStatusNotifications.tsxindex dda287bfb2..4f773eca2d 100644--- a/web/apps/albums/src/public-album/components/DownloadStatusNotifications.tsx+++ b/web/apps/albums/src/public-album/components/DownloadStatusNotifications.tsx@@ -20,7 +20,7 @@ import {isSaveCompleteWithErrors,type SaveGroup,} from "@/gallery/components/utils/save-groups";-import { Notification } from "ente-new/photos/components/Notification";+import { Notification } from "@/photos/components/Notification";import { t } from "i18next";import { useState } from "react";diff --git a/web/apps/albums/src/public-album/components/FileList.tsx b/web/apps/albums/src/public-album/components/FileList.tsxindex 416f15fdd1..c68c82d417 100644--- a/web/apps/albums/src/public-album/components/FileList.tsx+++ b/web/apps/albums/src/public-album/components/FileList.tsx@@ -12,12 +12,12 @@ import { FileType } from "ente-media/file-type";import {LoadingThumbnail,StaticThumbnail,-} from "ente-new/photos/components/PlaceholderThumbnails";+} from "@/photos/components/PlaceholderThumbnails";import {computeThumbnailGridLayoutParams,thumbnailGap,type ThumbnailGridLayoutParams,-} from "ente-new/photos/components/utils/thumbnail-grid-layout";+} from "@/photos/components/utils/thumbnail-grid-layout";import { batch } from "ente-utils/array";import { t } from "i18next";import React, {diff --git a/web/apps/albums/src/public-album/components/Upload.tsx b/web/apps/albums/src/public-album/components/Upload.tsxindex 6bcf382f64..6dc2d5281c 100644--- a/web/apps/albums/src/public-album/components/Upload.tsx+++ b/web/apps/albums/src/public-album/components/Upload.tsx@@ -40,12 +40,12 @@ import {} from "@/gallery/services/upload/upload-service";import { type Collection } from "ente-media/collection";import type { EnteFile } from "ente-media/file";-import { UploaderNameInput } from "ente-new/albums/components/UploaderNameInput";+import { UploaderNameInput } from "@/albums/components/UploaderNameInput";import {savedPublicCollectionUploaderName,savePublicCollectionUploaderName,-} from "ente-new/albums/services/public-albums-fdb";-import { usePhotosAppContext } from "ente-new/photos/types/context";+} from "@/albums/services/public-albums-fdb";+import { usePhotosAppContext } from "@/photos/types/context";import { firstNonEmpty } from "ente-utils/array";import { t } from "i18next";import React, { useCallback, useEffect, useRef, useState } from "react";diff --git a/web/apps/albums/src/public-album/components/lazy-ui.ts b/web/apps/albums/src/public-album/components/lazy-ui.tsindex 46327edae2..f0686d4399 100644--- a/web/apps/albums/src/public-album/components/lazy-ui.ts+++ b/web/apps/albums/src/public-album/components/lazy-ui.ts@@ -2,7 +2,7 @@ import dynamic from "next/dynamic";export const LazyNotification = dynamic(() =>- import("ente-new/photos/components/Notification").then(+ import("@/photos/components/Notification").then(({ Notification }) => Notification,),{ ssr: false },diff --git a/web/apps/albums/src/public-album/hooks/useNotification.ts b/web/apps/albums/src/public-album/hooks/useNotification.tsindex 966be39c1d..7cacad72ce 100644--- a/web/apps/albums/src/public-album/hooks/useNotification.ts+++ b/web/apps/albums/src/public-album/hooks/useNotification.ts@@ -1,4 +1,4 @@-import { type NotificationAttributes } from "ente-new/photos/components/Notification";+import { type NotificationAttributes } from "@/photos/components/Notification";import { useCallback, useState } from "react";/**diff --git a/web/apps/albums/src/public-album/services/upload-manager.ts b/web/apps/albums/src/public-album/services/upload-manager.tsindex 585d39c48a..dd1a9bdcd6 100644--- a/web/apps/albums/src/public-album/services/upload-manager.ts+++ b/web/apps/albums/src/public-album/services/upload-manager.ts@@ -31,7 +31,7 @@ import type { Collection } from "ente-media/collection";import { type EnteFile } from "ente-media/file";import { FileType } from "ente-media/file-type";import { potentialFileTypeFromExtension } from "ente-media/live-photo";-import { savedPublicCollectionFiles } from "ente-new/albums/services/public-albums-fdb";+import { savedPublicCollectionFiles } from "@/albums/services/public-albums-fdb";import { wait } from "ente-utils/promise";export type FileID = number;