💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Fix the circular zod object import deps
Manav Rathia09c01ce6d67
diff --git a/web/apps/photos/src/components/Sidebar/SubscriptionCard.tsx b/web/apps/photos/src/components/Sidebar/SubscriptionCard.tsxindex 735dc63087..e317a2c745 100644--- a/web/apps/photos/src/components/Sidebar/SubscriptionCard.tsx+++ b/web/apps/photos/src/components/Sidebar/SubscriptionCard.tsx@@ -1,10 +1,10 @@import { Overlay } from "@/base/components/mui/Container";import type { ButtonishProps } from "@/new/photos/components/mui";+import type { UserDetails } from "@/new/photos/services/user-details";import {familyUsage,isPartOfFamilyWithOtherMembers,-} from "@/new/photos/services/plan";-import type { UserDetails } from "@/new/photos/services/user";+} from "@/new/photos/services/user-details";import { bytesInGB, formattedStorageByteSize } from "@/new/photos/utils/units";import { SpaceBetweenFlex } from "@ente/shared/components/Container";import ChevronRightIcon from "@mui/icons-material/ChevronRight";diff --git a/web/apps/photos/src/components/Sidebar/index.tsx b/web/apps/photos/src/components/Sidebar/index.tsxindex 24af8dde14..ccc33f2efa 100644--- a/web/apps/photos/src/components/Sidebar/index.tsx+++ b/web/apps/photos/src/components/Sidebar/index.tsx@@ -19,6 +19,8 @@ import {TRASH_SECTION,} from "@/new/photos/services/collection";import type { CollectionSummaries } from "@/new/photos/services/collection/ui";+import { isInternalUser } from "@/new/photos/services/settings";+import { syncUserDetails } from "@/new/photos/services/user";import {familyAdminEmail,hasExceededStorageQuota,@@ -33,9 +35,8 @@ import {leaveFamily,redirectToCustomerPortal,userDetailsAddOnBonuses,-} from "@/new/photos/services/plan";-import { isInternalUser } from "@/new/photos/services/settings";-import { syncUserDetails, type UserDetails } from "@/new/photos/services/user";+ type UserDetails,+} from "@/new/photos/services/user-details";import { AppContext, useAppContext } from "@/new/photos/types/context";import { initiateEmail, openURL } from "@/new/photos/utils/web";import {diff --git a/web/apps/photos/src/components/Upload/Uploader.tsx b/web/apps/photos/src/components/Upload/Uploader.tsxindex 7a30eb8ef4..6a9fe6d82a 100644--- a/web/apps/photos/src/components/Upload/Uploader.tsx+++ b/web/apps/photos/src/components/Upload/Uploader.tsx@@ -7,12 +7,12 @@ import { CollectionMappingChoiceDialog } from "@/new/photos/components/Collectioimport type { CollectionSelectorAttributes } from "@/new/photos/components/CollectionSelector";import { downloadAppDialogAttributes } from "@/new/photos/components/utils/download";import { exportMetadataDirectoryName } from "@/new/photos/services/export";-import { redirectToCustomerPortal } from "@/new/photos/services/plan";import type {FileAndPath,UploadItem,} from "@/new/photos/services/upload/types";import { UPLOAD_STAGES } from "@/new/photos/services/upload/types";+import { redirectToCustomerPortal } from "@/new/photos/services/user-details";import { AppContext } from "@/new/photos/types/context";import { NotificationAttributes } from "@/new/photos/types/notification";import { firstNonEmpty } from "@/utils/array";diff --git a/web/apps/photos/src/components/pages/gallery/PlanSelector.tsx b/web/apps/photos/src/components/pages/gallery/PlanSelector.tsxindex 9d4c538bc3..0a62d44316 100644--- a/web/apps/photos/src/components/pages/gallery/PlanSelector.tsx+++ b/web/apps/photos/src/components/pages/gallery/PlanSelector.tsx@@ -11,7 +11,7 @@ import type {PlanPeriod,PlansData,Subscription,-} from "@/new/photos/services/plan";+} from "@/new/photos/services/user-details";import {activateStripeSubscription,cancelStripeSubscription,@@ -27,7 +27,7 @@ import {redirectToCustomerPortal,redirectToPaymentsApp,userDetailsAddOnBonuses,-} from "@/new/photos/services/plan";+} from "@/new/photos/services/user-details";import { AppContext, useAppContext } from "@/new/photos/types/context";import { bytesInGB, formattedStorageByteSize } from "@/new/photos/utils/units";import { openURL } from "@/new/photos/utils/web";diff --git a/web/apps/photos/src/pages/_app.tsx b/web/apps/photos/src/pages/_app.tsxindex 517ef5e5e8..357857d7e2 100644--- a/web/apps/photos/src/pages/_app.tsx+++ b/web/apps/photos/src/pages/_app.tsx@@ -24,7 +24,7 @@ import { photosDialogZIndex } from "@/new/photos/components/utils/z-index";import DownloadManager from "@/new/photos/services/download";import { runMigrations } from "@/new/photos/services/migrations";import { initML, isMLSupported } from "@/new/photos/services/ml";-import { getFamilyPortalRedirectURL } from "@/new/photos/services/plan";+import { getFamilyPortalRedirectURL } from "@/new/photos/services/user-details";import { AppContext } from "@/new/photos/types/context";import DialogBox from "@ente/shared/components/DialogBox";import { DialogBoxAttributes } from "@ente/shared/components/DialogBox/types";diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsxindex 3a10d03b53..9e671cc48b 100644--- a/web/apps/photos/src/pages/gallery.tsx+++ b/web/apps/photos/src/pages/gallery.tsx@@ -41,10 +41,6 @@ import {getLocalTrashedFiles,sortFiles,} from "@/new/photos/services/files";-import {- redirectToCustomerPortal,- verifyStripeSubscription,-} from "@/new/photos/services/plan";import {filterSearchableFiles,setSearchCollectionsAndFiles,@@ -55,6 +51,10 @@ import {initUserDetailsOrTriggerSync,userDetailsSnapshot,} from "@/new/photos/services/user";+import {+ redirectToCustomerPortal,+ verifyStripeSubscription,+} from "@/new/photos/services/user-details";import { useAppContext } from "@/new/photos/types/context";import { splitByPredicate } from "@/utils/array";import { ensure } from "@/utils/ensure";diff --git a/web/apps/photos/src/services/collectionService.ts b/web/apps/photos/src/services/collectionService.tsindex 6a7d2c4441..6d466336c3 100644--- a/web/apps/photos/src/services/collectionService.ts+++ b/web/apps/photos/src/services/collectionService.ts@@ -32,7 +32,7 @@ import {import { groupFilesByCollectionID } from "@/new/photos/services/file";import { getLocalFiles, sortFiles } from "@/new/photos/services/files";import { updateMagicMetadata } from "@/new/photos/services/magic-metadata";-import type { FamilyData } from "@/new/photos/services/plan";+import type { FamilyData } from "@/new/photos/services/user-details";import { batch } from "@/utils/array";import { CustomError } from "@ente/shared/error";import HTTPService from "@ente/shared/network/HTTPService";diff --git a/web/apps/photos/src/services/userService.ts b/web/apps/photos/src/services/userService.tsindex 6cde22ed3a..1d66bda69b 100644--- a/web/apps/photos/src/services/userService.ts+++ b/web/apps/photos/src/services/userService.ts@@ -1,7 +1,7 @@import { putAttributes } from "@/accounts/api/user";import log from "@/base/log";import { apiURL } from "@/base/origins";-import type { UserDetails } from "@/new/photos/services/user";+import type { UserDetails } from "@/new/photos/services/user-details";import { ApiError } from "@ente/shared/error";import HTTPService from "@ente/shared/network/HTTPService";import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";diff --git a/web/packages/new/photos/components/gallery/reducer.ts b/web/packages/new/photos/components/gallery/reducer.tsindex 6156f5fba9..1a90a6afc0 100644--- a/web/packages/new/photos/components/gallery/reducer.ts+++ b/web/packages/new/photos/components/gallery/reducer.ts@@ -40,7 +40,7 @@ import {isPinnedCollection,} from "../../services/magic-metadata";import type { PeopleState, Person } from "../../services/ml/people";-import type { FamilyData } from "../../services/plan";+import type { FamilyData } from "../../services/user-details";/*** Specifies what the bar at the top of the gallery is displaying currently.diff --git a/web/packages/new/photos/services/plan.ts b/web/packages/new/photos/services/user-details.tssimilarity index 74%rename from web/packages/new/photos/services/plan.tsrename to web/packages/new/photos/services/user-details.tsindex ebc8bcff59..52f38ae999 100644--- a/web/packages/new/photos/services/plan.ts+++ b/web/packages/new/photos/services/user-details.ts@@ -1,18 +1,18 @@import { authenticatedRequestHeaders, ensureOk } from "@/base/http";+import { getKV, setKV } from "@/base/kv";import { apiURL, familyAppOrigin, paymentsAppOrigin } from "@/base/origins";import { ensure } from "@/utils/ensure";-import { nullToUndefined } from "@/utils/transform";+import { nullishToZero, nullToUndefined } from "@/utils/transform";+import { getData, LS_KEYS, setLSUser } from "@ente/shared/storage/localStorage";import isElectron from "is-electron";import { z } from "zod";-import type { UserDetails } from "./user";-import { syncUserDetails, userDetailsSnapshot } from "./user";/*** Validity of the plan.*/export type PlanPeriod = "month" | "year";-export const Subscription = z.object({+const Subscription = z.object({/*** Store-specific ID of the product ("plan") that the user has subscribed* to. e.g. if the user has subscribed to a plan using Stripe, then this@@ -73,7 +73,7 @@ type FamilyMember = z.infer<typeof FamilyMember>;* Zod schema for details about the family plan (if any) that the user is a part* of.*/-export const FamilyData = z.object({+const FamilyData = z.object({members: z.array(FamilyMember),/*** Family admin subscription storage capacity.@@ -108,7 +108,7 @@ const Bonus = z.object({*/export type Bonus = z.infer<typeof Bonus>;-export const BonusData = z.object({+const BonusData = z.object({/*** List of bonuses applied for the user.*/@@ -122,6 +122,147 @@ export const BonusData = z.object({*/export type BonusData = z.infer<typeof BonusData>;+/**+ * Zod schema for {@link UserDetails}+ */+const UserDetails = z.object({+ email: z.string(),+ usage: z.number(),+ fileCount: z.number().nullish().transform(nullishToZero),+ subscription: Subscription,+ familyData: FamilyData.nullish().transform(nullToUndefined),+ storageBonus: z.number().nullish().transform(nullishToZero),+ bonusData: BonusData.nullish().transform(nullToUndefined),+});++export type UserDetails = z.infer<typeof UserDetails>;++/**+ * Internal in-memory state shared by the functions in this module.+ *+ * This entire object will be reset on logout.+ */+class UserDetailsState {+ /**+ * Subscriptions to {@link UserDetails} updates attached using+ * {@link userDetailsSubscribe}.+ */+ userDetailsListeners: (() => void)[] = [];++ /**+ * Snapshot of the {@link UserDetails} returned by the+ * {@link userDetailsSnapshot} function.+ */+ userDetailsSnapshot: UserDetails | undefined;+}++/**+ * State shared by the functions in this module. See {@link UserDetailsState}.+ */+let _state = new UserDetailsState();++export const logoutUserDetails = () => {+ _state = new UserDetailsState();+};++/**+ * Read in the locally persisted settings into memory, otherwise initate a+ * network requests to fetch the latest values (but don't wait for it to+ * complete).+ *+ * This assumes that the user is already logged in.+ */+export const initUserDetailsOrTriggerSync = async () => {+ const saved = await getKV("userDetails");+ if (saved) {+ setUserDetailsSnapshot(UserDetails.parse(saved));+ } else {+ void syncUserDetails();+ }+};++/**+ * A function that can be used to subscribe to updates to {@link UserDetails}.+ *+ * [Note: Snapshots and useSyncExternalStore]+ *+ * This subscribe function, along with {@link userDetailsSnapshot}, is meant to+ * be used as arguments to React's {@link useSyncExternalStore}.+ *+ * @param callback A function that will be invoked whenever the result of+ * {@link userDetailsSnapshot} changes.+ *+ * @returns A function that can be used to clear the subscription.+ */+export const userDetailsSubscribe = (onChange: () => void): (() => void) => {+ _state.userDetailsListeners.push(onChange);+ return () => {+ _state.userDetailsListeners = _state.userDetailsListeners.filter(+ (l) => l != onChange,+ );+ };+};++/**+ * Return the last known, cached {@link UserDetails}.+ *+ * This, along with {@link userDetailsSubscribe}, is meant to be used as+ * arguments to React's {@link useSyncExternalStore}.+ */+export const userDetailsSnapshot = () => _state.userDetailsSnapshot;++const setUserDetailsSnapshot = (snapshot: UserDetails) => {+ _state.userDetailsSnapshot = snapshot;+ _state.userDetailsListeners.forEach((l) => l());+};++/**+ * Fetch the user's details from remote and save them in local storage for+ * subsequent lookup, and also update our in-memory snapshots.+ */+export const syncUserDetails = async () => {+ const userDetails = await getUserDetailsV2();+ await setKV("userDetails", userDetails);+ setUserDetailsSnapshot(userDetails);++ // TODO: The existing code used to also set the email for the local storage+ // user whenever it updated the user details. I don't see why this would be+ // needed though.+ //+ // Retaining the existing behaviour for now, except we throw. The intent is+ // to remove this entire copy-over after a bit.+ //+ // Added Nov 2024, and can be removed after a while (tag: Migration).++ const oldLSUser = getData(LS_KEYS.USER) as unknown;+ const hasMatchingEmail =+ oldLSUser &&+ typeof oldLSUser == "object" &&+ "email" in oldLSUser &&+ typeof oldLSUser.email == "string" &&+ oldLSUser.email == userDetails.email;++ if (!hasMatchingEmail) {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument+ await setLSUser({+ ...getData(LS_KEYS.USER),+ email: userDetails.email,+ });+ throw new Error("Email in local storage did not match user details");+ }+};++/**+ * Fetch user details from remote.+ */+export const getUserDetailsV2 = async () => {+ const res = await fetch(await apiURL("/users/details/v2"), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return UserDetails.parse(await res.json());+};+/*** Zod schema for an individual plan received in the list of plans.*/diff --git a/web/packages/new/photos/services/user.ts b/web/packages/new/photos/services/user.tsindex 5a1835d8fc..4e0be7cf62 100644--- a/web/packages/new/photos/services/user.ts+++ b/web/packages/new/photos/services/user.ts@@ -1,149 +1,6 @@import { authenticatedRequestHeaders, ensureOk } from "@/base/http";-import { getKV, setKV } from "@/base/kv";import { apiURL } from "@/base/origins";-import { nullishToZero, nullToUndefined } from "@/utils/transform";-import { getData, LS_KEYS, setLSUser } from "@ente/shared/storage/localStorage";import { z } from "zod";-import { BonusData, FamilyData, Subscription } from "./plan";--/**- * Zod schema for {@link UserDetails}- */-const UserDetails = z.object({- email: z.string(),- usage: z.number(),- fileCount: z.number().nullish().transform(nullishToZero),- subscription: Subscription,- familyData: FamilyData.nullish().transform(nullToUndefined),- storageBonus: z.number().nullish().transform(nullishToZero),- bonusData: BonusData.nullish().transform(nullToUndefined),-});--export type UserDetails = z.infer<typeof UserDetails>;--/**- * Internal in-memory state shared by the functions in this module.- *- * This entire object will be reset on logout.- */-class UserState {- /**- * Subscriptions to {@link UserDetails} updates attached using- * {@link userDetailsSubscribe}.- */- userDetailsListeners: (() => void)[] = [];-- /**- * Snapshot of the {@link UserDetails} returned by the- * {@link userDetailsSnapshot} function.- */- userDetailsSnapshot: UserDetails | undefined;-}--/** State shared by the functions in this module. See {@link UserState}. */-let _state = new UserState();--export const logoutUserDetails = () => {- _state = new UserState();-};--/**- * Read in the locally persisted settings into memory, otherwise initate a- * network requests to fetch the latest values (but don't wait for it to- * complete).- *- * This assumes that the user is already logged in.- */-export const initUserDetailsOrTriggerSync = async () => {- const saved = await getKV("userDetails");- if (saved) {- setUserDetailsSnapshot(UserDetails.parse(saved));- } else {- void syncUserDetails();- }-};--/**- * A function that can be used to subscribe to updates to {@link UserDetails}.- *- * [Note: Snapshots and useSyncExternalStore]- *- * This subscribe function, along with {@link userDetailsSnapshot}, is meant to- * be used as arguments to React's {@link useSyncExternalStore}.- *- * @param callback A function that will be invoked whenever the result of- * {@link userDetailsSnapshot} changes.- *- * @returns A function that can be used to clear the subscription.- */-export const userDetailsSubscribe = (onChange: () => void): (() => void) => {- _state.userDetailsListeners.push(onChange);- return () => {- _state.userDetailsListeners = _state.userDetailsListeners.filter(- (l) => l != onChange,- );- };-};--/**- * Return the last known, cached {@link UserDetails}.- *- * This, along with {@link userDetailsSubscribe}, is meant to be used as- * arguments to React's {@link useSyncExternalStore}.- */-export const userDetailsSnapshot = () => _state.userDetailsSnapshot;--const setUserDetailsSnapshot = (snapshot: UserDetails) => {- _state.userDetailsSnapshot = snapshot;- _state.userDetailsListeners.forEach((l) => l());-};--/**- * Fetch the user's details from remote and save them in local storage for- * subsequent lookup, and also update our in-memory snapshots.- */-export const syncUserDetails = async () => {- const userDetails = await getUserDetailsV2();- await setKV("userDetails", userDetails);- setUserDetailsSnapshot(userDetails);-- // TODO: The existing code used to also set the email for the local storage- // user whenever it updated the user details. I don't see why this would be- // needed though.- //- // Retaining the existing behaviour for now, except we throw. The intent is- // to remove this entire copy-over after a bit.- //- // Added Nov 2024, and can be removed after a while (tag: Migration).-- const oldLSUser = getData(LS_KEYS.USER) as unknown;- const hasMatchingEmail =- oldLSUser &&- typeof oldLSUser == "object" &&- "email" in oldLSUser &&- typeof oldLSUser.email == "string" &&- oldLSUser.email == userDetails.email;-- if (!hasMatchingEmail) {- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument- await setLSUser({- ...getData(LS_KEYS.USER),- email: userDetails.email,- });- throw new Error("Email in local storage did not match user details");- }-};--/**- * Fetch user details from remote.- */-export const getUserDetailsV2 = async () => {- const res = await fetch(await apiURL("/users/details/v2"), {- headers: await authenticatedRequestHeaders(),- });- ensureOk(res);- return UserDetails.parse(await res.json());-};/*** Fetch the two-factor status (whether or not it is enabled) from remote.