Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Add support for uploading a space image (#1876)

Luke Vella9efa4279d407
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index b08f63110..3259bc788 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -204,9 +204,6 @@
"timeZoneChangeDetectorMessage": "Your timezone has changed to <b>{currentTimeZone}</b>. Do you want to update your preferences?",
"yesUpdateTimezone": "Yes, update my timezone",
"noKeepCurrentTimezone": "No, keep the current timezone",
- "removeAvatar": "Remove",
- "uploadProfilePicture": "Upload",
- "profilePictureDescription": "Up to 2MB, JPG or PNG",
"invalidFileType": "Invalid file type",
"invalidFileTypeDescription": "Please upload a JPG or PNG file.",
"fileTooLarge": "File too large",
@@ -452,5 +449,9 @@
"membersDescription": "Members have access to your space",
"pendingInvitesDescription": "Invite other users to share your space.",
"membersSettingsDescription": "Manage space members, invite new users, and control access permissions.",
- "spaceNamePlaceholder": "My Team"
+ "spaceNamePlaceholder": "My Team",
+ "uploadImage": "Upload",
+ "removeImage": "Remove",
+ "imageUploadDescription": "Up to 2MB, JPG or PNG",
+ "image": "Image"
}
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/components/sidebar/nav-user.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/components/sidebar/nav-user.tsx
index 3aa056609..ce1af0d01 100644
--- a/apps/web/src/app/[locale]/(space)/(dashboard)/components/sidebar/nav-user.tsx
+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/components/sidebar/nav-user.tsx
@@ -21,7 +21,7 @@ export function NavUser({
data-state={pathname.startsWith("/account") ? "active" : "inactive"}
className="group relative flex w-full items-center gap-3 rounded-md p-3 text-sm hover:bg-gray-200 data-[state=active]:bg-gray-200"
>
- <OptimizedAvatarImage size="md" src={image} name={name} />
+ <OptimizedAvatarImage size="lg" src={image} name={name} />
<div className="flex-1 truncate text-left">
<div className="font-medium">{name}</div>
<div className="mt-0.5 truncate font-normal text-muted-foreground text-xs">
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/components/sidebar/space-sidebar.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/components/sidebar/space-sidebar.tsx
index 95840ed03..e65cd69af 100644
--- a/apps/web/src/app/[locale]/(space)/(dashboard)/components/sidebar/space-sidebar.tsx
+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/components/sidebar/space-sidebar.tsx
@@ -48,7 +48,7 @@ export async function SpaceSidebar({
{isSpacesEnabled ? (
<SpaceDropdown spaces={spaces} activeSpaceId={activeSpace.id}>
<Button className="flex h-auto w-full p-2" variant="ghost">
- <SpaceIcon name={activeSpace.name} />
+ <SpaceIcon src={activeSpace.image} name={activeSpace.name} />
<div className="flex-1 px-0.5 text-left">
<div className="font-medium text-sm">{activeSpace.name}</div>
<div className="text-muted-foreground text-xs">
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/settings/general/components/space-settings-form.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/general/components/space-settings-form.tsx
index f7bcbcc79..c6483e231 100644
--- a/apps/web/src/app/[locale]/(space)/(dashboard)/settings/general/components/space-settings-form.tsx
+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/general/components/space-settings-form.tsx
@@ -12,12 +12,23 @@ import {
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
import { toast } from "@rallly/ui/sonner";
+import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { z } from "zod";
+import {
+ ImageUploadControl,
+ ImageUploadPreview,
+} from "@/components/image-upload";
import { Trans } from "@/components/trans";
-import { updateSpaceAction } from "@/features/space/actions";
+import {
+ removeSpaceImageAction,
+ updateSpaceAction,
+ updateSpaceImageAction,
+} from "@/features/space/actions";
+import { SpaceIcon } from "@/features/space/components/space-icon";
import type { SpaceDTO } from "@/features/space/types";
import { useTranslation } from "@/i18n/client";
+import { useFeatureFlag } from "@/lib/feature-flags/client";
import { useSafeAction } from "@/lib/safe-action/client";
const spaceSettingsSchema = z.object({
@@ -35,7 +46,12 @@ interface SpaceSettingsFormProps {
export function SpaceSettingsForm({ space }: SpaceSettingsFormProps) {
const { t } = useTranslation();
+ const router = useRouter();
+ const isStorageEnabled = useFeatureFlag("storage");
+
const updateSpace = useSafeAction(updateSpaceAction);
+ const updateImage = useSafeAction(updateSpaceImageAction);
+ const removeImage = useSafeAction(removeSpaceImageAction);
const form = useForm<SpaceSettingsData>({
resolver: zodResolver(spaceSettingsSchema),
@@ -63,9 +79,37 @@ export function SpaceSettingsForm({ space }: SpaceSettingsFormProps) {
form.reset(data);
};
+ const handleImageUploadSuccess = async (imageKey: string) => {
+ await updateImage.executeAsync({ imageKey });
+ router.refresh();
+ };
+
+ const handleImageRemoveSuccess = async () => {
+ await removeImage.executeAsync();
+ router.refresh();
+ };
+
return (
<Form {...form}>
- <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
+ {isStorageEnabled && (
+ <div>
+ <FormLabel>
+ <Trans i18nKey="image" defaults="Image" />
+ </FormLabel>
+ <div className="mt-2 flex items-center gap-x-4">
+ <ImageUploadPreview>
+ <SpaceIcon name={space.name} src={space.image} size="xl" />
+ </ImageUploadPreview>
+ <ImageUploadControl
+ keyPrefix="spaces"
+ onUploadSuccess={handleImageUploadSuccess}
+ onRemoveSuccess={handleImageRemoveSuccess}
+ hasCurrentImage={!!space.image}
+ />
+ </div>
+ </div>
+ )}
<FormField
control={form.control}
name="name"
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/page.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/page.tsx
index 67feeeb85..62948db44 100644
--- a/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/page.tsx
@@ -42,7 +42,7 @@ export default async function MembersSettingsPage() {
<OptimizedAvatarImage
src={member.image ?? undefined}
name={member.name}
- size="md"
+ size="lg"
/>
<div>
<div className="flex items-center gap-x-2">
diff --git a/apps/web/src/app/[locale]/(space)/account/profile/profile-picture.tsx b/apps/web/src/app/[locale]/(space)/account/profile/profile-picture.tsx
index c0335fe27..324bd583e 100644
--- a/apps/web/src/app/[locale]/(space)/account/profile/profile-picture.tsx
+++ b/apps/web/src/app/[locale]/(space)/account/profile/profile-picture.tsx
@@ -1,179 +1,55 @@
"use client";
import { usePostHog } from "@rallly/posthog/client";
-import { Button } from "@rallly/ui/button";
-import { toast } from "@rallly/ui/sonner";
import { useRouter } from "next/navigation";
-import React, { useState } from "react";
-import { z } from "zod";
+import {
+ ImageUpload,
+ ImageUploadControl,
+ ImageUploadPreview,
+} from "@/components/image-upload";
import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
-import { Trans } from "@/components/trans";
import { useAuthenticatedUser } from "@/components/user-provider";
-import { useTranslation } from "@/i18n/client";
import { useFeatureFlag } from "@/lib/feature-flags/client";
import { trpc } from "@/trpc/client";
-const allowedMimeTypes = z.enum(["image/jpeg", "image/png"]);
+function ProfilePictureUpload() {
+ const { user } = useAuthenticatedUser();
+ const router = useRouter();
+ const posthog = usePostHog();
-function ChangeAvatarButton({ onSuccess }: { onSuccess: () => void }) {
- const getPresignedUrl = trpc.user.getAvatarUploadUrl.useMutation();
const updateAvatar = trpc.user.updateAvatar.useMutation();
- const { t } = useTranslation();
- const [isUploading, setIsUploading] = useState(false);
-
- const handleFileChange = async (
- event: React.ChangeEvent<HTMLInputElement>,
- ) => {
- const file = event.target.files?.[0];
-
- if (!file) return;
-
- const parsedFileType = allowedMimeTypes.safeParse(file.type);
-
- if (!parsedFileType.success) {
- toast.message(
- t("invalidFileType", {
- defaultValue: "Invalid file type",
- }),
- {
- description: t("invalidFileTypeDescription", {
- defaultValue: "Please upload a JPG or PNG file.",
- }),
- },
- );
- return;
- }
-
- const fileType = parsedFileType.data;
-
- if (file.size > 2 * 1024 * 1024) {
- toast.message(
- t("fileTooLarge", {
- defaultValue: "File too large",
- }),
- {
- description: t("fileTooLargeDescription", {
- defaultValue: "Please upload a file smaller than 2MB.",
- }),
- },
- );
- return;
- }
- setIsUploading(true);
- try {
- // Get pre-signed URL
- const res = await getPresignedUrl.mutateAsync({
- fileType,
- fileSize: file.size,
- });
-
- const { url, fields } = res;
-
- await fetch(url, {
- method: "PUT",
- body: file,
- headers: {
- "Content-Type": fileType,
- "Content-Length": file.size.toString(),
- },
- });
-
- await updateAvatar.mutateAsync({
- imageKey: fields.key,
- });
+ const removeAvatar = trpc.user.removeAvatar.useMutation();
- onSuccess();
- } catch {
- toast.error(
- t("errorUploadPicture", {
- defaultValue: "Failed to upload",
- }),
- {
- description: t("errorUploadPictureDescription", {
- defaultValue:
- "There was an issue uploading your picture. Please try again later.",
- }),
- },
- );
- } finally {
- setIsUploading(false);
- }
+ const handleUploadSuccess = async (imageKey: string) => {
+ await updateAvatar.mutateAsync({ imageKey });
+ router.refresh();
+ posthog?.capture("upload profile picture");
};
- return (
- <>
- <Button
- loading={isUploading}
- onClick={() => {
- document.getElementById("avatar-upload")?.click();
- }}
- >
- <Trans i18nKey="uploadProfilePicture" defaults="Upload" />
- </Button>
- <input
- id="avatar-upload"
- type="file"
- accept="image/*"
- onChange={handleFileChange}
- className="hidden"
- />
- </>
- );
-}
-
-function RemoveAvatarButton({ onSuccess }: { onSuccess?: () => void }) {
- const [isLoading, setLoading] = React.useState(false);
- const removeAvatar = trpc.user.removeAvatar.useMutation();
- return (
- <Button
- loading={isLoading}
- variant="ghost"
- onClick={async () => {
- setLoading(true);
- try {
- await removeAvatar.mutateAsync();
- onSuccess?.();
- } finally {
- setLoading(false);
- }
- }}
- >
- <Trans i18nKey="removeAvatar" defaults="Remove" />
- </Button>
- );
-}
-
-function Upload() {
- const { user } = useAuthenticatedUser();
- const router = useRouter();
+ const handleRemoveSuccess = async () => {
+ await removeAvatar.mutateAsync();
+ router.refresh();
+ posthog?.capture("remove profile picture");
+ };
- const posthog = usePostHog();
+ if (!user) return null;
return (
- <div className="flex flex-col gap-y-2">
- <div className="flex gap-2">
- <ChangeAvatarButton
- onSuccess={() => {
- router.refresh();
- posthog?.capture("upload profile picture");
- }}
+ <ImageUpload>
+ <ImageUploadPreview>
+ <OptimizedAvatarImage
+ src={user.image ?? undefined}
+ name={user.name}
+ size="xl"
/>
- {user?.image ? (
- <RemoveAvatarButton
- onSuccess={() => {
- router.refresh();
- posthog?.capture("remove profile picture");
- }}
- />
- ) : null}
- </div>
- <p className="text-muted-foreground text-xs">
- <Trans
- i18nKey="profilePictureDescription"
- defaults="Up to 2MB, JPG or PNG"
- />
- </p>
- </div>
+ </ImageUploadPreview>
+ <ImageUploadControl
+ keyPrefix="avatars"
+ onUploadSuccess={handleUploadSuccess}
+ onRemoveSuccess={handleRemoveSuccess}
+ hasCurrentImage={!!user.image}
+ />
+ </ImageUpload>
);
}
@@ -185,10 +61,10 @@ export function ProfilePicture({
image?: string;
}) {
const isStorageEnabled = useFeatureFlag("storage");
- return (
- <div className="flex items-center gap-x-4">
- <OptimizedAvatarImage src={image} name={name} size="lg" />
- {isStorageEnabled ? <Upload /> : null}
- </div>
- );
+
+ if (isStorageEnabled) {
+ return <ProfilePictureUpload />;
+ }
+
+ return <OptimizedAvatarImage src={image} name={name} size="lg" />;
}
diff --git a/apps/web/src/app/[locale]/accept-invite/[inviteId]/page.tsx b/apps/web/src/app/[locale]/accept-invite/[inviteId]/page.tsx
index 60324d40b..49af7bde2 100644
--- a/apps/web/src/app/[locale]/accept-invite/[inviteId]/page.tsx
+++ b/apps/web/src/app/[locale]/accept-invite/[inviteId]/page.tsx
@@ -32,6 +32,7 @@ export default async function JoinPage({
space: {
select: {
name: true,
+ image: true,
},
},
},
@@ -48,7 +49,11 @@ export default async function JoinPage({
<FullLogoLink />
<div className="flex w-full max-w-sm flex-col rounded-xl border bg-white p-12 text-center shadow-sm">
<div className="mx-auto mb-4">
- <SpaceIcon name={invite.space.name} size="lg" />
+ <SpaceIcon
+ src={invite.space.image ?? undefined}
+ name={invite.space.name}
+ size="lg"
+ />
</div>
<h1 className="font-bold text-base">
<Trans
diff --git a/apps/web/src/auth/data.ts b/apps/web/src/auth/data.ts
index 3c6249e72..2569e5239 100644
--- a/apps/web/src/auth/data.ts
+++ b/apps/web/src/auth/data.ts
@@ -141,5 +141,6 @@ export const requireSpace = cache(async () => {
name: spaceMember.space.name,
subscription: spaceMember.space.subscription,
role: spaceMember.role,
+ image: spaceMember.space.image,
});
});
diff --git a/apps/web/src/components/image-upload.tsx b/apps/web/src/components/image-upload.tsx
new file mode 100644
index 000000000..36b7aaaba
--- /dev/null
+++ b/apps/web/src/components/image-upload.tsx
@@ -0,0 +1,166 @@
+"use client";
+
+import { cn } from "@rallly/ui";
+import { Button } from "@rallly/ui/button";
+import { toast } from "@rallly/ui/sonner";
+import React from "react";
+import { z } from "zod";
+import { Trans } from "@/components/trans";
+import { useTranslation } from "@/i18n/client";
+import { useSafeAction } from "@/lib/safe-action/client";
+import { getImageUploadUrlAction } from "@/lib/storage/actions";
+import { uploadImage } from "@/lib/storage/image-upload";
+
+const allowedMimeTypes = z.enum(["image/jpeg", "image/png"]);
+
+export interface ImageUploadControlProps {
+ keyPrefix: "avatars" | "spaces";
+ onUploadSuccess: (imageKey: string) => Promise<void> | void;
+ onRemoveSuccess: () => Promise<void> | void;
+ hasCurrentImage?: boolean;
+}
+
+export interface ImageUploadPreviewProps {
+ className?: string;
+ children?: React.ReactNode;
+}
+
+export function ImageUpload({ children }: { children?: React.ReactNode }) {
+ return <div className="flex items-center gap-x-4">{children}</div>;
+}
+
+export function ImageUploadControl({
+ keyPrefix,
+ onUploadSuccess,
+ onRemoveSuccess,
+ hasCurrentImage = false,
+}: ImageUploadControlProps) {
+ const { t } = useTranslation();
+ const [isRemoving, startRemoving] = React.useTransition();
+ const [isUploading, startUploading] = React.useTransition();
+ const getUploadUrl = useSafeAction(getImageUploadUrlAction);
+
+ const handleFileChange = async (
+ event: React.ChangeEvent<HTMLInputElement>,
+ ) => {
+ const file = event.target.files?.[0];
+
+ if (!file) return;
+
+ const parsedFileType = allowedMimeTypes.safeParse(file.type);
+
+ if (!parsedFileType.success) {
+ toast.message(
+ t("invalidFileType", {
+ defaultValue: "Invalid file type",
+ }),
+ {
+ description: t("invalidFileTypeDescription", {
+ defaultValue: "Please upload a JPG or PNG file.",
+ }),
+ },
+ );
+ return;
+ }
+
+ const fileType = parsedFileType.data;
+
+ if (file.size > 2 * 1024 * 1024) {
+ toast.message(
+ t("fileTooLarge", {
+ defaultValue: "File too large",
+ }),
+ {
+ description: t("fileTooLargeDescription", {
+ defaultValue: "Please upload a file smaller than 2MB.",
+ }),
+ },
+ );
+ return;
+ }
+
+ startUploading(async () => {
+ try {
+ const result = await getUploadUrl.executeAsync({
+ keyPrefix,
+ fileType,
+ fileSize: file.size,
+ });
+
+ if (!result.data) {
+ throw new Error("Failed to get upload URL");
+ }
+
+ const { url, fields } = result.data;
+
+ await uploadImage({
+ file,
+ url,
+ fileType,
+ });
+
+ onUploadSuccess(fields.key);
+ } catch {
+ toast.error(
+ t("errorUploadPicture", {
+ defaultValue: "Failed to upload",
+ }),
+ {
+ description: t("errorUploadPictureDescription", {
+ defaultValue:
+ "There was an issue uploading your picture. Please try again later.",
+ }),
+ },
+ );
+ }
+ });
+ };
+
+ const handleRemove = async () => {
+ startRemoving(async () => {
+ await onRemoveSuccess();
+ });
+ };
+
+ return (
+ <div className="flex flex-col gap-y-2">
+ <div className="flex gap-2">
+ <Button
+ loading={isUploading}
+ onClick={() => {
+ document.getElementById("image-upload")?.click();
+ }}
+ >
+ <Trans i18nKey="uploadImage" defaults="Upload" />
+ </Button>
+ {hasCurrentImage ? (
+ <Button loading={isRemoving} variant="ghost" onClick={handleRemove}>
+ <Trans i18nKey="removeImage" defaults="Remove" />
+ </Button>
+ ) : null}
+ </div>
+ <p className="text-muted-foreground text-xs">
+ <Trans
+ i18nKey="imageUploadDescription"
+ defaults="Up to 2MB, JPG or PNG"
+ />
+ </p>
+ <input
+ id="image-upload"
+ type="file"
+ accept="image/*"
+ onChange={handleFileChange}
+ className="hidden"
+ />
+ </div>
+ );
+}
+
+export function ImageUploadPreview({
+ className,
+ children,
+}: ImageUploadPreviewProps) {
+ return (
+ <div className={cn("relative overflow-hidden", className)}>{children}</div>
+ );
+}
diff --git a/apps/web/src/features/space/actions.ts b/apps/web/src/features/space/actions.ts
index 88751bd6b..c521e1a79 100644
--- a/apps/web/src/features/space/actions.ts
+++ b/apps/web/src/features/space/actions.ts
@@ -4,6 +4,7 @@ import { subject } from "@casl/ability";
import { accessibleBy } from "@casl/prisma";
import { prisma } from "@rallly/database";
import { absoluteUrl } from "@rallly/utils/absolute-url";
+import { waitUntil } from "@vercel/functions";
import { z } from "zod";
import { updateSeatCount } from "@/features/billing/mutations";
import { getMember } from "@/features/space/data";
@@ -13,6 +14,10 @@ import { setActiveSpace } from "@/features/user/mutations";
import { AppError } from "@/lib/errors";
import { isFeatureEnabled } from "@/lib/feature-flags/server";
import { authActionClient, spaceActionClient } from "@/lib/safe-action/server";
+import {
+ deleteImageFromS3,
+ getImageUploadUrl,
+} from "@/lib/storage/image-upload";
import { getEmailClient } from "@/utils/emails";
export const setActiveSpaceAction = authActionClient
@@ -421,6 +426,7 @@ export const updateSpaceAction = spaceActionClient
.inputSchema(
z.object({
name: z.string().min(1).max(100),
+ image: z.string().optional(),
}),
)
.action(async ({ ctx, parsedInput }) => {
@@ -438,12 +444,122 @@ export const updateSpaceAction = spaceActionClient
});
}
+ const oldImage = ctx.space.image;
+
await prisma.space.update({
where: {
id: ctx.space.id,
},
data: {
name: parsedInput.name,
+ image: parsedInput.image,
},
});
+
+ // Delete old image from S3 if it exists and we're updating to a new image
+ if (oldImage && parsedInput.image && oldImage !== parsedInput.image) {
+ await deleteImageFromS3(oldImage);
+ }
+ });
+
+export const getSpaceImageUploadUrlAction = spaceActionClient
+ .metadata({
+ actionName: "space_get_image_upload_url",
+ })
+ .inputSchema(
+ z.object({
+ fileType: z.enum(["image/jpeg", "image/png"]),
+ fileSize: z.number(),
+ }),
+ )
+ .action(async ({ ctx, parsedInput }) => {
+ if (
+ ctx
+ .getMemberAbility()
+ .cannot(
+ "update",
+ subject("Space", { id: ctx.space.id, ownerId: ctx.space.ownerId }),
+ )
+ ) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "You do not have permission to update this space",
+ });
+ }
+
+ return await getImageUploadUrl({
+ keyPrefix: "spaces",
+ entityId: ctx.space.id,
+ fileType: parsedInput.fileType,
+ fileSize: parsedInput.fileSize,
+ });
+ });
+
+export const updateSpaceImageAction = spaceActionClient
+ .metadata({
+ actionName: "space_update_image",
+ })
+ .inputSchema(
+ z.object({
+ imageKey: z.string().max(255),
+ }),
+ )
+ .action(async ({ ctx, parsedInput }) => {
+ if (
+ ctx
+ .getMemberAbility()
+ .cannot(
+ "update",
+ subject("Space", { id: ctx.space.id, ownerId: ctx.space.ownerId }),
+ )
+ ) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "You do not have permission to update this space",
+ });
+ }
+
+ const oldImageKey = ctx.space.image;
+
+ await prisma.space.update({
+ where: { id: ctx.space.id },
+ data: { image: parsedInput.imageKey },
+ });
+
+ // Delete old image from S3 if it exists
+ if (oldImageKey) {
+ waitUntil(deleteImageFromS3(oldImageKey));
+ }
+ });
+
+export const removeSpaceImageAction = spaceActionClient
+ .metadata({
+ actionName: "space_remove_image",
+ })
+ .action(async ({ ctx }) => {
+ if (
+ ctx
+ .getMemberAbility()
+ .cannot(
+ "update",
+ subject("Space", { id: ctx.space.id, ownerId: ctx.space.ownerId }),
+ )
+ ) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "You do not have permission to update this space",
+ });
+ }
+
+ const oldImageKey = ctx.space.image;
+
+ await prisma.space.update({
+ where: { id: ctx.space.id },
+ data: { image: null },
+ });
+
+ // Delete image from S3 if it exists
+ if (oldImageKey) {
+ await deleteImageFromS3(oldImageKey);
+ }
});
diff --git a/apps/web/src/features/space/components/space-dropdown.tsx b/apps/web/src/features/space/components/space-dropdown.tsx
index 2c583c3ac..ecfe0194e 100644
--- a/apps/web/src/features/space/components/space-dropdown.tsx
+++ b/apps/web/src/features/space/components/space-dropdown.tsx
@@ -30,6 +30,7 @@ export function SpaceDropdown({
id: string;
name: string;
tier: "hobby" | "pro";
+ image?: string;
}[];
activeSpaceId: string;
children?: React.ReactNode;
@@ -64,7 +65,7 @@ export function SpaceDropdown({
value={space.id}
className="flex items-center gap-2"
>
- <SpaceIcon size="sm" name={space.name} />
+ <SpaceIcon size="sm" src={space.image} name={space.name} />
<span>{space.name}</span>
{space.tier === "pro" ? <ProBadge /> : null}
</DropdownMenuRadioItem>
diff --git a/apps/web/src/features/space/components/space-icon.tsx b/apps/web/src/features/space/components/space-icon.tsx
index a21a9e661..9bc42281b 100644
--- a/apps/web/src/features/space/components/space-icon.tsx
+++ b/apps/web/src/features/space/components/space-icon.tsx
@@ -3,18 +3,30 @@
import { cn } from "@rallly/ui";
import type { AvatarProps } from "@rallly/ui/avatar";
import { Avatar, AvatarFallback } from "@rallly/ui/avatar";
+import Image from "next/image";
type SpaceIconProps = {
name: string;
className?: string;
+ src?: string;
} & AvatarProps;
-export function SpaceIcon({ name, className, size }: SpaceIconProps) {
+export function SpaceIcon({ name, src, className, size }: SpaceIconProps) {
return (
<Avatar className={cn(className)} size={size}>
- <AvatarFallback seed={name}>
- {name.slice(0, 2).toUpperCase()}
- </AvatarFallback>
+ {src ? (
+ <Image
+ src={`/api/storage/${src}`}
+ width={128}
+ height={128}
+ alt={name}
+ style={{ objectFit: "cover" }}
+ />
+ ) : (
+ <AvatarFallback seed={name}>
+ {name.slice(0, 2).toUpperCase()}
+ </AvatarFallback>
+ )}
</Avatar>
);
}
diff --git a/apps/web/src/features/space/data.ts b/apps/web/src/features/space/data.ts
index 438834529..c7a9989af 100644
--- a/apps/web/src/features/space/data.ts
+++ b/apps/web/src/features/space/data.ts
@@ -56,6 +56,7 @@ export function createSpaceDTO(space: {
ownerId: string;
name: string;
role: DBSpaceMemberRole;
+ image?: string | null;
subscription: {
active: boolean;
} | null;
@@ -66,6 +67,7 @@ export function createSpaceDTO(space: {
ownerId: space.ownerId,
tier: getSpaceTier(space),
role: fromDBRole(space.role),
+ image: space.image ?? undefined,
} satisfies SpaceDTO;
}
@@ -74,8 +76,16 @@ export const loadSpaces = cache(async () => {
const ability = defineAbilityFor(user);
const spaces = await prisma.space.findMany({
where: accessibleBy(ability).Space,
- include: {
- subscription: true,
+ select: {
+ id: true,
+ name: true,
+ ownerId: true,
+ image: true,
+ subscription: {
+ select: {
+ active: true,
+ },
+ },
members: {
where: {
userId: user.id,
@@ -104,6 +114,7 @@ export const loadSpaces = cache(async () => {
ownerId: space.ownerId,
tier: space.subscription?.active ? "pro" : "hobby",
role: fromDBRole(role),
+ image: space.image ?? undefined,
} satisfies SpaceDTO;
})
.filter(Boolean) as SpaceDTO[];
diff --git a/apps/web/src/features/space/types.ts b/apps/web/src/features/space/types.ts
index 3121217eb..c889e39f7 100644
--- a/apps/web/src/features/space/types.ts
+++ b/apps/web/src/features/space/types.ts
@@ -6,4 +6,5 @@ export type SpaceDTO = {
ownerId: string;
tier: "hobby" | "pro";
role: MemberRole;
+ image?: string;
};
diff --git a/apps/web/src/lib/errors.ts b/apps/web/src/lib/errors.ts
index 19b0be2cd..f4e6f18e1 100644
--- a/apps/web/src/lib/errors.ts
+++ b/apps/web/src/lib/errors.ts
@@ -1,9 +1,11 @@
-type AppErrorCode =
+export type AppErrorCode =
| "UNAUTHORIZED"
| "NOT_FOUND"
| "FORBIDDEN"
| "INTERNAL_SERVER_ERROR"
| "PAYMENT_REQUIRED"
+ | "PAYLOAD_TOO_LARGE"
+ | "SERVICE_UNAVAILABLE"
| "TOO_MANY_REQUESTS";
export class AppError extends Error {
diff --git a/apps/web/src/lib/safe-action/client.ts b/apps/web/src/lib/safe-action/client.ts
index 4c91a89ea..67a5671d2 100644
--- a/apps/web/src/lib/safe-action/client.ts
+++ b/apps/web/src/lib/safe-action/client.ts
@@ -3,6 +3,7 @@ import { toast } from "@rallly/ui/sonner";
import { useRouter } from "next/navigation";
import { useAction } from "next-safe-action/hooks";
import { useTranslation } from "@/i18n/client";
+import type { AppErrorCode } from "@/lib/errors";
export const useSafeAction: typeof useAction = (action, options) => {
const { t } = useTranslation();
@@ -17,7 +18,7 @@ export const useSafeAction: typeof useAction = (action, options) => {
if (error.serverError) {
let translatedDescription = "An unexpected error occurred";
- switch (error.serverError) {
+ switch (error.serverError as AppErrorCode) {
case "UNAUTHORIZED":
translatedDescription = t("actionErrorUnauthorized", {
defaultValue: "You are not authorized to perform this action",
@@ -48,6 +49,18 @@ export const useSafeAction: typeof useAction = (action, options) => {
defaultValue: "You need to upgrade to perform this action",
});
break;
+ case "SERVICE_UNAVAILABLE":
+ translatedDescription = t("actionErrorServiceUnavailable", {
+ defaultValue:
+ "The service required to perform this action is not available",
+ });
+ break;
+ case "PAYLOAD_TOO_LARGE":
+ translatedDescription = t("actionErrorPayloadTooLarge", {
+ defaultValue:
+ "The file you uploaded is too large. Please try a smaller file.",
+ });
+ break;
}
toast.error(translatedDescription);
diff --git a/apps/web/src/lib/safe-action/server.ts b/apps/web/src/lib/safe-action/server.ts
index 2fac3e950..d70eb864d 100644
--- a/apps/web/src/lib/safe-action/server.ts
+++ b/apps/web/src/lib/safe-action/server.ts
@@ -69,7 +69,7 @@ export const actionClient = createSafeActionClient({
z.object({
actionName: z.string(),
}),
- handleServerError: async (error, { metadata }) => {
+ handleServerError: (error, { metadata }) => {
Sentry.captureException(error, {
tags: {
errorHandler: "safe-action",
@@ -83,7 +83,7 @@ export const actionClient = createSafeActionClient({
return error.code;
}
- return "INTERNAL_SERVER_ERROR";
+ return "INTERNAL_SERVER_ERROR" as const;
},
});
diff --git a/apps/web/src/lib/storage/actions.ts b/apps/web/src/lib/storage/actions.ts
new file mode 100644
index 000000000..c27f63a05
--- /dev/null
+++ b/apps/web/src/lib/storage/actions.ts
@@ -0,0 +1,37 @@
+"use server";
+
+import { z } from "zod";
+import { AppError } from "@/lib/errors";
+import { authActionClient } from "@/lib/safe-action/server";
+import { isStorageEnabled } from "@/lib/storage/constants";
+import { getImageUploadUrl } from "./image-upload";
+
+export const getImageUploadUrlAction = authActionClient
+ .metadata({
+ actionName: "get_image_upload_url",
+ })
+ .inputSchema(
+ z.object({
+ keyPrefix: z.enum(["avatars", "spaces"]),
+ fileType: z.enum(["image/jpeg", "image/png"]),
+ fileSize: z.number(),
+ }),
+ )
+ .use(async ({ next }) => {
+ if (!isStorageEnabled) {
+ throw new AppError({
+ code: "SERVICE_UNAVAILABLE",
+ message:
+ "This feature requires an object store to be configured on this instance.",
+ });
+ }
+ return next();
+ })
+ .action(async ({ ctx, parsedInput }) => {
+ return await getImageUploadUrl({
+ keyPrefix: parsedInput.keyPrefix,
+ entityId: ctx.user.id,
+ fileType: parsedInput.fileType,
+ fileSize: parsedInput.fileSize,
+ });
+ });
diff --git a/apps/web/src/lib/storage/constants.ts b/apps/web/src/lib/storage/constants.ts
new file mode 100644
index 000000000..149a0da15
--- /dev/null
+++ b/apps/web/src/lib/storage/constants.ts
@@ -0,0 +1,5 @@
+import { env } from "@/env";
+
+export const isStorageEnabled = Boolean(
+ env.S3_BUCKET_NAME && env.S3_ACCESS_KEY_ID && env.S3_SECRET_ACCESS_KEY,
+);
diff --git a/apps/web/src/lib/storage/image-upload.ts b/apps/web/src/lib/storage/image-upload.ts
new file mode 100644
index 000000000..169d3bec5
--- /dev/null
+++ b/apps/web/src/lib/storage/image-upload.ts
@@ -0,0 +1,99 @@
+import { DeleteObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
+import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
+
+import { env } from "@/env";
+import { AppError } from "@/lib/errors";
+import { getS3Client } from "./s3";
+
+const mimeToExtension = {
+ "image/jpeg": "jpg",
+ "image/png": "png",
+} as const;
+
+export interface GetImageUploadUrlParams {
+ keyPrefix: string;
+ entityId: string;
+ fileType: "image/jpeg" | "image/png";
+ fileSize: number;
+}
+
+export async function getImageUploadUrl({
+ keyPrefix,
+ entityId,
+ fileType,
+ fileSize,
+}: GetImageUploadUrlParams) {
+ const s3Client = getS3Client();
+
+ if (!s3Client) {
+ throw new AppError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "S3 storage has not been configured",
+ });
+ }
+
+ if (fileSize > 2 * 1024 * 1024) {
+ throw new AppError({
+ code: "PAYLOAD_TOO_LARGE",
+ message: "File size too large",
+ });
+ }
+
+ const key = `${keyPrefix}/${entityId}-${Date.now()}.${mimeToExtension[fileType]}`;
+
+ const command = new PutObjectCommand({
+ Bucket: env.S3_BUCKET_NAME,
+ Key: key,
+ ContentType: fileType,
+ ContentLength: fileSize,
+ });
+
+ const url = await getSignedUrl(s3Client, command, { expiresIn: 3600 });
+
+ return {
+ success: true,
+ url,
+ fields: {
+ key,
+ },
+ } as const;
+}
+
+export interface UploadImageParams {
+ file: File;
+ url: string;
+ fileType: "image/jpeg" | "image/png";
+}
+
+export async function uploadImage({
+ file,
+ url,
+ fileType,
+}: UploadImageParams): Promise<void> {
+ const response = await fetch(url, {
+ method: "PUT",
+ body: file,
+ headers: {
+ "Content-Type": fileType,
+ "Content-Length": file.size.toString(),
+ },
+ });
+
+ if (!response.ok) {
+ throw new AppError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Failed to upload image to storage",
+ });
+ }
+}
+
+export async function deleteImageFromS3(imageKey: string) {
+ const s3Client = getS3Client();
+
+ s3Client?.send(
+ new DeleteObjectCommand({
+ Bucket: env.S3_BUCKET_NAME,
+ Key: imageKey,
+ }),
+ );
+}
diff --git a/apps/web/src/lib/storage/index.ts b/apps/web/src/lib/storage/index.ts
index 240c01c3a..bffb59158 100644
--- a/apps/web/src/lib/storage/index.ts
+++ b/apps/web/src/lib/storage/index.ts
@@ -1,4 +1,2 @@
-export const isStorageEnabled =
- !!process.env.S3_BUCKET_NAME &&
- !!process.env.S3_ACCESS_KEY_ID &&
- !!process.env.S3_SECRET_ACCESS_KEY;
+export * from "./actions";
+export * from "./constants";
diff --git a/apps/web/src/trpc/routers/user.ts b/apps/web/src/trpc/routers/user.ts
index 3651773c1..0301cfcd6 100644
--- a/apps/web/src/trpc/routers/user.ts
+++ b/apps/web/src/trpc/routers/user.ts
@@ -1,13 +1,11 @@
-import { DeleteObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
-import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { prisma } from "@rallly/database";
import { absoluteUrl } from "@rallly/utils/absolute-url";
import { TRPCError } from "@trpc/server";
-import { waitUntil } from "@vercel/functions";
import { z } from "zod";
-
-import { env } from "@/env";
-import { getS3Client } from "@/lib/storage/s3";
+import {
+ deleteImageFromS3,
+ getImageUploadUrl,
+} from "@/lib/storage/image-upload";
import { getEmailClient } from "@/utils/emails";
import { createToken } from "@/utils/session";
import {
@@ -17,11 +15,6 @@ import {
router,
} from "../trpc";
-const mimeToExtension = {
- "image/jpeg": "jpg",
- "image/png": "png",
-} as const;
-
export const user = router({
getByEmail: publicProcedure
.input(z.object({ email: z.string() }))
@@ -157,41 +150,12 @@ export const user = router({
}),
)
.mutation(async ({ ctx, input }) => {
- const s3Client = getS3Client();
-
- if (!s3Client) {
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "S3 storage has not been configured",
- });
- }
-
- const userId = ctx.user.id;
- const key = `avatars/${userId}-${Date.now()}.${mimeToExtension[input.fileType]}`;
-
- if (input.fileSize > 2 * 1024 * 1024) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "File size too large",
- });
- }
-
- const command = new PutObjectCommand({
- Bucket: env.S3_BUCKET_NAME,
- Key: key,
- ContentType: input.fileType,
- ContentLength: input.fileSize,
+ return await getImageUploadUrl({
+ keyPrefix: "avatars",
+ entityId: ctx.user.id,
+ fileType: input.fileType,
+ fileSize: input.fileSize,
});
-
- const url = await getSignedUrl(s3Client, command, { expiresIn: 3600 });
-
- return {
- success: true,
- url,
- fields: {
- key,
- },
- } as const;
}),
updateAvatar: privateProcedure
.input(z.object({ imageKey: z.string().max(255) }))
@@ -204,23 +168,16 @@ export const user = router({
data: { image: input.imageKey },
});
- const s3Client = getS3Client();
-
- if (oldImageKey && s3Client) {
- waitUntil(
- s3Client?.send(
- new DeleteObjectCommand({
- Bucket: env.S3_BUCKET_NAME,
- Key: oldImageKey,
- }),
- ),
- );
+ // Delete old image from S3 if it exists
+ if (oldImageKey) {
+ await deleteImageFromS3(oldImageKey);
}
return { success: true };
}),
removeAvatar: privateProcedure.mutation(async ({ ctx }) => {
const userId = ctx.user.id;
+ const oldImageKey = ctx.user.image;
await prisma.user.update({
where: { id: userId },
@@ -228,24 +185,12 @@ export const user = router({
});
// Delete the avatar from storage if it's an internal avatar
- const isInternalAvatar =
- ctx.user.image && !ctx.user.image.startsWith("https://");
+ const isInternalAvatar = oldImageKey && !oldImageKey.startsWith("https://");
if (isInternalAvatar) {
- const s3Client = getS3Client();
-
- if (s3Client) {
- waitUntil(
- s3Client.send(
- new DeleteObjectCommand({
- Bucket: env.S3_BUCKET_NAME,
- Key: ctx.user.image,
- }),
- ),
- );
- }
-
- return { success: true };
+ await deleteImageFromS3(oldImageKey);
}
+
+ return { success: true };
}),
});
diff --git a/packages/database/prisma/migrations/20250804130713_add_space_image_column/migration.sql b/packages/database/prisma/migrations/20250804130713_add_space_image_column/migration.sql
new file mode 100644
index 000000000..cc62bbda1
--- /dev/null
+++ b/packages/database/prisma/migrations/20250804130713_add_space_image_column/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "spaces" ADD COLUMN "image" TEXT;
diff --git a/packages/database/prisma/models/space.prisma b/packages/database/prisma/models/space.prisma
index 5b3614751..7f0b0d2d8 100644
--- a/packages/database/prisma/models/space.prisma
+++ b/packages/database/prisma/models/space.prisma
@@ -1,6 +1,7 @@
model Space {
id String @id @default(uuid())
name String
+ image String?
ownerId String @map("owner_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")