Skip to content

armgit / ente

Public Imported from GitHub
0

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

wip checkpoint

Manav Rathie468c6186721
diff --git a/web/apps/photos/src/components/MemberSubscriptionManage.tsx b/web/apps/photos/src/components/MemberSubscriptionManage.tsx
index d7f2419ffe..7a903dac36 100644
--- a/web/apps/photos/src/components/MemberSubscriptionManage.tsx
+++ b/web/apps/photos/src/components/MemberSubscriptionManage.tsx
@@ -1,5 +1,5 @@
import { useIsSmallWidth } from "@/base/hooks";
-import { getFamilyPlanAdmin, leaveFamily } from "@/new/photos/services/family";
+import { getFamilyPlanAdmin, leaveFamily } from "@/new/photos/services/plan";
import { AppContext } from "@/new/photos/types/context";
import {
FlexWrapper,
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index d359f139e0..84d02082b2 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -34,7 +34,6 @@ import {
} from "@/new/photos/services/collection";
import { areOnlySystemCollections } from "@/new/photos/services/collection/ui";
import downloadManager from "@/new/photos/services/download";
-import { getLocalFamilyData } from "@/new/photos/services/family";
import {
getLocalFiles,
getLocalTrashedFiles,
@@ -364,9 +363,8 @@ export default function Gallery() {
}
setIsFirstLogin(false);
const user = getData(LS_KEYS.USER);
- // TODO: Temp fallback
- const familyData =
- userDetailsSnapshot()?.familyData ?? getLocalFamilyData();
+ // TODO: Pass entire snapshot to reducer?
+ const familyData = userDetailsSnapshot()?.familyData;
const files = sortFiles(
mergeMetadata(await getLocalFiles("normal")),
);
diff --git a/web/apps/photos/src/services/userService.ts b/web/apps/photos/src/services/userService.ts
index 35769f00d6..6cde22ed3a 100644
--- a/web/apps/photos/src/services/userService.ts
+++ b/web/apps/photos/src/services/userService.ts
@@ -1,8 +1,7 @@
import { putAttributes } from "@/accounts/api/user";
import log from "@/base/log";
-import { apiURL, familyAppOrigin } from "@/base/origins";
+import { apiURL } from "@/base/origins";
import type { UserDetails } from "@/new/photos/services/user";
-import { getLocalFamilyData, isPartOfFamily } from "@/new/photos/services/family";
import { ApiError } from "@ente/shared/error";
import HTTPService from "@ente/shared/network/HTTPService";
import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
@@ -24,24 +23,6 @@ export const getPublicKey = async (email: string) => {
return resp.data.publicKey;
};
-export const getFamiliesToken = async () => {
- try {
- const token = getToken();
-
- const resp = await HTTPService.get(
- await apiURL("/users/families-token"),
- null,
- {
- "X-Auth-Token": token,
- },
- );
- return resp.data["familiesToken"];
- } catch (e) {
- log.error("failed to get family token", e);
- throw e;
- }
-};
-
export const isTokenValid = async (token: string) => {
try {
const resp = await HTTPService.get(
@@ -100,19 +81,6 @@ export const getUserDetailsV2 = async (): Promise<UserDetails> => {
}
};
-export const getFamilyPortalRedirectURL = async () => {
- try {
- const jwtToken = await getFamiliesToken();
- const isFamilyCreated = isPartOfFamily(getLocalFamilyData());
- return `${familyAppOrigin()}?token=${jwtToken}&isFamilyCreated=${isFamilyCreated}&redirectURL=${
- window.location.origin
- }/gallery`;
- } catch (e) {
- log.error("unable to generate to family portal URL", e);
- throw e;
- }
-};
-
export interface DeleteChallengeResponse {
allowDelete: boolean;
encryptedChallenge: string;
diff --git a/web/packages/new/photos/services/family.ts b/web/packages/new/photos/services/family.ts
index 3ca86bf139..e69de29bb2 100644
--- a/web/packages/new/photos/services/family.ts
+++ b/web/packages/new/photos/services/family.ts
@@ -1,111 +0,0 @@
-import { authenticatedRequestHeaders, ensureOk } from "@/base/http";
-import log from "@/base/log";
-import { apiURL } from "@/base/origins";
-import { nullToUndefined } from "@/utils/transform";
-import {
- LS_KEYS,
- getData,
- removeData,
-} from "@ente/shared/storage/localStorage";
-import type { User } from "@ente/shared/user/types";
-import { z } from "zod";
-import type { UserDetails } from "./user";
-
-const FamilyMember = z.object({
- /**
- * Email address of the family member.
- */
- email: z.string(),
- /**
- * Storage used by the family member.
- *
- * This field will not be present for invited members until they accept.
- */
- usage: z.number().nullish().transform(nullToUndefined),
- /**
- * `true` if this is the admin.
- *
- * This field will not be sent for invited members until they accept.
- */
- isAdmin: z.boolean().nullish().transform(nullToUndefined),
-});
-
-type FamilyMember = z.infer<typeof FamilyMember>;
-
-/**
- * Zod schema for details about the family plan (if any) that the user is a part
- * of.
- */
-export const FamilyData = z.object({
- members: z.array(FamilyMember),
- /**
- * Family admin subscription storage capacity.
- *
- * This excludes add-on and any other bonus storage.
- */
- storage: z.number(),
-});
-
-/**
- * Details about the family plan (if any) that the user is a part of.
- */
-export type FamilyData = z.infer<typeof FamilyData>;
-
-export function getLocalFamilyData(): FamilyData {
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
- return getData(LS_KEYS.FAMILY_DATA);
-}
-
-/**
- * Return true if the user (represented by the given {@link userDetails}) is
- * part of a family plan.
- */
-export const isPartOfFamily = (userDetails: UserDetails) =>
- (userDetails.familyData?.members.length ?? 0) > 0;
-
-/**
- * Return true if the user (represented by the given {@link userDetails}) is
- * part of a family plan which has members in the family.
- */
-export const isPartOfFamilyWithOtherMembers = (userDetails: UserDetails) =>
- (userDetails.familyData?.members.length ?? 0) > 1;
-
-export function isFamilyAdmin(userDetails: UserDetails): boolean {
- const familyAdmin: FamilyMember = getFamilyPlanAdmin(userDetails);
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
- const user: User = getData(LS_KEYS.USER);
- return familyAdmin.email === user.email;
-}
-
-export function getFamilyPlanAdmin(userDetails: UserDetails): FamilyMember {
- if (isPartOfFamily(userDetails)) {
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion, @typescript-eslint/no-non-null-asserted-optional-chain
- return userDetails.familyData?.members.find((x) => x.isAdmin)!;
- } else {
- log.error(
- "invalid getFamilyPlanAdmin call - verify user is part of family plan before calling this method",
- );
- throw new Error(
- "invalid getFamilyPlanAdmin call - verify user is part of family plan before calling this method",
- );
- }
-}
-
-/**
- * Return the combined usage of all the family members.
- */
-export const familyUsage = (userDetails: UserDetails) =>
- (userDetails.familyData?.members ?? []).reduce(
- (sum, { usage }) => sum + (usage ?? 0),
- 0,
- );
-
-export const leaveFamily = async () => {
- ensureOk(
- await fetch(await apiURL("/family/leave"), {
- method: "DELETE",
- headers: await authenticatedRequestHeaders(),
- }),
- );
- removeData(LS_KEYS.FAMILY_DATA);
-};
diff --git a/web/packages/new/photos/services/plan.ts b/web/packages/new/photos/services/plan.ts
index 100b26768a..870bddc3f7 100644
--- a/web/packages/new/photos/services/plan.ts
+++ b/web/packages/new/photos/services/plan.ts
@@ -2,17 +2,20 @@
/* eslint-disable @typescript-eslint/prefer-optional-chain */
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
import { authenticatedRequestHeaders, ensureOk } from "@/base/http";
-import { apiURL, paymentsAppOrigin } from "@/base/origins";
-import {
- familyUsage,
- getTotalFamilyUsage,
- isPartOfFamily,
-} from "@/new/photos/services/family";
+import log from "@/base/log";
+import { apiURL, familyAppOrigin, paymentsAppOrigin } from "@/base/origins";
import { nullToUndefined } from "@/utils/transform";
-import { LS_KEYS, setData } from "@ente/shared/storage/localStorage";
+import {
+ LS_KEYS,
+ getData,
+ removeData,
+ setData,
+} from "@ente/shared/storage/localStorage";
+import type { User } from "@ente/shared/user/types";
import isElectron from "is-electron";
import { z } from "zod";
import type { BonusData, UserDetails } from "./user";
+import { userDetailsSnapshot } from "./user";
const PlanPeriod = z.enum(["month", "year"]);
@@ -43,6 +46,46 @@ export const Subscription = z.object({
*/
export type Subscription = z.infer<typeof Subscription>;
+const FamilyMember = z.object({
+ /**
+ * Email address of the family member.
+ */
+ email: z.string(),
+ /**
+ * Storage used by the family member.
+ *
+ * This field will not be present for invited members until they accept.
+ */
+ usage: z.number().nullish().transform(nullToUndefined),
+ /**
+ * `true` if this is the admin.
+ *
+ * This field will not be sent for invited members until they accept.
+ */
+ isAdmin: z.boolean().nullish().transform(nullToUndefined),
+});
+
+type FamilyMember = z.infer<typeof FamilyMember>;
+
+/**
+ * Zod schema for details about the family plan (if any) that the user is a part
+ * of.
+ */
+export const FamilyData = z.object({
+ members: z.array(FamilyMember),
+ /**
+ * Family admin subscription storage capacity.
+ *
+ * This excludes add-on and any other bonus storage.
+ */
+ storage: z.number(),
+});
+
+/**
+ * Details about the family plan (if any) that the user is a part of.
+ */
+export type FamilyData = z.infer<typeof FamilyData>;
+
/**
* Zod schema for an individual plan received in the list of plans.
*/
@@ -150,7 +193,7 @@ export const redirectToPaymentsApp = async (
action: "buy" | "update",
) => {
const paymentToken = await getPaymentToken();
- const redirectURL = completionRedirectURL();
+ const redirectURL = paymentCompletionRedirectURL();
window.location.href = `${paymentsAppOrigin()}?productID=${productID}&paymentToken=${paymentToken}&action=${action}&redirectURL=${redirectURL}`;
};
@@ -158,7 +201,7 @@ export const redirectToPaymentsApp = async (
* Return the URL to which the payments app should redirect back on completion
* of the flow.
*/
-const completionRedirectURL = () =>
+const paymentCompletionRedirectURL = () =>
isElectron()
? `${paymentsAppOrigin()}/desktop-redirect`
: `${window.location.origin}/gallery`;
@@ -181,7 +224,7 @@ const getPaymentToken = async () => {
* details about their subscription and modify their payment method.
*/
export const redirectToCustomerPortal = async () => {
- const redirectURL = completionRedirectURL();
+ const redirectURL = paymentCompletionRedirectURL();
const url = await apiURL("/billing/stripe/customer-portal");
const params = new URLSearchParams({ redirectURL });
const res = await fetch(`${url}?${params.toString()}`, {
@@ -259,3 +302,85 @@ export function hasExceededStorageQuota(userDetails: UserDetails) {
);
}
}
+
+/**
+ * Return true if the user (represented by the given {@link userDetails}) is
+ * part of a family plan.
+ */
+export const isPartOfFamily = (userDetails: UserDetails) =>
+ (userDetails.familyData?.members.length ?? 0) > 0;
+
+/**
+ * Return true if the user (represented by the given {@link userDetails}) is
+ * part of a family plan which has members in the family.
+ */
+export const isPartOfFamilyWithOtherMembers = (userDetails: UserDetails) =>
+ (userDetails.familyData?.members.length ?? 0) > 1;
+
+export function isFamilyAdmin(userDetails: UserDetails): boolean {
+ const familyAdmin: FamilyMember = getFamilyPlanAdmin(userDetails);
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+ const user: User = getData(LS_KEYS.USER);
+ return familyAdmin.email === user.email;
+}
+
+export function getFamilyPlanAdmin(userDetails: UserDetails): FamilyMember {
+ if (isPartOfFamily(userDetails)) {
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion, @typescript-eslint/no-non-null-asserted-optional-chain
+ return userDetails.familyData?.members.find((x) => x.isAdmin)!;
+ } else {
+ log.error(
+ "invalid getFamilyPlanAdmin call - verify user is part of family plan before calling this method",
+ );
+ throw new Error(
+ "invalid getFamilyPlanAdmin call - verify user is part of family plan before calling this method",
+ );
+ }
+}
+
+/**
+ * Return the combined usage of all the family members.
+ */
+export const familyUsage = (userDetails: UserDetails) =>
+ (userDetails.familyData?.members ?? []).reduce(
+ (sum, { usage }) => sum + (usage ?? 0),
+ 0,
+ );
+
+/**
+ * Return a pre-authenticated URL for the families app, where the user can
+ * manage their family plan.
+ */
+export const getFamilyPortalRedirectURL = async () => {
+ const userDetails = userDetailsSnapshot();
+
+ const token = await getFamiliesToken();
+ const isFamilyCreated =
+ userDetails && isPartOfFamily(userDetails) ? "true" : "false";
+ const redirectURL = `${window.location.origin}/gallery`;
+ const params = new URLSearchParams({ token, isFamilyCreated, redirectURL });
+ return `${familyAppOrigin()}?${params.toString()}`;
+};
+
+/**
+ * Fetch and return a one-time token that can be used to authenticate user's
+ * requests to the families app.
+ */
+const getFamiliesToken = async () => {
+ const res = await fetch(await apiURL("/users/families-token"), {
+ headers: await authenticatedRequestHeaders(),
+ });
+ ensureOk(res);
+ return z.object({ familiesToken: z.string() }).parse(await res.json())
+ .familiesToken;
+};
+
+export const leaveFamily = async () => {
+ ensureOk(
+ await fetch(await apiURL("/family/leave"), {
+ method: "DELETE",
+ headers: await authenticatedRequestHeaders(),
+ }),
+ );
+ removeData(LS_KEYS.FAMILY_DATA);
+};
diff --git a/web/packages/new/photos/services/user.ts b/web/packages/new/photos/services/user.ts
index f3284fca78..fe80e8b435 100644
--- a/web/packages/new/photos/services/user.ts
+++ b/web/packages/new/photos/services/user.ts
@@ -3,8 +3,7 @@ import { getKV, setKV } from "@/base/kv";
import { apiURL } from "@/base/origins";
import { getData, LS_KEYS, setLSUser } from "@ente/shared/storage/localStorage";
import { z } from "zod";
-import { FamilyData } from "./family";
-import { Subscription } from "./plan";
+import { FamilyData, Subscription } from "./plan";
const BonusData = z.object({
/**