feat: Base implementation of v2 of avatars (#12369)

* feat: Base implementation of v2 of avatars

* Make avatarUrl and logoUrl entirely optional

* Made necessary backwards compat changes

* fix: type errors

* Fix: OG image

* fix types

* Consistency with other behaviour, ux tweak

---------

Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
Alex van AndelandPeer Richelsen authored and GitHub committed 2023-11-20 12:49:38 +00:00
1 parent c55b36f235
commit 4f26ca1a7b
18 files changed
+258 -69

No files matched your search

@@ -30,6 +30,7 @@ export async function getUserFromSession(ctx: TRPCContextInner, session: Maybe<S
email: true,
emailVerified: true,
bio: true,
avatarUrl: true,
timeZone: true,
weekStart: true,
startTime: true,
@@ -1,3 +1,4 @@
import prisma from "@calcom/prisma";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
type AvatarOptions = {
@@ -7,7 +8,15 @@ type AvatarOptions = {
};
export const avatarHandler = async ({ ctx }: AvatarOptions) => {
const data = await prisma.user.findUnique({
where: {
id: ctx.user.id,
},
select: {
avatar: true,
},
});
return {
avatar: ctx.user.avatar,
avatar: data?.avatar,
};
};
@@ -25,6 +25,7 @@ export const meHandler = async ({ ctx }: MeOptions) => {
timeFormat: user.timeFormat,
timeZone: user.timeZone,
avatar: getUserAvatarUrl(user),
avatarUrl: user.avatarUrl,
createdDate: user.createdDate,
trialEndsAt: user.trialEndsAt,
defaultScheduleId: user.defaultScheduleId,
@@ -1,5 +1,6 @@
import type { Prisma } from "@prisma/client";
import type { GetServerSidePropsContext, NextApiResponse } from "next";
import { v4 as uuidv4 } from "uuid";
import stripe from "@calcom/app-store/stripepayment/lib/server";
import { getPremiumPlanProductId } from "@calcom/app-store/stripepayment/lib/utils";
@@ -31,12 +32,35 @@ type UpdateProfileOptions = {
input: TUpdateProfileInputSchema;
};
const uploadAvatar = async ({ userId, avatar: data }: { userId: number; avatar: string }) => {
const objectKey = uuidv4();
await prisma.avatar.upsert({
where: {
teamId_userId: {
teamId: 0,
userId,
},
},
create: {
userId: userId,
data,
objectKey,
},
update: {
data,
objectKey,
},
});
return `/api/avatar/${objectKey}.png`;
};
export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions) => {
const { user } = ctx;
const userMetadata = handleUserMetadata({ ctx, input });
const data: Prisma.UserUpdateInput = {
...input,
avatar: input.avatar ? await getAvatarToSet(input.avatar) : null,
metadata: userMetadata,
};
@@ -114,6 +138,15 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
// when the email changes, the user needs to sign in again.
signOutUser = true;
}
// don't do anything if avatar is undefined.
if (typeof input.avatar !== "undefined") {
data.avatarUrl = input.avatar
? await uploadAvatar({
avatar: await resizeBase64Image(input.avatar),
userId: user.id,
})
: null;
}
const updatedUser = await prisma.user.update({
where: {
@@ -129,6 +162,7 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
metadata: true,
name: true,
createdDate: true,
avatarUrl: true,
locale: true,
schedules: {
select: {
@@ -186,28 +220,11 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
},
});
}
// Revalidate booking pages
// Disabled because the booking pages are currently not using getStaticProps
/*const res = ctx.res as NextApiResponse;
if (typeof res?.revalidate !== "undefined") {
const eventTypes = await prisma.eventType.findMany({
where: {
userId: user.id,
team: null,
},
select: {
id: true,
slug: true,
},
});
// waiting for this isn't needed
Promise.all(
eventTypes.map((eventType) => res?.revalidate(`/new-booker/${ctx.user.username}/${eventType.slug}`))
)
.then(() => console.info("Booking pages revalidated"))
.catch((e) => console.error(e));
}*/
return { ...input, signOutUser, passwordReset };
// don't return avatar, we don't need it anymore.
delete input.avatar;
return { ...input, signOutUser, passwordReset, avatarUrl: updatedUser.avatarUrl };
};
const cleanMetadataAllowedUpdateKeys = (metadata: TUpdateProfileInputSchema["metadata"]) => {
@@ -230,17 +247,3 @@ const handleUserMetadata = ({ ctx, input }: UpdateProfileOptions) => {
// Required so we don't override and delete saved values
return { ...userMetadata, ...cleanMetadata };
};
async function getAvatarToSet(avatar: string | null | undefined) {
if (avatar === null || avatar === undefined) {
return avatar;
}
if (!avatar.startsWith("data:image")) {
// Non Base64 avatar currently could only be the dynamic avatar URL(i.e. /{USER}/avatar.png). If we allow setting that URL, we would get infinite redirects on /user/avatar.ts endpoint
log.warn("Non Base64 avatar, ignored it", { avatar });
// `undefined` would not ignore the avatar, but `null` would remove it. So, we return `undefined` here.
return undefined;
}
return await resizeBase64Image(avatar);
}