Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Refactor icon handling to properly use RPC and signed URLs (#1274)

Brendan Allan2e56050d4421
diff --git a/apps/web/actions/organization/upload-space-icon.ts b/apps/web/actions/organization/upload-space-icon.ts
index 891885914..b2c532574 100644
--- a/apps/web/actions/organization/upload-space-icon.ts
+++ b/apps/web/actions/organization/upload-space-icon.ts
@@ -3,9 +3,8 @@
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { spaces } from "@cap/database/schema";
-import { serverEnv } from "@cap/env";
import { S3Buckets } from "@cap/web-backend";
-import type { Space } from "@cap/web-domain";
+import { ImageUpload, type Space } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { Effect, Option } from "effect";
import { revalidatePath } from "next/cache";
@@ -54,9 +53,11 @@ export async function uploadSpaceIcon(
// Prepare new file key
const fileExtension = file.name.split(".").pop();
- const fileKey = `organizations/${
- space.organizationId
- }/spaces/${spaceId}/icon-${Date.now()}.${fileExtension}`;
+ const fileKey = ImageUpload.ImageKey.make(
+ `organizations/${
+ space.organizationId
+ }/spaces/${spaceId}/icon-${Date.now()}.${fileExtension}`,
+ );
const [bucket] = await S3Buckets.getBucketAccess(Option.none()).pipe(
runPromise,
@@ -89,12 +90,13 @@ export async function uploadSpaceIcon(
)
.pipe(runPromise);
- const iconUrl = fileKey;
-
- await db().update(spaces).set({ iconUrl }).where(eq(spaces.id, spaceId));
+ await db()
+ .update(spaces)
+ .set({ iconUrl: fileKey })
+ .where(eq(spaces.id, spaceId));
revalidatePath("/dashboard");
- return { success: true, iconUrl };
+ return { success: true, iconUrl: fileKey };
} catch (error) {
console.error("Error uploading space icon:", error);
throw new Error(error instanceof Error ? error.message : "Upload failed");
diff --git a/apps/web/app/(org)/dashboard/Contexts.tsx b/apps/web/app/(org)/dashboard/Contexts.tsx
index ae9459ea4..6caeee6ad 100644
--- a/apps/web/app/(org)/dashboard/Contexts.tsx
+++ b/apps/web/app/(org)/dashboard/Contexts.tsx
@@ -1,10 +1,10 @@
"use client";
-import type { users } from "@cap/database/schema";
import { buildEnv } from "@cap/env";
import Cookies from "js-cookie";
-import { usePathname } from "next/navigation";
+import { redirect, usePathname } from "next/navigation";
import { createContext, useContext, useEffect, useState } from "react";
+import { type CurrentUser, useCurrentUser } from "@/app/Layout/AuthContext";
import { UpgradeModal } from "@/components/UpgradeModal";
import type {
Organization,
@@ -21,7 +21,7 @@ type SharedContext = {
userSpaces: Spaces[] | null;
sharedSpaces: Spaces[] | null;
activeSpace: Spaces | null;
- user: typeof users.$inferSelect;
+ user: CurrentUser;
userCapsCount: number | null;
isSubscribed: boolean;
toggleSidebarCollapsed: () => void;
@@ -56,7 +56,6 @@ export function DashboardContexts({
activeOrganization,
spacesData,
userCapsCount,
- user,
isSubscribed,
organizationSettings,
userPreferences,
@@ -70,7 +69,6 @@ export function DashboardContexts({
activeOrganization: SharedContext["activeOrganization"];
spacesData: SharedContext["spacesData"];
userCapsCount: SharedContext["userCapsCount"];
- user: SharedContext["user"];
isSubscribed: SharedContext["isSubscribed"];
organizationSettings: SharedContext["organizationSettings"];
userPreferences: SharedContext["userPreferences"];
@@ -79,6 +77,9 @@ export function DashboardContexts({
initialSidebarCollapsed: boolean;
referClicked: boolean;
}) {
+ const user = useCurrentUser();
+ if (!user) redirect("/login");
+
const [theme, setTheme] = useState<ITheme>(initialTheme);
const [sidebarCollapsed, setSidebarCollapsed] = useState(
initialSidebarCollapsed,
diff --git a/apps/web/app/(org)/dashboard/_components/MobileTab.tsx b/apps/web/app/(org)/dashboard/_components/MobileTab.tsx
index ce1b469a9..7ff0c8847 100644
--- a/apps/web/app/(org)/dashboard/_components/MobileTab.tsx
+++ b/apps/web/app/(org)/dashboard/_components/MobileTab.tsx
@@ -78,7 +78,6 @@ const Orgs = ({
<SignedImageUrl
image={activeOrg?.organization.iconUrl}
name={activeOrg?.organization.name ?? "No organization found"}
- type="organization"
letterClass="text-xs"
className="relative flex-shrink-0 mx-auto size-6"
/>
@@ -138,7 +137,6 @@ const OrgsMenu = ({
<SignedImageUrl
image={organization.organization.iconUrl}
name={organization.organization.name}
- type="organization"
letterClass="text-xs"
className="relative flex-shrink-0 size-5"
/>
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
index 4515df3fe..420e56ec6 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
@@ -127,7 +127,6 @@ const AdminNavItems = ({ toggleMobileNav }: Props) => {
name={
activeOrg?.organization.name ?? "No organization found"
}
- type="organization"
letterClass={clsx(
sidebarCollapsed ? "text-sm" : "text-[13px]",
)}
@@ -216,7 +215,6 @@ const AdminNavItems = ({ toggleMobileNav }: Props) => {
<SignedImageUrl
image={organization.organization.iconUrl}
name={organization.organization.name}
- type="organization"
letterClass="text-xs"
className="relative flex-shrink-0 size-5"
/>
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/SpaceDialog.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/SpaceDialog.tsx
index 2de90da95..668da19c0 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/SpaceDialog.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/SpaceDialog.tsx
@@ -14,6 +14,7 @@ import {
Input,
Label,
} from "@cap/ui";
+import type { ImageUpload } from "@cap/web-domain";
import { faLayerGroup } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
@@ -36,7 +37,7 @@ interface SpaceDialogProps {
id: string;
name: string;
members: string[];
- iconUrl?: string;
+ iconUrl?: ImageUpload.ImageUrl;
} | null;
onSpaceUpdated?: () => void;
}
@@ -117,7 +118,7 @@ export interface NewSpaceFormProps {
id: string;
name: string;
members: string[];
- iconUrl?: string;
+ iconUrl?: ImageUpload.ImageUrl;
} | null;
}
@@ -277,7 +278,6 @@ export const NewSpaceForm: React.FC<NewSpaceFormProps> = (props) => {
<FileInput
id="space-icon"
name="icon"
- type="organization"
initialPreviewUrl={space?.iconUrl || null}
notDraggingClassName="hover:bg-gray-3"
onChange={setSelectedFile}
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/SpacesList.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/SpacesList.tsx
index 8933d19b8..7fddb1a68 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/SpacesList.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/SpacesList.tsx
@@ -282,7 +282,6 @@ const SpacesList = ({ toggleMobileNav }: { toggleMobileNav?: () => void }) => {
<SignedImageUrl
image={space.iconUrl}
name={space.name}
- type="organization"
letterClass={clsx(
sidebarCollapsed ? "text-sm" : "text-[11px]",
)}
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
index c1bc6469b..5f1022bd2 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
@@ -104,7 +104,6 @@ const Top = () => {
<SignedImageUrl
image={activeSpace.iconUrl}
name={activeSpace?.name}
- type="organization"
letterClass="text-xs"
className="relative flex-shrink-0 size-5"
/>
@@ -262,9 +261,8 @@ const User = () => {
>
<div className="flex items-center">
<SignedImageUrl
- image={user.image}
+ image={user.imageUrl}
name={user.name ?? "User"}
- type="user"
letterClass="text-xs lg:text-md"
className="flex-shrink-0 size-[24px] text-gray-12"
/>
diff --git a/apps/web/app/(org)/dashboard/caps/Caps.tsx b/apps/web/app/(org)/dashboard/caps/Caps.tsx
index bc0ff17e6..6d27c4b0d 100644
--- a/apps/web/app/(org)/dashboard/caps/Caps.tsx
+++ b/apps/web/app/(org)/dashboard/caps/Caps.tsx
@@ -2,17 +2,15 @@
import type { VideoMetadata } from "@cap/database/types";
import { Button } from "@cap/ui";
-import type { Video } from "@cap/web-domain";
+import type { ImageUpload, Video } from "@cap/web-domain";
import { faFolderPlus, faInfoCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Effect, Exit } from "effect";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
-import { useEffectMutation } from "@/lib/EffectRuntime";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
import { useVideosAnalyticsQuery } from "@/lib/Queries/Analytics";
-import { AnalyticsRequest } from "@/lib/Requests/AnalyticsRequest";
-import { Rpc, withRpc } from "@/lib/Rpcs";
import { useDashboardContext } from "../Contexts";
import {
NewFolderDialog,
@@ -36,11 +34,14 @@ export type VideoData = {
totalComments: number;
totalReactions: number;
foldersData: FolderDataType[];
- sharedOrganizations: { id: string; name: string; iconUrl?: string }[];
+ sharedOrganizations: {
+ id: string;
+ name: string;
+ iconUrl?: ImageUpload.ImageUrl | null;
+ }[];
sharedSpaces?: {
id: string;
name: string;
- iconUrl: string;
isOrg: boolean;
organizationId: string;
}[];
@@ -147,12 +148,12 @@ export const Caps = ({
});
};
+ const rpc = useRpcClient();
+
const { mutate: deleteCaps, isPending: isDeletingCaps } = useEffectMutation({
mutationFn: Effect.fn(function* (ids: Video.VideoId[]) {
if (ids.length === 0) return;
- const rpc = yield* Rpc;
-
const fiber = yield* Effect.gen(function* () {
const results = yield* Effect.all(
ids.map((id) => rpc.VideoDelete(id).pipe(Effect.exit)),
@@ -203,7 +204,7 @@ export const Caps = ({
});
const { mutate: deleteCap, isPending: isDeletingCap } = useEffectMutation({
- mutationFn: (id: Video.VideoId) => withRpc((r) => r.VideoDelete(id)),
+ mutationFn: (id: Video.VideoId) => rpc.VideoDelete(id),
onSuccess: () => {
toast.success("Cap deleted successfully");
router.refresh();
diff --git a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx
index a6fa4d6e6..3f5272559 100644
--- a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx
@@ -8,7 +8,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@cap/ui";
-import type { Video } from "@cap/web-domain";
+import type { ImageUpload, Video } from "@cap/web-domain";
import { HttpClient } from "@effect/platform";
import {
faCheck,
@@ -41,7 +41,7 @@ import {
type ImageLoadingStatus,
VideoThumbnail,
} from "@/components/VideoThumbnail";
-import { useEffectMutation } from "@/lib/EffectRuntime";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
import { withRpc } from "@/lib/Rpcs";
import { usePublicEnv } from "@/utils/public-env";
import { PasswordDialog } from "../PasswordDialog";
@@ -63,12 +63,12 @@ export interface CapCardProps extends PropsWithChildren {
sharedOrganizations?: {
id: string;
name: string;
- iconUrl?: string | null;
+ iconUrl?: ImageUpload.ImageUrl | null;
}[];
sharedSpaces?: {
id: string;
name: string;
- iconUrl?: string | null;
+ iconUrl?: ImageUpload.ImageUrl | null;
organizationId: string;
}[];
ownerName: string | null;
@@ -133,11 +133,12 @@ export const CapCard = ({
const [confirmOpen, setConfirmOpen] = useState(false);
const router = useRouter();
+ const rpc = useRpcClient();
const downloadMutation = useEffectMutation({
mutationFn: () =>
Effect.gen(function* () {
- const result = yield* withRpc((r) => r.VideoGetDownloadInfo(cap.id));
+ const result = yield* rpc.VideoGetDownloadInfo(cap.id);
const httpClient = yield* HttpClient.HttpClient;
if (Option.isSome(result)) {
const fetchResponse = yield* httpClient.get(result.value.downloadUrl);
@@ -175,7 +176,7 @@ export const CapCard = ({
});
const duplicateMutation = useEffectMutation({
- mutationFn: () => withRpc((r) => r.VideoDuplicate(cap.id)),
+ mutationFn: () => rpc.VideoDuplicate(cap.id),
onSuccess: () => {
router.refresh();
},
diff --git a/apps/web/app/(org)/dashboard/caps/components/Folder.tsx b/apps/web/app/(org)/dashboard/caps/components/Folder.tsx
index 239821e25..becf3f852 100644
--- a/apps/web/app/(org)/dashboard/caps/components/Folder.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/Folder.tsx
@@ -9,8 +9,7 @@ import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { moveVideoToFolder } from "@/actions/folders/moveVideoToFolder";
-import { useEffectMutation } from "@/lib/EffectRuntime";
-import { withRpc } from "@/lib/Rpcs";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
import { ConfirmationDialog } from "../../_components/ConfirmationDialog";
import { useDashboardContext, useTheme } from "../../Contexts";
import { registerDropTarget } from "../../folder/[id]/components/ClientCapCard";
@@ -70,8 +69,10 @@ const FolderCard = ({
}),
});
+ const rpc = useRpcClient();
+
const deleteFolder = useEffectMutation({
- mutationFn: (id: Folder.FolderId) => withRpc((r) => r.FolderDelete(id)),
+ mutationFn: (id: Folder.FolderId) => rpc.FolderDelete(id),
onSuccess: () => {
router.refresh();
toast.success("Folder deleted successfully");
@@ -83,8 +84,7 @@ const FolderCard = ({
});
const updateFolder = useEffectMutation({
- mutationFn: (data: Folder.FolderUpdate) =>
- withRpc((r) => r.FolderUpdate(data)),
+ mutationFn: (data: Folder.FolderUpdate) => rpc.FolderUpdate(data),
onSuccess: () => {
toast.success("Folder name updated successfully");
router.refresh();
diff --git a/apps/web/app/(org)/dashboard/caps/components/NewFolderDialog.tsx b/apps/web/app/(org)/dashboard/caps/components/NewFolderDialog.tsx
index 6565de9b7..065f2e4ea 100644
--- a/apps/web/app/(org)/dashboard/caps/components/NewFolderDialog.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/NewFolderDialog.tsx
@@ -18,8 +18,7 @@ import { Option } from "effect";
import { useRouter } from "next/navigation";
import React, { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
-import { useEffectMutation } from "@/lib/EffectRuntime";
-import { withRpc } from "@/lib/Rpcs";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
import {
BlueFolder,
type FolderHandle,
@@ -101,16 +100,16 @@ export const NewFolderDialog: React.FC<Props> = ({
),
);
+ const rpc = useRpcClient();
+
const createFolder = useEffectMutation({
mutationFn: (data: { name: string; color: Folder.FolderColor }) =>
- withRpc((r) =>
- r.FolderCreate({
- name: data.name,
- color: data.color,
- spaceId: Option.fromNullable(spaceId),
- parentId: Option.none(),
- }),
- ),
+ rpc.FolderCreate({
+ name: data.name,
+ color: data.color,
+ spaceId: Option.fromNullable(spaceId),
+ parentId: Option.none(),
+ }),
onSuccess: () => {
setFolderName("");
setSelectedColor(null);
diff --git a/apps/web/app/(org)/dashboard/caps/components/SettingsDialog.tsx b/apps/web/app/(org)/dashboard/caps/components/SettingsDialog.tsx
index 06226dd17..14372dac8 100644
--- a/apps/web/app/(org)/dashboard/caps/components/SettingsDialog.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/SettingsDialog.tsx
@@ -96,8 +96,6 @@ export const SettingsDialog = ({
}
}, [buildSettings, isOpen, settingsData]);
- const isUserPro = userIsPro(user);
-
const saveHandler = async () => {
if (!settings) return;
setSaveLoading(true);
@@ -193,7 +191,7 @@ export const SettingsDialog = ({
</div>
<Switch
disabled={
- (option.pro && !isUserPro) ||
+ (option.pro && !user.isPro) ||
((key === "disableSummary" || key === "disableChapters") &&
getEffectiveValue(
"disableTranscript" as keyof OrganizationSettings,
diff --git a/apps/web/app/(org)/dashboard/caps/components/SharingDialog.tsx b/apps/web/app/(org)/dashboard/caps/components/SharingDialog.tsx
index 5db9749c0..71d0e4405 100644
--- a/apps/web/app/(org)/dashboard/caps/components/SharingDialog.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/SharingDialog.tsx
@@ -9,7 +9,7 @@ import {
Input,
Switch,
} from "@cap/ui";
-import { Space, type Video } from "@cap/web-domain";
+import { type ImageUpload, Space, type Video } from "@cap/web-domain";
import { faCopy, faShareNodes } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useMutation } from "@tanstack/react-query";
@@ -388,7 +388,7 @@ const SpaceCard = ({
space: {
id: string;
name: string;
- iconUrl?: string | null;
+ iconUrl?: ImageUpload.ImageUrl | null;
organizationId: string;
};
selectedSpaces: Set<string>;
@@ -419,7 +419,6 @@ const SpaceCard = ({
<SignedImageUrl
image={space.iconUrl}
name={space.name}
- type="organization"
letterClass="text-[11px]"
className="relative z-10 flex-shrink-0 size-5"
/>
diff --git a/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx b/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
index 8449a5f73..885642e06 100644
--- a/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
@@ -38,9 +38,7 @@ export const UploadCapButton = ({
const handleClick = () => {
if (!user) return;
- const isCapPro = userIsPro(user);
-
- if (!isCapPro) {
+ if (!user.isPro) {
setUpgradeModalOpen(true);
return;
}
diff --git a/apps/web/app/(org)/dashboard/caps/page.tsx b/apps/web/app/(org)/dashboard/caps/page.tsx
index f86da3da9..a4da232f3 100644
--- a/apps/web/app/(org)/dashboard/caps/page.tsx
+++ b/apps/web/app/(org)/dashboard/caps/page.tsx
@@ -12,10 +12,13 @@ import {
videoUploads,
} from "@cap/database/schema";
import { serverEnv } from "@cap/env";
-import { Video } from "@cap/web-domain";
+import { Database, ImageUploads } from "@cap/web-backend";
+import { type ImageUpload, Video } from "@cap/web-domain";
import { and, count, desc, eq, inArray, isNull, sql } from "drizzle-orm";
+import { type Array, Effect } from "effect";
import type { Metadata } from "next";
import { redirect } from "next/navigation";
+import { runPromise } from "@/lib/server";
import { Caps } from "./Caps";
export const metadata: Metadata = {
@@ -23,35 +26,45 @@ export const metadata: Metadata = {
};
// Helper function to fetch shared spaces data for videos
-async function getSharedSpacesForVideos(videoIds: Video.VideoId[]) {
+const getSharedSpacesForVideos = Effect.fn(function* (
+ videoIds: Video.VideoId[],
+) {
if (videoIds.length === 0) return {};
+ const db = yield* Database;
+
// Fetch space-level sharing
- const spaceSharing = await db()
- .select({
- videoId: spaceVideos.videoId,
- id: spaces.id,
- name: spaces.name,
- organizationId: spaces.organizationId,
- iconUrl: organizations.iconUrl,
- })
- .from(spaceVideos)
- .innerJoin(spaces, eq(spaceVideos.spaceId, spaces.id))
- .innerJoin(organizations, eq(spaces.organizationId, organizations.id))
- .where(inArray(spaceVideos.videoId, videoIds));
+ const spaceSharing = yield* db.use((db) =>
+ db
+ .select({
+ videoId: spaceVideos.videoId,
+ id: spaces.id,
+ name: spaces.name,
+ organizationId: spaces.organizationId,
+ })
+ .from(spaceVideos)
+ .innerJoin(spaces, eq(spaceVideos.spaceId, spaces.id))
+ .innerJoin(organizations, eq(spaces.organizationId, organizations.id))
+ .where(inArray(spaceVideos.videoId, videoIds)),
+ );
// Fetch organization-level sharing
- const orgSharing = await db()
- .select({
- videoId: sharedVideos.videoId,
- id: organizations.id,
- name: organizations.name,
- organizationId: organizations.id,
- iconUrl: organizations.iconUrl,
- })
- .from(sharedVideos)
- .innerJoin(organizations, eq(sharedVideos.organizationId, organizations.id))
- .where(inArray(sharedVideos.videoId, videoIds));
+ const orgSharing = yield* db.use((db) =>
+ db
+ .select({
+ videoId: sharedVideos.videoId,
+ id: organizations.id,
+ name: organizations.name,
+ organizationId: organizations.id,
+ iconUrl: organizations.iconUrl,
+ })
+ .from(sharedVideos)
+ .innerJoin(
+ organizations,
+ eq(sharedVideos.organizationId, organizations.id),
+ )
+ .where(inArray(sharedVideos.videoId, videoIds)),
+ );
// Combine and group by videoId
const sharedSpacesMap: Record<
@@ -60,7 +73,6 @@ async function getSharedSpacesForVideos(videoIds: Video.VideoId[]) {
id: string;
name: string;
organizationId: string;
- iconUrl: string;
isOrg: boolean;
}>
> = {};
@@ -74,7 +86,6 @@ async function getSharedSpacesForVideos(videoIds: Video.VideoId[]) {
id: space.id,
name: space.name,
organizationId: space.organizationId,
- iconUrl: space.iconUrl || "",
isOrg: false,
});
});
@@ -88,13 +99,12 @@ async function getSharedSpacesForVideos(videoIds: Video.VideoId[]) {
id: org.id,
name: org.name,
organizationId: org.organizationId,
- iconUrl: org.iconUrl || "",
isOrg: true,
});
});
return sharedSpacesMap;
-}
+});
export default async function CapsPage(props: PageProps<"/dashboard/caps">) {
const searchParams = await props.searchParams;
@@ -134,7 +144,13 @@ export default async function CapsPage(props: PageProps<"/dashboard/caps">) {
public: videos.public,
totalComments: sql<number>`COUNT(DISTINCT CASE WHEN ${comments.type} = 'text' THEN ${comments.id} END)`,
totalReactions: sql<number>`COUNT(DISTINCT CASE WHEN ${comments.type} = 'emoji' THEN ${comments.id} END)`,
- sharedOrganizations: sql<{ id: string; name: string; iconUrl: string }[]>`
+ sharedOrganizations: sql<
+ {
+ id: string;
+ name: string;
+ iconUrl: ImageUpload.ImageUrlOrKey | null;
+ }[]
+ >`
COALESCE(
JSON_ARRAYAGG(
JSON_OBJECT(
@@ -211,33 +227,47 @@ export default async function CapsPage(props: PageProps<"/dashboard/caps">) {
// Fetch shared spaces data for all videos
const videoIds = videoData.map((video) => video.id);
- const sharedSpacesMap = await getSharedSpacesForVideos(videoIds);
-
- const processedVideoData = videoData.map((video) => {
- const { effectiveDate, ...videoWithoutEffectiveDate } = video;
-
- return {
- ...videoWithoutEffectiveDate,
- id: Video.VideoId.make(video.id),
- foldersData,
- settings: video.settings,
- sharedOrganizations: Array.isArray(video.sharedOrganizations)
- ? video.sharedOrganizations.filter(
- (organization) => organization.id !== null,
- )
- : [],
- sharedSpaces: Array.isArray(sharedSpacesMap[video.id])
- ? sharedSpacesMap[video.id]
- : [],
- ownerName: video.ownerName ?? "",
- metadata: video.metadata as
- | {
- customCreatedAt?: string;
- [key: string]: any;
- }
- | undefined,
- };
- });
+ const sharedSpacesMap =
+ await getSharedSpacesForVideos(videoIds).pipe(runPromise);
+
+ const processedVideoData = await Effect.all(
+ videoData.map(
+ Effect.fn(function* (video) {
+ const imageUploads = yield* ImageUploads;
+
+ const { effectiveDate, ...videoWithoutEffectiveDate } = video;
+
+ return {
+ ...videoWithoutEffectiveDate,
+ id: Video.VideoId.make(video.id),
+ foldersData,
+ settings: video.settings,
+ sharedOrganizations: yield* Effect.all(
+ (video.sharedOrganizations ?? [])
+ .filter((organization) => organization.id !== null)
+ .map(
+ Effect.fn(function* (org) {
+ return {
+ ...org,
+ iconUrl: org.iconUrl
+ ? yield* imageUploads.resolveImageUrl(org.iconUrl)
+ : null,
+ };
+ }),
+ ),
+ ),
+ sharedSpaces: sharedSpacesMap[video.id] ?? [],
+ ownerName: video.ownerName ?? "",
+ metadata: video.metadata as
+ | {
+ customCreatedAt?: string;
+ [key: string]: any;
+ }
+ | undefined,
+ };
+ }),
+ ),
+ ).pipe(runPromise);
return (
<Caps
diff --git a/apps/web/app/(org)/dashboard/dashboard-data.ts b/apps/web/app/(org)/dashboard/dashboard-data.ts
index 0bebb01e3..5574dc73f 100644
--- a/apps/web/app/(org)/dashboard/dashboard-data.ts
+++ b/apps/web/app/(org)/dashboard/dashboard-data.ts
@@ -11,15 +11,21 @@ import {
users,
videos,
} from "@cap/database/schema";
+import { Database, ImageUploads } from "@cap/web-backend";
+import type { ImageUpload } from "@cap/web-domain";
import { and, count, eq, inArray, isNull, or, sql } from "drizzle-orm";
+import { Effect } from "effect";
+import { runPromise } from "@/lib/server";
export type Organization = {
- organization: typeof organizations.$inferSelect;
+ organization: Omit<typeof organizations.$inferSelect, "iconUrl"> & {
+ iconUrl: ImageUpload.ImageUrl | null;
+ };
members: (typeof organizationMembers.$inferSelect & {
user: Pick<
typeof users.$inferSelect,
- "id" | "name" | "email" | "lastName" | "image"
- >;
+ "id" | "name" | "email" | "lastName"
+ > & { image?: ImageUpload.ImageUrl | null };
})[];
invites: (typeof organizationInvites.$inferSelect)[];
inviteQuota: number;
@@ -32,10 +38,11 @@ export type OrganizationSettings = NonNullable<
export type Spaces = Omit<
typeof spaces.$inferSelect,
- "createdAt" | "updatedAt"
+ "createdAt" | "updatedAt" | "iconUrl"
> & {
memberCount: number;
videoCount: number;
+ iconUrl: ImageUpload.ImageUrl | null;
};
export type UserPreferences = (typeof users.$inferSelect)["preferences"];
@@ -121,40 +128,63 @@ export async function getDashboardData(user: typeof userSelectProps) {
.where(eq(organizations.id, activeOrganizationId));
organizationSettings = organizationSetting?.settings || null;
- spacesData = await db()
- .selectDistinct({
- id: spaces.id,
- primary: spaces.primary,
- privacy: spaces.privacy,
- name: spaces.name,
- description: spaces.description,
- organizationId: spaces.organizationId,
- createdById: spaces.createdById,
- iconUrl: spaces.iconUrl,
- memberImage: users.image,
- memberCount: sql<number>`(
+ spacesData = await Effect.gen(function* () {
+ const db = yield* Database;
+ const imageUploads = yield* ImageUploads;
+
+ return yield* db
+ .use((db) =>
+ db
+ .selectDistinct({
+ id: spaces.id,
+ primary: spaces.primary,
+ privacy: spaces.privacy,
+ name: spaces.name,
+ description: spaces.description,
+ organizationId: spaces.organizationId,
+ createdById: spaces.createdById,
+ iconUrl: spaces.iconUrl,
+ memberImage: users.image,
+ memberCount: sql<number>`(
SELECT COUNT(*) FROM space_members WHERE space_members.spaceId = spaces.id
)`,
- videoCount: sql<number>`(
+ videoCount: sql<number>`(
SELECT COUNT(*) FROM space_videos WHERE space_videos.spaceId = spaces.id
)`,
- })
- .from(spaces)
- .leftJoin(spaceMembers, eq(spaces.id, spaceMembers.spaceId))
- .leftJoin(users, eq(spaceMembers.userId, users.id))
- .where(
- and(
- eq(spaces.organizationId, activeOrganizationId),
- or(
- // User is the space creator
- eq(spaces.createdById, user.id),
- // User is a member of the space
- eq(spaceMembers.userId, user.id),
- // Space is public within the organization
- eq(spaces.privacy, "Public"),
+ })
+ .from(spaces)
+ .leftJoin(spaceMembers, eq(spaces.id, spaceMembers.spaceId))
+ .leftJoin(users, eq(spaceMembers.userId, users.id))
+ .where(
+ and(
+ eq(spaces.organizationId, activeOrganizationId),
+ or(
+ // User is the space creator
+ eq(spaces.createdById, user.id),
+ // User is a member of the space
+ eq(spaceMembers.userId, user.id),
+ // Space is public within the organization
+ eq(spaces.privacy, "Public"),
+ ),
+ ),
+ ),
+ )
+ .pipe(
+ Effect.map((rows) =>
+ rows.map(
+ Effect.fn(function* (row) {
+ return {
+ ...row,
+ iconUrl: row.iconUrl
+ ? yield* imageUploads.resolveImageUrl(row.iconUrl)
+ : null,
+ };
+ }),
+ ),
),
- ),
- );
+ Effect.flatMap(Effect.all),
+ );
+ }).pipe(runPromise);
// Add a single 'All spaces' entry for the active organization
const activeOrgInfo = organizationsWithMembers.find(
@@ -198,18 +228,27 @@ export async function getDashboardData(user: typeof userSelectProps) {
userCapsCount = userCapsCountResult[0]?.value || 0;
- const allSpacesEntry = {
- id: activeOrgInfo.organization.id,
- primary: true,
- privacy: "Public",
- name: `All ${activeOrgInfo.organization.name}`,
- description: `View all content in ${activeOrgInfo.organization.name}`,
- organizationId: activeOrgInfo.organization.id,
- iconUrl: activeOrgInfo.organization.iconUrl,
- memberCount: orgMemberCount,
- createdById: activeOrgInfo.organization.ownerId,
- videoCount: orgVideoCount,
- } as const;
+ const allSpacesEntry = await Effect.gen(function* () {
+ const imageUploads = yield* ImageUploads;
+
+ const iconUrl = activeOrgInfo.organization.iconUrl;
+
+ return {
+ id: activeOrgInfo.organization.id,
+ primary: true,
+ privacy: "Public",
+ name: `All ${activeOrgInfo.organization.name}`,
+ description: `View all content in ${activeOrgInfo.organization.name}`,
+ organizationId: activeOrgInfo.organization.id,
+ iconUrl: iconUrl
+ ? yield* imageUploads.resolveImageUrl(iconUrl)
+ : null,
+ memberCount: orgMemberCount,
+ createdById: activeOrgInfo.organization.ownerId,
+ videoCount: orgVideoCount,
+ } as const;
+ }).pipe(runPromise);
+
spacesData = [allSpacesEntry, ...spacesData];
}
}
@@ -222,7 +261,7 @@ export async function getDashboardData(user: typeof userSelectProps) {
.where(eq(users.id, user.id))
.limit(1);
- const organizationSelect: Organization[] = await Promise.all(
+ const organizationSelect: Organization[] = await Effect.all(
organizationsWithMembers
.reduce((acc: (typeof organizations.$inferSelect)[], row) => {
const existingOrganization = acc.find(
@@ -233,62 +272,94 @@ export async function getDashboardData(user: typeof userSelectProps) {
}
return acc;
}, [])
- .map(async (organization) => {
- const allMembers = await db()
- .select({
- member: organizationMembers,
- user: {
- id: users.id,
- name: users.name,
- lastName: users.lastName,
- email: users.email,
- image: users.image,
- },
- })
- .from(organizationMembers)
- .leftJoin(users, eq(organizationMembers.userId, users.id))
- .where(eq(organizationMembers.organizationId, organization.id));
-
- const owner = await db()
- .select({
- inviteQuota: users.inviteQuota,
- })
- .from(users)
- .where(eq(users.id, organization.ownerId))
- .then((result) => result[0]);
-
- const totalInvitesResult = await db()
- .select({
- value: sql<number>`
+ .map(
+ Effect.fn(function* (organization) {
+ const db = yield* Database;
+ const iconImages = yield* ImageUploads;
+
+ const allMembers = yield* db.use((db) =>
+ db
+ .select({
+ member: organizationMembers,
+ user: {
+ id: users.id,
+ name: users.name,
+ lastName: users.lastName,
+ email: users.email,
+ image: users.image,
+ },
+ })
+ .from(organizationMembers)
+ .leftJoin(users, eq(organizationMembers.userId, users.id))
+ .where(eq(organizationMembers.organizationId, organization.id)),
+ );
+
+ const owner = yield* db.use((db) =>
+ db
+ .select({
+ inviteQuota: users.inviteQuota,
+ })
+ .from(users)
+ .where(eq(users.id, organization.ownerId))
+ .then((result) => result[0]),
+ );
+
+ const totalInvitesResult = yield* db.use((db) =>
+ db
+ .select({
+ value: sql<number>`
${count(organizationMembers.id)} + ${count(
organizationInvites.id,
)}
`,
- })
- .from(organizations)
- .leftJoin(
- organizationMembers,
- eq(organizations.id, organizationMembers.organizationId),
- )
- .leftJoin(
- organizationInvites,
- eq(organizations.id, organizationInvites.organizationId),
- )
- .where(eq(organizations.ownerId, organization.ownerId));
-
- const totalInvites = totalInvitesResult[0]?.value || 0;
+ })
+ .from(organizations)
+ .leftJoin(
+ organizationMembers,
+ eq(organizations.id, organizationMembers.organizationId),
+ )
+ .leftJoin(
+ organizationInvites,
+ eq(organizations.id, organizationInvites.organizationId),
+ )
+ .where(eq(organizations.ownerId, organization.ownerId)),
+ );
- return {
- organization,
- members: allMembers.map((m) => ({ ...m.member, user: m.user! })),
- invites: organizationInvitesData.filter(
- (invite) => invite.organizationId === organization.id,
- ),
- inviteQuota: owner?.inviteQuota || 1,
- totalInvites,
- };
- }),
- );
+ const totalInvites = totalInvitesResult[0]?.value || 0;
+
+ return {
+ organization: {
+ ...organization,
+ iconUrl: organization.iconUrl
+ ? yield* iconImages.resolveImageUrl(organization.iconUrl)
+ : null,
+ },
+ members: yield* Effect.all(
+ allMembers.map(
+ Effect.fn(function* (m) {
+ const imageUploads = yield* ImageUploads;
+ return {
+ ...m.member,
+ user: {
+ ...m.user!,
+ image: m.user!.image
+ ? yield* imageUploads.resolveImageUrl(m.user!.image)
+ : null,
+ },
+ };
+ }),
+ ),
+ ),
+ invites: organizationInvitesData.filter(
+ (invite) => invite.organizationId === organization.id,
+ ),
+ inviteQuota: owner?.inviteQuota || 1,
+ totalInvites,
+ };
+ }),
+ ),
+ { concurrency: 3 },
+ ).pipe(runPromise);
return {
organizationSelect,
diff --git a/apps/web/app/(org)/dashboard/folder/[id]/components/ClientMyCapsLink.tsx b/apps/web/app/(org)/dashboard/folder/[id]/components/ClientMyCapsLink.tsx
index ca6c2de19..dd8488b89 100644
--- a/apps/web/app/(org)/dashboard/folder/[id]/components/ClientMyCapsLink.tsx
+++ b/apps/web/app/(org)/dashboard/folder/[id]/components/ClientMyCapsLink.tsx
@@ -128,7 +128,6 @@ export function ClientMyCapsLink({
<SignedImageUrl
image={activeSpace.iconUrl}
name={activeSpace.name}
- type="organization"
letterClass="text-xs"
className="relative flex-shrink-0 size-5"
/>
diff --git a/apps/web/app/(org)/dashboard/folder/[id]/components/FolderVideosSection.tsx b/apps/web/app/(org)/dashboard/folder/[id]/components/FolderVideosSection.tsx
index 443591ae4..5b4f40b0e 100644
--- a/apps/web/app/(org)/dashboard/folder/[id]/components/FolderVideosSection.tsx
+++ b/apps/web/app/(org)/dashboard/folder/[id]/components/FolderVideosSection.tsx
@@ -6,10 +6,8 @@ import { useRouter } from "next/navigation";
import { useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";
-import { useEffectMutation } from "@/lib/EffectRuntime";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
import { useVideosAnalyticsQuery } from "@/lib/Queries/Analytics";
-import { AnalyticsRequest } from "@/lib/Requests/AnalyticsRequest";
-import { Rpc, withRpc } from "@/lib/Rpcs";
import type { VideoData } from "../../../caps/Caps";
import { CapCard } from "../../../caps/components/CapCard/CapCard";
import { SelectedCapsBar } from "../../../caps/components/SelectedCapsBar";
@@ -31,12 +29,12 @@ export default function FolderVideosSection({
const [selectedCaps, setSelectedCaps] = useState<Video.VideoId[]>([]);
const previousCountRef = useRef<number>(0);
+ const rpc = useRpcClient();
+
const { mutate: deleteCaps, isPending: isDeletingCaps } = useEffectMutation({
mutationFn: Effect.fn(function* (ids: Video.VideoId[]) {
if (ids.length === 0) return;
- const rpc = yield* Rpc;
-
const fiber = yield* Effect.gen(function* () {
const results = yield* Effect.all(
ids.map((id) => rpc.VideoDelete(id).pipe(Effect.exit)),
@@ -87,7 +85,7 @@ export default function FolderVideosSection({
});
const { mutate: deleteCap, isPending: isDeletingCap } = useEffectMutation({
- mutationFn: (id: Video.VideoId) => withRpc((r) => r.VideoDelete(id)),
+ mutationFn: (id: Video.VideoId) => rpc.VideoDelete(id),
onSuccess: () => {
toast.success("Cap deleted successfully");
router.refresh();
diff --git a/apps/web/app/(org)/dashboard/folder/[id]/components/SubfolderDialog.tsx b/apps/web/app/(org)/dashboard/folder/[id]/components/SubfolderDialog.tsx
index 0c0561d56..3fdc67ba3 100644
--- a/apps/web/app/(org)/dashboard/folder/[id]/components/SubfolderDialog.tsx
+++ b/apps/web/app/(org)/dashboard/folder/[id]/components/SubfolderDialog.tsx
@@ -19,7 +19,7 @@ import { Option } from "effect";
import { useRouter } from "next/navigation";
import React, { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
-import { useEffectMutation } from "@/lib/EffectRuntime";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
import { withRpc } from "@/lib/Rpcs";
import { useDashboardContext } from "../../../Contexts";
import {
@@ -107,16 +107,16 @@ export const SubfolderDialog: React.FC<Props> = ({
),
);
+ const rpc = useRpcClient();
+
const createSubfolder = useEffectMutation({
mutationFn: (data: { name: string; color: Folder.FolderColor }) =>
- withRpc((r) =>
- r.FolderCreate({
- name: data.name,
- color: data.color,
- spaceId: Option.fromNullable(activeSpace?.id),
- parentId: Option.some(parentFolderId),
- }),
- ),
+ rpc.FolderCreate({
+ name: data.name,
+ color: data.color,
+ spaceId: Option.fromNullable(activeSpace?.id),
+ parentId: Option.some(parentFolderId),
+ }),
onSuccess: () => {
setFolderName("");
setSelectedColor(null);
diff --git a/apps/web/app/(org)/dashboard/folder/[id]/page.tsx b/apps/web/app/(org)/dashboard/folder/[id]/page.tsx
index 139af910f..d6a001f31 100644
--- a/apps/web/app/(org)/dashboard/folder/[id]/page.tsx
+++ b/apps/web/app/(org)/dashboard/folder/[id]/page.tsx
@@ -1,6 +1,7 @@
import { getCurrentUser } from "@cap/database/auth/session";
import { serverEnv } from "@cap/env";
-import { CurrentUser, Folder } from "@cap/web-domain";
+import { makeCurrentUserLayer } from "@cap/web-backend";
+import { Folder } from "@cap/web-domain";
import { Effect } from "effect";
import { notFound } from "next/navigation";
import {
@@ -9,6 +10,7 @@ import {
getVideosByFolderId,
} from "@/lib/folder";
import { runPromise } from "@/lib/server";
+
import { UploadCapButton } from "../../caps/components";
import FolderCard from "../../caps/components/Folder";
import {
@@ -86,7 +88,7 @@ const FolderPage = async (props: PageProps<"/dashboard/folder/[id]">) => {
/>
</div>
);
- }).pipe(Effect.provideService(CurrentUser, user), runPromise);
+ }).pipe(Effect.provide(makeCurrentUserLayer(user)), runPromise);
};
export default FolderPage;
diff --git a/apps/web/app/(org)/dashboard/layout.tsx b/apps/web/app/(org)/dashboard/layout.tsx
index 74d611c36..18be46405 100644
--- a/apps/web/app/(org)/dashboard/layout.tsx
+++ b/apps/web/app/(org)/dashboard/layout.tsx
@@ -24,9 +24,7 @@ export default async function DashboardLayout({
}) {
const user = await getCurrentUser();
- if (!user || !user.id) {
- redirect("/login");
- }
+ if (!user) redirect("/login");
if (!user.name || user.name.length === 0) {
redirect("/onboarding/welcome");
@@ -82,7 +80,6 @@ export default async function DashboardLayout({
organizationData={organizationSelect}
activeOrganization={activeOrganization || null}
spacesData={spacesData}
- user={user}
isSubscribed={isSubscribed}
initialTheme={theme as "light" | "dark"}
initialSidebarCollapsed={sidebar === "true"}
diff --git a/apps/web/app/(org)/dashboard/settings/account/Settings.tsx b/apps/web/app/(org)/dashboard/settings/account/Settings.tsx
index 96d61bc11..e9df809f1 100644
--- a/apps/web/app/(org)/dashboard/settings/account/Settings.tsx
+++ b/apps/web/app/(org)/dashboard/settings/account/Settings.tsx
@@ -9,26 +9,22 @@ import {
Input,
Select,
} from "@cap/ui";
-import { Organisation } from "@cap/web-domain";
+import { type ImageUpload, Organisation } from "@cap/web-domain";
import { useMutation } from "@tanstack/react-query";
-import { Effect } from "effect";
+import { Effect, Option } from "effect";
import { useRouter } from "next/navigation";
import { useEffect, useId, useState } from "react";
import { toast } from "sonner";
import { SignedImageUrl } from "@/components/SignedImageUrl";
-import { useEffectMutation } from "@/lib/EffectRuntime";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
import { withRpc } from "@/lib/Rpcs";
import { useDashboardContext } from "../../Contexts";
import { ProfileImage } from "./components/ProfileImage";
import { patchAccountSettings } from "./server";
-export const Settings = ({
- user,
-}: {
- user?: typeof users.$inferSelect | null;
-}) => {
+export const Settings = () => {
const router = useRouter();
- const { organizationData } = useDashboardContext();
+ const { organizationData, user } = useDashboardContext();
const [firstName, setFirstName] = useState(user?.name || "");
const [lastName, setLastName] = useState(user?.lastName || "");
const [defaultOrgId, setDefaultOrgId] = useState<
@@ -37,9 +33,9 @@ export const Settings = ({
const firstNameId = useId();
const lastNameId = useId();
const contactEmailId = useId();
- const initialProfileImage = user?.image ?? null;
+ const initialProfileImage = user?.imageUrl ?? null;
const [profileImageOverride, setProfileImageOverride] = useState<
- string | null | undefined
+ ImageUpload.ImageUrl | null | undefined
>(undefined);
const profileImagePreviewUrl =
profileImageOverride !== undefined
@@ -91,81 +87,50 @@ export const Settings = ({
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, [hasChanges]);
- const uploadProfileImageMutation = useEffectMutation({
- mutationFn: (file: File) => {
- if (!user?.id) {
- return Effect.fail(new Error("User ID is required"));
- }
+ const rpc = useRpcClient();
- return Effect.promise(() => file.arrayBuffer()).pipe(
- Effect.map((arrayBuffer) => new Uint8Array(arrayBuffer)),
- Effect.flatMap((data) =>
- withRpc((rpc) =>
- rpc.UploadImage({
- data,
- contentType: file.type,
- fileName: file.name,
- type: "user" as const,
- entityId: user.id,
- oldImageKey: user.image,
- }),
- ),
- ),
- Effect.tap(() =>
- Effect.sync(() => {
- setProfileImageOverride(undefined);
- toast.success("Profile image updated successfully");
- router.refresh();
- }),
- ),
- Effect.catchAll((error) =>
- Effect.sync(() => {
- console.error("Error uploading profile image:", error);
- setProfileImageOverride(undefined);
- toast.error(
- error instanceof Error
- ? error.message
- : "Failed to upload profile image",
- );
- throw error;
- }),
- ),
+ const uploadProfileImageMutation = useEffectMutation({
+ mutationFn: Effect.fn(function* (file: File) {
+ const arrayBuffer = yield* Effect.promise(() => file.arrayBuffer());
+ yield* rpc.UserUpdate({
+ id: user.id,
+ image: Option.some({
+ data: new Uint8Array(arrayBuffer),
+ contentType: file.type,
+ fileName: file.name,
+ }),
+ });
+ }),
+ onSuccess: () => {
+ setProfileImageOverride(undefined);
+ toast.success("Profile image updated successfully");
+ router.refresh();
+ },
+ onError: (error) => {
+ console.error("Error uploading profile image:", error);
+ setProfileImageOverride(undefined);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to upload profile image",
);
},
});
const removeProfileImageMutation = useEffectMutation({
- mutationFn: () => {
- if (!user?.id) {
- return Effect.fail(new Error("User ID is required"));
- }
-
- return withRpc((rpc) =>
- rpc.RemoveImage({
- imageKey: user.image || "",
- type: "user" as const,
- entityId: user.id,
- }),
- ).pipe(
- Effect.tap(() =>
- Effect.sync(() => {
- setProfileImageOverride(null);
- toast.success("Profile image removed");
- router.refresh();
- }),
- ),
- Effect.catchAll((error) =>
- Effect.sync(() => {
- console.error("Error removing profile image:", error);
- setProfileImageOverride(initialProfileImage);
- toast.error(
- error instanceof Error
- ? error.message
- : "Failed to remove profile image",
- );
- throw error;
- }),
- ),
+ mutationFn: () => rpc.UserUpdate({ id: user.id, image: Option.none() }),
+ onSuccess: () => {
+ setProfileImageOverride(null);
+ toast.success("Profile image removed");
+ router.refresh();
+ },
+ onError: (error) => {
+ console.error("Error removing profile image:", error);
+ setProfileImageOverride(initialProfileImage);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to remove profile image",
);
},
});
@@ -285,7 +250,6 @@ export const Settings = ({
className="size-5"
image={org.organization.iconUrl}
name={org.organization.name}
- type="organization"
/>
),
}))}
diff --git a/apps/web/app/(org)/dashboard/settings/account/components/ProfileImage.tsx b/apps/web/app/(org)/dashboard/settings/account/components/ProfileImage.tsx
index d494ab89a..360c0d29a 100644
--- a/apps/web/app/(org)/dashboard/settings/account/components/ProfileImage.tsx
+++ b/apps/web/app/(org)/dashboard/settings/account/components/ProfileImage.tsx
@@ -1,6 +1,7 @@
"use client";
import { Button } from "@cap/ui";
+import { ImageUpload } from "@cap/web-domain";
import { faImage, faTrash } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
@@ -10,7 +11,7 @@ import { SignedImageUrl } from "@/components/SignedImageUrl";
import { Tooltip } from "@/components/Tooltip";
interface ProfileImageProps {
- initialPreviewUrl?: string | null;
+ initialPreviewUrl?: ImageUpload.ImageUrl | null;
onChange?: (file: File | null) => void;
onRemove?: () => void;
disabled?: boolean;
@@ -28,7 +29,7 @@ export function ProfileImage({
isRemoving = false,
userName,
}: ProfileImageProps) {
- const [previewUrl, setPreviewUrl] = useState<string | null>(
+ const [previewUrl, setPreviewUrl] = useState<ImageUpload.ImageUrl | null>(
initialPreviewUrl || null,
);
const [isLocalPreview, setIsLocalPreview] = useState(false);
@@ -54,7 +55,7 @@ export function ProfileImage({
URL.revokeObjectURL(previewUrl);
}
const objectUrl = URL.createObjectURL(file);
- setPreviewUrl(objectUrl);
+ setPreviewUrl(ImageUpload.ImageUrl.make(objectUrl));
setIsLocalPreview(true);
onChange?.(file);
};
@@ -92,7 +93,6 @@ export function ProfileImage({
<SignedImageUrl
image={previewUrl}
name={userName || "User"}
- type="user"
letterClass="text-lg"
className="size-full"
/>
diff --git a/apps/web/app/(org)/dashboard/settings/account/page.tsx b/apps/web/app/(org)/dashboard/settings/account/page.tsx
index daed483fd..1408e3b9d 100644
--- a/apps/web/app/(org)/dashboard/settings/account/page.tsx
+++ b/apps/web/app/(org)/dashboard/settings/account/page.tsx
@@ -1,4 +1,3 @@
-import { getCurrentUser } from "@cap/database/auth/session";
import type { Metadata } from "next";
import { Settings } from "./Settings";
@@ -7,7 +6,5 @@ export const metadata: Metadata = {
};
export default async function SettingsPage() {
- const user = await getCurrentUser();
-
- return <Settings user={user} />;
+ return <Settings />;
}
diff --git a/apps/web/app/(org)/dashboard/settings/organization/components/CapSettingsCard.tsx b/apps/web/app/(org)/dashboard/settings/organization/components/CapSettingsCard.tsx
index ff94679ec..edb941065 100644
--- a/apps/web/app/(org)/dashboard/settings/organization/components/CapSettingsCard.tsx
+++ b/apps/web/app/(org)/dashboard/settings/organization/components/CapSettingsCard.tsx
@@ -63,8 +63,6 @@ const CapSettingsCard = () => {
organizationSettings || settings,
);
- const isUserPro = userIsPro(user);
-
const debouncedUpdateSettings = useDebounce(settings, 1000);
useEffect(() => {
@@ -179,7 +177,7 @@ const CapSettingsCard = () => {
</div>
<Switch
disabled={
- (option.pro && !isUserPro) ||
+ (option.pro && !user.isPro) ||
((option.value === "disableSummary" ||
option.value === "disableChapters") &&
settings?.disableTranscript)
diff --git a/apps/web/app/(org)/dashboard/settings/organization/components/OrganizationIcon.tsx b/apps/web/app/(org)/dashboard/settings/organization/components/OrganizationIcon.tsx
index 32f7947ee..98dc6500e 100644
--- a/apps/web/app/(org)/dashboard/settings/organization/components/OrganizationIcon.tsx
+++ b/apps/web/app/(org)/dashboard/settings/organization/components/OrganizationIcon.tsx
@@ -1,12 +1,13 @@
"use client";
import { CardDescription, Label } from "@cap/ui";
-import { Effect } from "effect";
+import type { Organisation } from "@cap/web-domain";
+import { Effect, Option } from "effect";
import { useRouter } from "next/navigation";
-import { useId, useState } from "react";
+import { useId } from "react";
import { toast } from "sonner";
import { FileInput } from "@/components/FileInput";
-import * as EffectRuntime from "@/lib/EffectRuntime";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
import { withRpc } from "@/lib/Rpcs";
import { useDashboardContext } from "../../../Contexts";
@@ -17,74 +18,55 @@ export const OrganizationIcon = () => {
const organizationId = activeOrganization?.organization.id;
const existingIconUrl = activeOrganization?.organization.iconUrl ?? null;
- const [isUploading, setIsUploading] = useState(false);
+ const rpc = useRpcClient();
- const handleFileChange = async (file: File | null) => {
- // If file is null, it means the user removed the file
- if (!file || !organizationId) return;
+ const uploadIcon = useEffectMutation({
+ mutationFn: Effect.fn(function* ({
+ file,
+ organizationId,
+ }: {
+ organizationId: Organisation.OrganisationId;
+ file: File;
+ }) {
+ const arrayBuffer = yield* Effect.promise(() => file.arrayBuffer());
- // Upload the file to the server immediately
- try {
- setIsUploading(true);
-
- const arrayBuffer = await file.arrayBuffer();
- const data = new Uint8Array(arrayBuffer);
-
- await EffectRuntime.EffectRuntime.runPromise(
- withRpc((rpc) =>
- rpc.UploadImage({
- data,
- contentType: file.type,
- fileName: file.name,
- type: "organization" as const,
- entityId: organizationId,
- oldImageKey: existingIconUrl,
- }),
- ).pipe(
- Effect.tap(() =>
- Effect.sync(() => {
- toast.success("Organization icon updated successfully");
- router.refresh();
- }),
- ),
- ),
- );
- } catch (error) {
+ yield* rpc.OrganisationUpdate({
+ id: organizationId,
+ image: Option.some({
+ contentType: file.type,
+ fileName: file.name,
+ data: new Uint8Array(arrayBuffer),
+ }),
+ });
+ }),
+ onSuccess: () => {
+ toast.success("Organization icon updated successfully");
+ router.refresh();
+ },
+ onError: (error) => {
toast.error(
error instanceof Error ? error.message : "Failed to upload icon",
);
- } finally {
- setIsUploading(false);
- }
- };
+ },
+ });
- const handleRemoveIcon = async () => {
- if (!organizationId) return;
-
- try {
- await EffectRuntime.EffectRuntime.runPromise(
- withRpc((rpc) =>
- rpc.RemoveImage({
- imageKey: existingIconUrl || "",
- type: "organization" as const,
- entityId: organizationId,
- }),
- ).pipe(
- Effect.tap(() =>
- Effect.sync(() => {
- toast.success("Organization icon removed successfully");
- router.refresh();
- }),
- ),
- ),
- );
- } catch (error) {
+ const removeIcon = useEffectMutation({
+ mutationFn: (organizationId: Organisation.OrganisationId) =>
+ rpc.OrganisationUpdate({
+ id: organizationId,
+ image: Option.none(),
+ }),
+ onSuccess: () => {
+ toast.success("Organization icon removed successfully");
+ router.refresh();
+ },
+ onError: (error) => {
console.error("Error removing organization icon:", error);
toast.error(
error instanceof Error ? error.message : "Failed to remove icon",
);
- }
- };
+ },
+ });
return (
<div className="flex-1 space-y-4">
@@ -99,12 +81,17 @@ export const OrganizationIcon = () => {
previewIconSize={20}
id={iconInputId}
name="icon"
- type="organization"
- onChange={handleFileChange}
- disabled={isUploading}
- isLoading={isUploading}
+ onChange={(file) => {
+ if (!file || !organizationId) return;
+ uploadIcon.mutate({ organizationId, file });
+ }}
+ disabled={uploadIcon.isPending}
+ isLoading={uploadIcon.isPending}
initialPreviewUrl={existingIconUrl}
- onRemove={handleRemoveIcon}
+ onRemove={() => {
+ if (!organizationId) return;
+ removeIcon.mutate(organizationId);
+ }}
maxFileSizeBytes={1 * 1024 * 1024} // 1MB
/>
</div>
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MemberSelect.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MemberSelect.tsx
index 0f372b7c3..4d83760b8 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MemberSelect.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MemberSelect.tsx
@@ -7,6 +7,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@cap/ui";
+import type { ImageUpload } from "@cap/web-domain";
import { faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
@@ -20,7 +21,7 @@ type UserObject = {
id: string;
email: string;
name: string | null;
- image: string | null;
+ image: ImageUpload.ImageUrl | null;
};
type OrganizationMember = {
@@ -31,7 +32,7 @@ type OrganizationMember = {
export interface TagOption {
value: string;
label: string;
- image?: string;
+ image?: ImageUpload.ImageUrl;
}
interface MemberSelectProps {
@@ -198,7 +199,6 @@ export const MemberSelect = forwardRef<HTMLDivElement, MemberSelectProps>(
<SignedImageUrl
name={opt.label}
image={opt.image}
- type="user"
className="w-5 h-5"
letterClass="text-[11px]"
/>
@@ -222,7 +222,6 @@ export const MemberSelect = forwardRef<HTMLDivElement, MemberSelectProps>(
<SignedImageUrl
name={tag.label}
image={tag.image}
- type="user"
className="w-5 h-5"
letterClass="text-[11px]"
/>
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersDialog.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersDialog.tsx
index c6bec9528..7f37a995e 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersDialog.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersDialog.tsx
@@ -1,4 +1,6 @@
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@cap/ui";
+import type { ImageUpload } from "@cap/web-domain";
+import { ImageUpdatePayload } from "@cap/web-domain/src/ImageUpload";
import { SignedImageUrl } from "@/components/SignedImageUrl";
interface OrganizationMember {
@@ -14,7 +16,7 @@ interface OrganizationMember {
email: string;
firstName?: string | null;
lastName?: string | null;
- memberImage?: string | null;
+ memberImage?: ImageUpload.ImageUrl | null;
};
}
@@ -45,7 +47,6 @@ export const MembersDialog = ({
<SignedImageUrl
image={member.user?.memberImage || undefined}
name={member.user?.name || "User"}
- type="user"
className="mr-3 size-8"
letterClass="text-md"
/>
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersIndicator.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersIndicator.tsx
index 885d7c7c0..7aeb2af63 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersIndicator.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersIndicator.tsx
@@ -168,7 +168,6 @@ export const MembersIndicator = ({
<SignedImageUrl
name={member.name || member.email}
image={member.image || undefined}
- type="user"
className="size-8"
letterClass="text-sm"
/>
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/OrganizationIndicator.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/OrganizationIndicator.tsx
index 33d57ce70..729d96a13 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/OrganizationIndicator.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/OrganizationIndicator.tsx
@@ -9,6 +9,7 @@ import {
DialogTitle,
DialogTrigger,
} from "@cap/ui";
+import type { ImageUpload } from "@cap/web-domain";
import { faBuilding, faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
@@ -20,7 +21,7 @@ export type OrganizationMemberData = {
id: string;
userId: string;
role: string;
- image?: string | null;
+ image?: ImageUpload.ImageUrl | null;
name: string | null;
email: string;
};
@@ -73,9 +74,8 @@ export const OrganizationIndicator = ({
className="flex gap-3 items-center px-3 py-2 rounded-lg border transition-colors bg-gray-3 border-gray-4"
>
<SignedImageUrl
- image={member.image || undefined}
+ image={member.image}
name={member.name || member.email}
- type="user"
className="size-8"
letterClass="text-sm"
/>
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/folder/[folderId]/page.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/folder/[folderId]/page.tsx
index 655f78b9d..c530083cf 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/folder/[folderId]/page.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/folder/[folderId]/page.tsx
@@ -1,7 +1,7 @@
import { getCurrentUser } from "@cap/database/auth/session";
import { serverEnv } from "@cap/env";
-import { Spaces } from "@cap/web-backend";
-import { CurrentUser, type Folder, Space } from "@cap/web-domain";
+import { makeCurrentUserLayer, Spaces } from "@cap/web-backend";
+import { type Folder, Space } from "@cap/web-domain";
import { Effect } from "effect";
import { notFound } from "next/navigation";
import FolderCard from "@/app/(org)/dashboard/caps/components/Folder";
@@ -109,7 +109,7 @@ const FolderPage = async (props: {
);
}).pipe(
Effect.catchTag("PolicyDenied", () => Effect.sync(() => notFound())),
- Effect.provideService(CurrentUser, user),
+ Effect.provide(makeCurrentUserLayer(user)),
runPromise,
);
};
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/page.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/page.tsx
index 750d52706..f90bd8650 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/page.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/page.tsx
@@ -12,8 +12,18 @@ import {
videoUploads,
} from "@cap/database/schema";
import { serverEnv } from "@cap/env";
-import { Spaces } from "@cap/web-backend";
-import { CurrentUser, type Organisation, Space, Video } from "@cap/web-domain";
+import {
+ Database,
+ ImageUploads,
+ makeCurrentUserLayer,
+ Spaces,
+} from "@cap/web-backend";
+import {
+ type ImageUpload,
+ type Organisation,
+ Space,
+ Video,
+} from "@cap/web-domain";
import { and, count, desc, eq, isNull, sql } from "drizzle-orm";
import { Effect } from "effect";
import type { Metadata } from "next";
@@ -29,7 +39,7 @@ export type SpaceMemberData = {
id: string;
userId: string;
role: string;
- image?: string | null;
+ image?: ImageUpload.ImageUrl | null;
name: string | null;
email: string;
};
@@ -55,35 +65,81 @@ async function fetchFolders(
.where(and(eq(folders.spaceId, spaceId), isNull(folders.parentId)));
}
-async function fetchSpaceMembers(spaceId: Space.SpaceIdOrOrganisationId) {
- return db()
- .select({
- id: spaceMembers.id,
- userId: spaceMembers.userId,
- role: sql<string>`'member'`,
- name: users.name,
- email: users.email,
- image: users.image,
- })
- .from(spaceMembers)
- .innerJoin(users, eq(spaceMembers.userId, users.id))
- .where(eq(spaceMembers.spaceId, spaceId));
-}
+const fetchSpaceMembers = Effect.fn(function* (
+ spaceId: Space.SpaceIdOrOrganisationId,
+) {
+ const db = yield* Database;
+ const imageUploads = yield* ImageUploads;
-async function fetchOrganizationMembers(orgId: Organisation.OrganisationId) {
- return db()
- .select({
- id: organizationMembers.id,
- userId: organizationMembers.userId,
- role: organizationMembers.role,
- name: users.name,
- email: users.email,
- image: users.image,
- })
- .from(organizationMembers)
- .innerJoin(users, eq(organizationMembers.userId, users.id))
- .where(eq(organizationMembers.organizationId, orgId));
-}
+ return yield* db
+ .use((db) =>
+ db
+ .select({
+ id: spaceMembers.id,
+ userId: spaceMembers.userId,
+ role: sql<string>`'member'`,
+ name: users.name,
+ email: users.email,
+ image: users.image,
+ })
+ .from(spaceMembers)
+ .innerJoin(users, eq(spaceMembers.userId, users.id))
+ .where(eq(spaceMembers.spaceId, spaceId)),
+ )
+ .pipe(
+ Effect.map((v) =>
+ v.map(
+ Effect.fn(function* (v) {
+ return {
+ ...v,
+ image: v.image
+ ? yield* imageUploads.resolveImageUrl(v.image)
+ : null,
+ };
+ }),
+ ),
+ ),
+ Effect.flatMap(Effect.all),
+ );
+});
+
+const fetchOrganizationMembers = Effect.fn(function* (
+ orgId: Organisation.OrganisationId,
+) {
+ const db = yield* Database;
+ const imageUploads = yield* ImageUploads;
+
+ return yield* db
+ .use((db) =>
+ db
+ .select({
+ id: organizationMembers.id,
+ userId: organizationMembers.userId,
+ role: organizationMembers.role,
+ name: users.name,
+ email: users.email,
+ image: users.image,
+ })
+ .from(organizationMembers)
+ .innerJoin(users, eq(organizationMembers.userId, users.id))
+ .where(eq(organizationMembers.organizationId, orgId)),
+ )
+ .pipe(
+ Effect.map((v) =>
+ v.map(
+ Effect.fn(function* (v) {
+ return {
+ ...v,
+ image: v.image
+ ? yield* imageUploads.resolveImageUrl(v.image)
+ : null,
+ };
+ }),
+ ),
+ ),
+ Effect.flatMap(Effect.all),
+ );
+});
export default async function SharedCapsPage(props: {
params: Promise<{ spaceId: string }>;
@@ -100,7 +156,7 @@ export default async function SharedCapsPage(props: {
s.getSpaceOrOrg(Space.SpaceId.make(params.spaceId)),
).pipe(
Effect.catchTag("PolicyDenied", () => Effect.sync(() => notFound())),
- Effect.provideService(CurrentUser, user),
+ Effect.provide(makeCurrentUserLayer(user)),
runPromise,
);
@@ -112,8 +168,8 @@ export default async function SharedCapsPage(props: {
// Fetch members in parallel
const [spaceMembersData, organizationMembersData, foldersData] =
await Promise.all([
- fetchSpaceMembers(space.id),
- fetchOrganizationMembers(space.organizationId),
+ fetchSpaceMembers(space.id).pipe(runPromise),
+ fetchOrganizationMembers(space.organizationId).pipe(runPromise),
fetchFolders(space.id, false),
]);
@@ -284,7 +340,7 @@ export default async function SharedCapsPage(props: {
const [organizationVideos, organizationMembersData, foldersData] =
await Promise.all([
fetchOrganizationVideos(organization.id, page, limit),
- fetchOrganizationMembers(organization.id),
+ fetchOrganizationMembers(organization.id).pipe(runPromise),
fetchFolders(organization.id, true),
]);
diff --git a/apps/web/app/(org)/dashboard/spaces/browse/page.tsx b/apps/web/app/(org)/dashboard/spaces/browse/page.tsx
index b34d20368..d4ed2ca05 100644
--- a/apps/web/app/(org)/dashboard/spaces/browse/page.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/browse/page.tsx
@@ -135,7 +135,6 @@ export default function BrowseSpacesPage() {
<SignedImageUrl
image={space.iconUrl}
name={space.name}
- type="organization"
className="relative flex-shrink-0 size-7"
letterClass="text-sm"
/>
diff --git a/apps/web/app/(org)/onboarding/components/Bottom.tsx b/apps/web/app/(org)/onboarding/components/Bottom.tsx
index c1a1eb5ed..6e3070cb8 100644
--- a/apps/web/app/(org)/onboarding/components/Bottom.tsx
+++ b/apps/web/app/(org)/onboarding/components/Bottom.tsx
@@ -5,20 +5,19 @@ import { useRouter } from "next/navigation";
import { signOut } from "next-auth/react";
import { startTransition } from "react";
import { toast } from "sonner";
-import { useEffectMutation } from "@/lib/EffectRuntime";
-import { withRpc } from "@/lib/Rpcs";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
export const Bottom = () => {
const router = useRouter();
+ const rpc = useRpcClient();
+
const skipToDashboard = useEffectMutation({
mutationFn: () =>
- withRpc((r) =>
- r.UserCompleteOnboardingStep({
- step: "skipToDashboard",
- data: undefined,
- }),
- ),
+ rpc.UserCompleteOnboardingStep({
+ step: "skipToDashboard",
+ data: undefined,
+ }),
onSuccess: () => {
startTransition(() => {
router.push("/dashboard/caps");
diff --git a/apps/web/app/(org)/onboarding/components/CustomDomainPage.tsx b/apps/web/app/(org)/onboarding/components/CustomDomainPage.tsx
index 8f7ec09d9..2572ba8d4 100644
--- a/apps/web/app/(org)/onboarding/components/CustomDomainPage.tsx
+++ b/apps/web/app/(org)/onboarding/components/CustomDomainPage.tsx
@@ -6,26 +6,21 @@ import { useRouter } from "next/navigation";
import { startTransition, useState } from "react";
import { toast } from "sonner";
import { UpgradeModal } from "@/components/UpgradeModal";
-import { useEffectMutation } from "@/lib/EffectRuntime";
-import { withRpc } from "@/lib/Rpcs";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
import { Base } from "./Base";
export function CustomDomainPage() {
const router = useRouter();
+ const rpc = useRpcClient();
const [showUpgradeModal, setShowUpgradeModal] = useState(false);
const customDomainMutation = useEffectMutation({
- mutationFn: (redirect: boolean) =>
- Effect.gen(function* () {
- yield* withRpc((r) =>
- r.UserCompleteOnboardingStep({
- step: "customDomain",
- data: undefined,
- }),
- );
- return redirect;
+ mutationFn: (_redirect: boolean) =>
+ rpc.UserCompleteOnboardingStep({
+ step: "customDomain",
+ data: undefined,
}),
- onSuccess: (redirect: boolean) => {
+ onSuccess: (_, redirect) => {
startTransition(() => {
if (redirect) {
router.push("/onboarding/invite-team");
diff --git a/apps/web/app/(org)/onboarding/components/InviteTeamPage.tsx b/apps/web/app/(org)/onboarding/components/InviteTeamPage.tsx
index 6a3e8cbd9..326b1673a 100644
--- a/apps/web/app/(org)/onboarding/components/InviteTeamPage.tsx
+++ b/apps/web/app/(org)/onboarding/components/InviteTeamPage.tsx
@@ -11,7 +11,7 @@ import { useRouter } from "next/navigation";
import { type MouseEvent, startTransition, useId, useState } from "react";
import { toast } from "sonner";
import { useStripeContext } from "@/app/Layout/StripeContext";
-import { useEffectMutation } from "@/lib/EffectRuntime";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
import { withRpc } from "@/lib/Rpcs";
import { homepageCopy } from "../../../../data/homepage-copy";
import { Base } from "./Base";
@@ -22,6 +22,8 @@ export function InviteTeamPage() {
const [users, setUsers] = useState(1);
const [isAnnually, setIsAnnually] = useState(true);
const router = useRouter();
+ const rpc = useRpcClient();
+
const CAP_PRO_ANNUAL_PRICE_PER_USER = homepageCopy.pricing.pro.pricing.annual;
const CAP_PRO_MONTHLY_PRICE_PER_USER =
homepageCopy.pricing.pro.pricing.monthly;
@@ -39,17 +41,12 @@ export function InviteTeamPage() {
const decrementUsers = () => setUsers((n) => (n > 1 ? n - 1 : 1));
const inviteTeamMutation = useEffectMutation({
- mutationFn: (redirect: boolean) =>
- Effect.gen(function* () {
- yield* withRpc((r) =>
- r.UserCompleteOnboardingStep({
- step: "inviteTeam",
- data: undefined,
- }),
- );
- return redirect;
+ mutationFn: (_redirect: boolean) =>
+ rpc.UserCompleteOnboardingStep({
+ step: "inviteTeam",
+ data: undefined,
}),
- onSuccess: (redirect: boolean) => {
+ onSuccess: (_, redirect: boolean) => {
startTransition(() => {
if (redirect) {
router.push("/onboarding/download");
diff --git a/apps/web/app/(org)/onboarding/components/OrganizationSetupPage.tsx b/apps/web/app/(org)/onboarding/components/OrganizationSetupPage.tsx
index a34804fc8..31a8a09e1 100644
--- a/apps/web/app/(org)/onboarding/components/OrganizationSetupPage.tsx
+++ b/apps/web/app/(org)/onboarding/components/OrganizationSetupPage.tsx
@@ -8,7 +8,7 @@ import Image from "next/image";
import { useRouter } from "next/navigation";
import { startTransition, useRef, useState } from "react";
import { toast } from "sonner";
-import { useEffectMutation } from "@/lib/EffectRuntime";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
import { withRpc } from "@/lib/Rpcs";
import { Base } from "./Base";
@@ -23,6 +23,7 @@ export function OrganizationSetupPage({
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const router = useRouter();
+ const rpc = useRpcClient();
const handleFileChange = () => {
const file = fileInputRef.current?.files?.[0];
@@ -52,15 +53,13 @@ export function OrganizationSetupPage({
};
}
- yield* withRpc((r) =>
- r.UserCompleteOnboardingStep({
- step: "organizationSetup",
- data: {
- organizationName: data.organizationName,
- organizationIcon,
- },
- }),
- );
+ yield* rpc.UserCompleteOnboardingStep({
+ step: "organizationSetup",
+ data: {
+ organizationName: data.organizationName,
+ organizationIcon,
+ },
+ });
}),
onSuccess: () => {
startTransition(() => {
diff --git a/apps/web/app/(org)/onboarding/components/WelcomePage.tsx b/apps/web/app/(org)/onboarding/components/WelcomePage.tsx
index 070bd97d5..5c3168c67 100644
--- a/apps/web/app/(org)/onboarding/components/WelcomePage.tsx
+++ b/apps/web/app/(org)/onboarding/components/WelcomePage.tsx
@@ -4,23 +4,21 @@ import { Button, Input } from "@cap/ui";
import { useRouter } from "next/navigation";
import { startTransition, useState } from "react";
import { toast } from "sonner";
-import { useEffectMutation } from "@/lib/EffectRuntime";
-import { withRpc } from "@/lib/Rpcs";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
import { Base } from "./Base";
export function WelcomePage() {
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const router = useRouter();
+ const rpc = useRpcClient();
const welcomeMutation = useEffectMutation({
mutationFn: (data: { firstName: string; lastName?: string }) =>
- withRpc((r) =>
- r.UserCompleteOnboardingStep({
- step: "welcome",
- data,
- }),
- ),
+ rpc.UserCompleteOnboardingStep({
+ step: "welcome",
+ data,
+ }),
onSuccess: () => {
startTransition(() => {
router.push("/onboarding/organization-setup");
diff --git a/apps/web/app/(site)/Navbar.tsx b/apps/web/app/(site)/Navbar.tsx
index cbeac9a58..18a7ddc6e 100644
--- a/apps/web/app/(site)/Navbar.tsx
+++ b/apps/web/app/(site)/Navbar.tsx
@@ -17,9 +17,9 @@ import { motion } from "motion/react";
import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
-import { Suspense, use, useEffect, useState } from "react";
+import { Suspense, useEffect, useState } from "react";
import MobileMenu from "@/components/ui/MobileMenu";
-import { useAuthContext } from "../Layout/AuthContext";
+import { useCurrentUser } from "../Layout/AuthContext";
const Links = [
{
@@ -115,7 +115,7 @@ const Links = [
export const Navbar = () => {
const pathname = usePathname();
const [showMobileMenu, setShowMobileMenu] = useState(false);
- const auth = use(useAuthContext().user);
+ const auth = useCurrentUser();
const [hideLogoName, setHideLogoName] = useState(false);
@@ -295,7 +295,7 @@ export const Navbar = () => {
};
function LoginOrDashboard() {
- const auth = use(useAuthContext().user);
+ const auth = useCurrentUser();
return (
<Button
diff --git a/apps/web/app/Layout/AuthContext.tsx b/apps/web/app/Layout/AuthContext.tsx
index efbad3b04..d5dfe9741 100644
--- a/apps/web/app/Layout/AuthContext.tsx
+++ b/apps/web/app/Layout/AuthContext.tsx
@@ -1,10 +1,20 @@
"use client";
-import type { getCurrentUser } from "@cap/database/auth/session";
+import type { ImageUpload, Organisation, User } from "@cap/web-domain";
import { createContext, use } from "react";
+export type CurrentUser = {
+ id: User.UserId;
+ email: string;
+ name: string | null;
+ lastName: string | null;
+ imageUrl: ImageUpload.ImageUrl | null;
+ defaultOrgId: Organisation.OrganisationId | null;
+ isPro: boolean;
+};
+
const AuthContext = createContext<
- { user: ReturnType<typeof getCurrentUser> } | undefined
+ { user: Promise<CurrentUser | null> } | undefined
>(undefined);
export function AuthContextProvider({
@@ -12,7 +22,7 @@ export function AuthContextProvider({
user,
}: {
children: React.ReactNode;
- user: ReturnType<typeof getCurrentUser>;
+ user: Promise<CurrentUser | null>;
}) {
return (
<AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>
@@ -26,3 +36,7 @@ export function useAuthContext() {
}
return context;
}
+
+export function useCurrentUser() {
+ return use(useAuthContext().user);
+}
diff --git a/apps/web/app/Layout/Intercom/Client.tsx b/apps/web/app/Layout/Intercom/Client.tsx
index b3aebb658..a292adeed 100644
--- a/apps/web/app/Layout/Intercom/Client.tsx
+++ b/apps/web/app/Layout/Intercom/Client.tsx
@@ -2,11 +2,11 @@
import Intercom from "@intercom/messenger-js-sdk";
import { usePathname } from "next/navigation";
-import { use, useEffect } from "react";
-import { useAuthContext } from "../AuthContext";
+import { useEffect } from "react";
+import { useCurrentUser } from "../AuthContext";
export function Client(props: { hash?: string }) {
- const user = use(useAuthContext().user);
+ const user = useCurrentUser();
const pathname = usePathname();
const isSharePage = pathname?.startsWith("/s/");
const isBlogPage = pathname?.startsWith("/blog");
diff --git a/apps/web/app/Layout/PosthogIdentify.tsx b/apps/web/app/Layout/PosthogIdentify.tsx
index 1eaad3994..00644319f 100644
--- a/apps/web/app/Layout/PosthogIdentify.tsx
+++ b/apps/web/app/Layout/PosthogIdentify.tsx
@@ -7,7 +7,7 @@ import {
initAnonymousUser,
trackEvent,
} from "../utils/analytics";
-import { useAuthContext } from "./AuthContext";
+import { useCurrentUser } from "./AuthContext";
export function PosthogIdentify() {
return (
@@ -18,7 +18,7 @@ export function PosthogIdentify() {
}
function Inner() {
- const user = use(useAuthContext().user);
+ const user = useCurrentUser();
useEffect(() => {
if (!user) {
diff --git a/apps/web/app/api/upload/[...route]/multipart.ts b/apps/web/app/api/upload/[...route]/multipart.ts
index e3d39487e..1cbeb34e4 100644
--- a/apps/web/app/api/upload/[...route]/multipart.ts
+++ b/apps/web/app/api/upload/[...route]/multipart.ts
@@ -8,6 +8,8 @@ import { serverEnv } from "@cap/env";
import {
AwsCredentials,
Database,
+ makeCurrentUser,
+ makeCurrentUserLayer,
provideOptionalAuth,
S3Buckets,
Videos,
@@ -70,7 +72,6 @@ app.post(
.where(eq(Db.videoUploads.videoId, video.value[0].id)),
);
}).pipe(
- provideOptionalAuth,
Effect.tapError(Effect.logError),
Effect.catchAll((e) => {
if (e._tag === "VideoNotFoundError")
@@ -80,7 +81,7 @@ app.post(
c.json({ error: "Error initiating multipart upload" }, 500),
);
}),
- Effect.provideService(CurrentUser, user),
+ Effect.provide(makeCurrentUserLayer(user)),
runPromise,
);
if (resp) return resp;
@@ -478,6 +479,6 @@ app.post(
);
}),
);
- }).pipe(Effect.provideService(CurrentUser, user), runPromise);
+ }).pipe(Effect.provide(makeCurrentUserLayer(user)), runPromise);
},
);
diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx
index 1292e33ee..6e7cd3ea4 100644
--- a/apps/web/app/layout.tsx
+++ b/apps/web/app/layout.tsx
@@ -1,13 +1,18 @@
import "@/app/globals.css";
import { getCurrentUser } from "@cap/database/auth/session";
import { buildEnv, serverEnv } from "@cap/env";
-import { STRIPE_PLAN_IDS } from "@cap/utils";
+import { STRIPE_PLAN_IDS, userIsPro } from "@cap/utils";
+import { ImageUploads } from "@cap/web-backend";
+import type { ImageUpload } from "@cap/web-domain";
import { Analytics as DubAnalytics } from "@dub/analytics/react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
+import { Effect } from "effect";
import type { Metadata } from "next";
import localFont from "next/font/local";
import type { PropsWithChildren } from "react";
import { SonnerToaster } from "@/components/SonnerToastProvider";
+import { EffectRuntime } from "@/lib/EffectRuntime";
+import { runPromise } from "@/lib/server";
import { getBootstrapData } from "@/utils/getBootstrapData";
import { PublicEnvContext } from "@/utils/public-env";
import { AuthContextProvider } from "./Layout/AuthContext";
@@ -75,78 +80,98 @@ export const metadata: Metadata = {
export const dynamic = "force-dynamic";
-export default async function RootLayout({ children }: PropsWithChildren) {
- const bootstrapData = await getBootstrapData();
- const userPromise = getCurrentUser();
+export default ({ children }: PropsWithChildren) =>
+ Effect.gen(function* () {
+ const imageUploads = yield* ImageUploads;
+ const bootstrapData = yield* Effect.promise(getBootstrapData);
+ const userPromise = Effect.promise(getCurrentUser).pipe(
+ Effect.flatMap(
+ Effect.fn(function* (u) {
+ if (!u) return null;
+ return {
+ id: u.id,
+ name: u.name,
+ lastName: u.lastName,
+ defaultOrgId: u.defaultOrgId,
+ email: u.email,
+ imageUrl: u.image
+ ? yield* imageUploads.resolveImageUrl(u.image)
+ : null,
+ isPro: userIsPro(u),
+ };
+ }),
+ ),
+ runPromise,
+ );
- return (
- <html className={defaultFont.className} lang="en">
- <head>
- <link
- rel="apple-touch-icon"
- sizes="180x180"
- href="/apple-touch-icon.png"
- />
- <link
- rel="icon"
- type="image/png"
- sizes="32x32"
- href="/favicon-32x32.png"
- />
- <link
- rel="icon"
- type="image/png"
- sizes="16x16"
- href="/favicon-16x16.png"
- />
- <link rel="manifest" href="/site.webmanifest" />
- <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" />
- <link rel="shortcut icon" href="/favicon.ico" />
- <meta name="msapplication-TileColor" content="#da532c" />
- <meta name="theme-color" content="#ffffff" />
- </head>
- <body suppressHydrationWarning>
- <script
- dangerouslySetInnerHTML={{ __html: `(${script.toString()})()` }}
- />
- <TooltipPrimitive.Provider>
- <PostHogProvider bootstrapData={bootstrapData}>
- <AuthContextProvider user={userPromise}>
- <SessionProvider>
- <StripeContextProvider
- plans={
- serverEnv().VERCEL_ENV === "production"
- ? STRIPE_PLAN_IDS.production
- : STRIPE_PLAN_IDS.development
- }
- >
- <PublicEnvContext
- value={{
- webUrl: buildEnv.NEXT_PUBLIC_WEB_URL,
- }}
- >
- <ReactQueryProvider>
- <SonnerToaster />
- <main className="w-full">{children}</main>
- <PosthogIdentify />
- <MetaPixel />
- <GTag />
- <PurchaseTracker />
- </ReactQueryProvider>
- </PublicEnvContext>
- </StripeContextProvider>
- </SessionProvider>
- </AuthContextProvider>
- </PostHogProvider>
- </TooltipPrimitive.Provider>
- {buildEnv.NEXT_PUBLIC_IS_CAP && (
- <DubAnalytics
- domainsConfig={{
- refer: "go.cap.so",
- }}
+ return (
+ <html className={defaultFont.className} lang="en">
+ <head>
+ <link
+ rel="apple-touch-icon"
+ sizes="180x180"
+ href="/apple-touch-icon.png"
+ />
+ <link
+ rel="icon"
+ type="image/png"
+ sizes="32x32"
+ href="/favicon-32x32.png"
+ />
+ <link
+ rel="icon"
+ type="image/png"
+ sizes="16x16"
+ href="/favicon-16x16.png"
/>
- )}
- </body>
- </html>
- );
-}
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" />
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <meta name="msapplication-TileColor" content="#da532c" />
+ <meta name="theme-color" content="#ffffff" />
+ </head>
+ <body suppressHydrationWarning>
+ <script
+ dangerouslySetInnerHTML={{ __html: `(${script.toString()})()` }}
+ />
+ <TooltipPrimitive.Provider>
+ <PostHogProvider bootstrapData={bootstrapData}>
+ <AuthContextProvider user={userPromise}>
+ <SessionProvider>
+ <StripeContextProvider
+ plans={
+ serverEnv().VERCEL_ENV === "production"
+ ? STRIPE_PLAN_IDS.production
+ : STRIPE_PLAN_IDS.development
+ }
+ >
+ <PublicEnvContext
+ value={{
+ webUrl: buildEnv.NEXT_PUBLIC_WEB_URL,
+ }}
+ >
+ <ReactQueryProvider>
+ <SonnerToaster />
+ <main className="w-full">{children}</main>
+ <PosthogIdentify />
+ <MetaPixel />
+ <GTag />
+ <PurchaseTracker />
+ </ReactQueryProvider>
+ </PublicEnvContext>
+ </StripeContextProvider>
+ </SessionProvider>
+ </AuthContextProvider>
+ </PostHogProvider>
+ </TooltipPrimitive.Provider>
+ {buildEnv.NEXT_PUBLIC_IS_CAP && (
+ <DubAnalytics
+ domainsConfig={{
+ refer: "go.cap.so",
+ }}
+ />
+ )}
+ </body>
+ </html>
+ );
+ }).pipe(runPromise);
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index 2d3cae7d9..3d0e4e71d 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -2,7 +2,7 @@
import type { userSelectProps } from "@cap/database/auth/session";
import type { comments as commentsSchema, videos } from "@cap/database/schema";
-import type { Video } from "@cap/web-domain";
+import type { ImageUpload, Video } from "@cap/web-domain";
import { useQuery } from "@tanstack/react-query";
import {
startTransition,
@@ -25,12 +25,12 @@ import { Toolbar } from "./_components/Toolbar";
type CommentWithAuthor = typeof commentsSchema.$inferSelect & {
authorName: string | null;
- authorImageUrlOrKey: string | null;
+ authorImage: ImageUpload.ImageUrl | null;
};
export type CommentType = typeof commentsSchema.$inferSelect & {
authorName?: string | null;
- authorImageUrlOrKey?: string | null;
+ authorImage?: ImageUpload.ImageUrl | null;
sending?: boolean;
};
@@ -44,7 +44,6 @@ type VideoWithOrganizationInfo = typeof videos.$inferSelect & {
interface ShareProps {
data: VideoWithOrganizationInfo;
- user: typeof userSelectProps | null;
comments: MaybePromise<CommentWithAuthor[]>;
views: MaybePromise<number>;
customDomain: string | null;
@@ -139,7 +138,6 @@ const useVideoStatus = (
export const Share = ({
data,
- user,
comments,
ownerIsPro,
views,
@@ -292,7 +290,6 @@ export const Share = ({
<div className="absolute inset-3 w-[calc(100%-1.5rem)] h-[calc(100%-1.5rem)] overflow-visible rounded-xl">
<ShareVideo
data={{ ...data, transcriptionStatus }}
- user={user}
comments={comments}
areChaptersDisabled={areChaptersDisabled}
areCaptionsDisabled={areCaptionsDisabled}
@@ -309,7 +306,6 @@ export const Share = ({
onOptimisticComment={handleOptimisticComment}
onCommentSuccess={handleCommentSuccess}
data={data}
- user={user}
/>
</div>
</div>
@@ -324,7 +320,6 @@ export const Share = ({
}}
ownerIsPro={ownerIsPro}
videoSettings={videoSettings}
- user={user}
commentsData={commentsData}
setCommentsData={setCommentsData}
optimisticComments={optimisticComments}
@@ -351,7 +346,6 @@ export const Share = ({
data.orgSettings?.disableReactions
}
data={data}
- user={user}
/>
</div>
</div>
diff --git a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
index 876d7c9ba..f05d17636 100644
--- a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
@@ -50,7 +50,6 @@ interface Props {
type: "text" | "emoji";
content: string;
authorName?: string | null;
- authorImageUrlOrKey?: string | null;
}>;
onSeek?: (time: number) => void;
}
diff --git a/apps/web/app/s/[videoId]/_components/CommentStamp.tsx b/apps/web/app/s/[videoId]/_components/CommentStamp.tsx
index 91d8b538d..95011ccff 100644
--- a/apps/web/app/s/[videoId]/_components/CommentStamp.tsx
+++ b/apps/web/app/s/[videoId]/_components/CommentStamp.tsx
@@ -1,3 +1,4 @@
+import type { ImageUpload } from "@cap/web-domain";
import { faComment } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { SignedImageUrl } from "@/components/SignedImageUrl";
@@ -9,7 +10,7 @@ interface CommentStampsProps {
type: "text" | "emoji";
content: string;
authorName?: string | null;
- authorImageUrlOrKey?: string | null;
+ authorImage?: ImageUpload.ImageUrl | null;
};
adjustedPosition: string;
handleMouseEnter: (id: string) => void;
@@ -64,9 +65,8 @@ const CommentStamp: React.FC<CommentStampsProps> = ({
{/* User avatar/initial */}
{comment.authorName && (
<SignedImageUrl
- image={comment.authorImageUrlOrKey}
+ image={comment.authorImage}
name={comment.authorName}
- type="user"
className="size-6"
letterClass="text-sm"
/>
diff --git a/apps/web/app/s/[videoId]/_components/ImageViewer.tsx b/apps/web/app/s/[videoId]/_components/ImageViewer.tsx
index 0ed75ab90..d4d6ad8ca 100644
--- a/apps/web/app/s/[videoId]/_components/ImageViewer.tsx
+++ b/apps/web/app/s/[videoId]/_components/ImageViewer.tsx
@@ -12,12 +12,10 @@ import { Toolbar } from "./Toolbar";
// million-ignore
export const ImageViewer = ({
data,
- user,
comments,
imageSrc,
}: {
data: typeof videos.$inferSelect;
- user: typeof userSelectProps | null;
comments: (typeof commentsSchema.$inferSelect)[];
imageSrc: string;
}) => {
@@ -33,7 +31,7 @@ export const ImageViewer = ({
return (
<div className="wrapper py-8">
<div className="space-y-6">
- <ShareHeader data={data} user={user} />
+ <ShareHeader data={data} />
<div
className="relative flex h-full w-full overflow-hidden shadow-lg rounded-lg group"
id="player"
@@ -106,7 +104,7 @@ export const ImageViewer = ({
</div>
</div>
<div className="flex justify-center">
- <Toolbar data={data} user={user} />
+ <Toolbar data={data} />
</div>
</div>
</div>
diff --git a/apps/web/app/s/[videoId]/_components/ProgressCircle.tsx b/apps/web/app/s/[videoId]/_components/ProgressCircle.tsx
index 0148e2030..ce5a6c3ae 100644
--- a/apps/web/app/s/[videoId]/_components/ProgressCircle.tsx
+++ b/apps/web/app/s/[videoId]/_components/ProgressCircle.tsx
@@ -3,8 +3,7 @@
import type { Video } from "@cap/web-domain";
import clsx from "clsx";
import { Effect, Option } from "effect";
-import { useEffectQuery } from "@/lib/EffectRuntime";
-import { withRpc } from "@/lib/Rpcs";
+import { useEffectQuery, useRpcClient } from "@/lib/EffectRuntime";
type UploadProgress =
| { status: "fetching" }
@@ -27,12 +26,14 @@ export function useUploadProgress(
videoId: Video.VideoId,
enabled: boolean,
): UploadProgress | null {
+ const rpc = useRpcClient();
+
const query = useEffectQuery({
queryKey: ["getUploadProgress", videoId],
queryFn: () =>
- withRpc((rpc) => rpc.GetUploadProgress(videoId)).pipe(
- Effect.map((v) => Option.getOrNull(v ?? Option.none())),
- ),
+ rpc
+ .GetUploadProgress(videoId)
+ .pipe(Effect.map((v) => Option.getOrNull(v ?? Option.none()))),
enabled,
refetchInterval: (query) => {
if (!enabled || !query.state.data) return false;
diff --git a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
index 9ea8d9cc0..12939e03b 100644
--- a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
@@ -5,6 +5,7 @@ import type { videos } from "@cap/database/schema";
import { buildEnv, NODE_ENV } from "@cap/env";
import { Button } from "@cap/ui";
import { userIsPro } from "@cap/utils";
+import type { ImageUpload } from "@cap/web-domain";
import { faChevronDown, faLock } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Check, Copy, Globe2 } from "lucide-react";
@@ -16,13 +17,13 @@ import { editTitle } from "@/actions/videos/edit-title";
import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";
import { SharingDialog } from "@/app/(org)/dashboard/caps/components/SharingDialog";
import type { Spaces } from "@/app/(org)/dashboard/dashboard-data";
+import { useCurrentUser } from "@/app/Layout/AuthContext";
import { SignedImageUrl } from "@/components/SignedImageUrl";
import { UpgradeModal } from "@/components/UpgradeModal";
import { usePublicEnv } from "@/utils/public-env";
export const ShareHeader = ({
data,
- user,
customDomain,
domainVerified,
sharedOrganizations = [],
@@ -31,10 +32,9 @@ export const ShareHeader = ({
}: {
data: typeof videos.$inferSelect & {
ownerName?: string | null;
- ownerImage?: string | null;
+ ownerImage?: ImageUpload.ImageUrl | null;
ownerIsPro?: boolean;
};
- user: typeof userSelectProps | null;
customDomain?: string | null;
domainVerified?: boolean;
sharedOrganizations?: { id: string; name: string }[];
@@ -53,6 +53,7 @@ export const ShareHeader = ({
}[];
spacesData?: Spaces[] | null;
}) => {
+ const user = useCurrentUser();
const { push, refresh } = useRouter();
const [isEditing, setIsEditing] = useState(false);
const [title, setTitle] = useState(data.name);
@@ -240,7 +241,6 @@ export const ShareHeader = ({
<SignedImageUrl
name={data.ownerName ?? "User"}
image={data.ownerImage}
- type="user"
className="size-8"
letterClass="text-base"
/>
diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
index 6dd3c6529..49fcb681f 100644
--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
@@ -2,6 +2,7 @@ import type { userSelectProps } from "@cap/database/auth/session";
import type { comments as commentsSchema, videos } from "@cap/database/schema";
import { NODE_ENV } from "@cap/env";
import { Logo } from "@cap/ui";
+import type { ImageUpload } from "@cap/web-domain";
import { useTranscript } from "hooks/use-transcript";
import {
forwardRef,
@@ -29,7 +30,7 @@ declare global {
type CommentWithAuthor = typeof commentsSchema.$inferSelect & {
authorName: string | null;
- authorImageUrlOrKey: string | null;
+ authorImage: ImageUpload.ImageUrl | null;
};
export const ShareVideo = forwardRef<
@@ -40,7 +41,6 @@ export const ShareVideo = forwardRef<
hasActiveUpload?: boolean;
orgSettings?: OrganizationSettings | null;
};
- user: typeof userSelectProps | null;
comments: MaybePromise<CommentWithAuthor[]>;
chapters?: { title: string; start: number }[];
areChaptersDisabled?: boolean;
@@ -203,7 +203,7 @@ export const ShareVideo = forwardRef<
timestamp: comment.timestamp,
content: comment.content,
authorName: comment.authorName,
- authorImageUrlOrKey: comment.authorImageUrlOrKey ?? undefined,
+ authorImage: comment.authorImage ?? undefined,
}))}
onSeek={handleSeek}
/>
diff --git a/apps/web/app/s/[videoId]/_components/Sidebar.tsx b/apps/web/app/s/[videoId]/_components/Sidebar.tsx
index 137977050..409ad205e 100644
--- a/apps/web/app/s/[videoId]/_components/Sidebar.tsx
+++ b/apps/web/app/s/[videoId]/_components/Sidebar.tsx
@@ -1,11 +1,12 @@
import type { userSelectProps } from "@cap/database/auth/session";
import type { comments as commentsSchema, videos } from "@cap/database/schema";
import { classNames, userIsPro } from "@cap/utils";
-import type { Video } from "@cap/web-domain";
+import type { ImageUpload, Video } from "@cap/web-domain";
import clsx from "clsx";
import { AnimatePresence, motion } from "framer-motion";
import { forwardRef, Suspense, useState } from "react";
import type { OrganizationSettings } from "@/app/(org)/dashboard/dashboard-data";
+import { useCurrentUser } from "@/app/Layout/AuthContext";
import { Activity } from "./tabs/Activity";
import { Settings } from "./tabs/Settings";
import { Summary } from "./tabs/Summary";
@@ -15,7 +16,7 @@ type TabType = "activity" | "transcript" | "summary" | "settings";
type CommentType = typeof commentsSchema.$inferSelect & {
authorName?: string | null;
- authorImage?: string | null;
+ authorImage?: ImageUpload.ImageUrl | null;
};
type VideoWithOrganizationInfo = typeof videos.$inferSelect & {
@@ -26,7 +27,6 @@ type VideoWithOrganizationInfo = typeof videos.$inferSelect & {
interface SidebarProps {
data: VideoWithOrganizationInfo;
- user: typeof userSelectProps | null;
commentsData: CommentType[];
optimisticComments: CommentType[];
handleCommentSuccess: (comment: CommentType) => void;
@@ -74,7 +74,6 @@ export const Sidebar = forwardRef<{ scrollToBottom: () => void }, SidebarProps>(
(
{
data,
- user,
commentsData,
setCommentsData,
optimisticComments,
@@ -90,6 +89,8 @@ export const Sidebar = forwardRef<{ scrollToBottom: () => void }, SidebarProps>(
},
ref,
) => {
+ const user = useCurrentUser();
+
const isOwnerOrMember: boolean = Boolean(
user?.id === data.ownerId ||
(data.organizationId &&
@@ -148,12 +149,7 @@ export const Sidebar = forwardRef<{ scrollToBottom: () => void }, SidebarProps>(
case "activity":
return (
<Suspense
- fallback={
- <Activity.Skeleton
- user={user}
- isOwnerOrMember={isOwnerOrMember}
- />
- }
+ fallback={<Activity.Skeleton isOwnerOrMember={isOwnerOrMember} />}
>
<Activity
ref={ref}
@@ -165,7 +161,6 @@ export const Sidebar = forwardRef<{ scrollToBottom: () => void }, SidebarProps>(
false
}
setComments={setCommentsData}
- user={user}
optimisticComments={optimisticComments}
setOptimisticComments={setOptimisticComments}
handleCommentSuccess={handleCommentSuccess}
diff --git a/apps/web/app/s/[videoId]/_components/Toolbar.tsx b/apps/web/app/s/[videoId]/_components/Toolbar.tsx
index 9bb617844..4605d4d12 100644
--- a/apps/web/app/s/[videoId]/_components/Toolbar.tsx
+++ b/apps/web/app/s/[videoId]/_components/Toolbar.tsx
@@ -6,6 +6,7 @@ import { AnimatePresence, motion } from "motion/react";
import { startTransition, useEffect, useState } from "react";
import { newComment } from "@/actions/videos/new-comment";
import type { OrganizationSettings } from "@/app/(org)/dashboard/dashboard-data";
+import { useCurrentUser } from "@/app/Layout/AuthContext";
import type { CommentType } from "../Share";
import { AuthOverlay } from "./AuthOverlay";
@@ -16,7 +17,6 @@ interface ToolbarProps {
data: typeof videos.$inferSelect & {
orgSettings?: OrganizationSettings | null;
};
- user: typeof userSelectProps | null;
onOptimisticComment?: (comment: CommentType) => void;
onCommentSuccess?: (comment: CommentType) => void;
disableReactions?: boolean;
@@ -24,23 +24,24 @@ interface ToolbarProps {
export const Toolbar = ({
data,
- user,
onOptimisticComment,
onCommentSuccess,
disableReactions,
}: ToolbarProps) => {
+ const user = useCurrentUser();
const [commentBoxOpen, setCommentBoxOpen] = useState(false);
const [comment, setComment] = useState("");
const [showAuthOverlay, setShowAuthOverlay] = useState(false);
const handleEmojiClick = async (emoji: string) => {
+ if (!user) return;
const videoElement = document.querySelector("video") as HTMLVideoElement;
const currentTime = videoElement?.currentTime || 0;
const optimisticComment: CommentType = {
id: Comment.CommentId.make(`temp-${Date.now()}`),
- authorId: User.UserId.make(user?.id || "anonymous"),
- authorName: user?.name || "Anonymous",
- authorImageUrlOrKey: user?.image ?? null,
+ authorId: user.id,
+ authorName: user.name,
+ authorImage: user.imageUrl,
content: emoji,
createdAt: new Date(),
videoId: data.id,
@@ -73,16 +74,16 @@ export const Toolbar = ({
};
const handleCommentSubmit = async () => {
- if (comment.length === 0) {
+ if (comment.length === 0 || !user) {
return;
}
const videoElement = document.querySelector("video") as HTMLVideoElement;
const currentTime = videoElement?.currentTime || 0;
const optimisticComment: CommentType = {
id: Comment.CommentId.make(`temp-${Date.now()}`),
- authorId: User.UserId.make(user?.id || "anonymous"),
- authorName: user?.name || "Anonymous",
- authorImageUrlOrKey: user?.image ?? null,
+ authorId: user.id,
+ authorName: user.name,
+ authorImage: user.imageUrl,
content: comment,
createdAt: new Date(),
videoId: data.id,
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx
index 0367b2cd2..55fef7d8f 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx
@@ -8,6 +8,7 @@ import clsx from "clsx";
import { motion } from "framer-motion";
import { useSearchParams } from "next/navigation";
import type React from "react";
+import { useCurrentUser } from "@/app/Layout/AuthContext";
import { SignedImageUrl } from "@/components/SignedImageUrl";
import { Tooltip } from "@/components/Tooltip";
import type { CommentType } from "../../../Share";
@@ -25,7 +26,6 @@ const CommentComponent: React.FC<{
commentId: Comment.CommentId,
parentId: Comment.CommentId | null,
) => void;
- user: typeof userSelectProps | null;
level?: number;
onSeek?: (time: number) => void;
}> = ({
@@ -36,10 +36,10 @@ const CommentComponent: React.FC<{
handleReply,
onCancelReply,
onDelete,
- user,
level = 0,
onSeek,
}) => {
+ const user = useCurrentUser();
const isReplying = replyingToId === comment.id;
const isOwnComment = user?.id === comment.authorId;
const commentParams = useSearchParams().get("comment");
@@ -77,9 +77,8 @@ const CommentComponent: React.FC<{
<div className="flex items-start space-x-2.5">
{comment.authorName && (
<SignedImageUrl
- image={comment.authorImageUrlOrKey}
+ image={comment.authorImage}
name={comment.authorName}
- type="user"
className="size-6"
letterClass="text-sm"
/>
@@ -167,7 +166,6 @@ const CommentComponent: React.FC<{
onCancel={onCancelReply}
placeholder="Write a reply..."
showCancelButton={true}
- user={user}
autoFocus={true}
/>
</div>
@@ -185,7 +183,6 @@ const CommentComponent: React.FC<{
handleReply={handleReply}
onCancelReply={onCancelReply}
onDelete={onDelete}
- user={user}
level={1}
onSeek={onSeek}
/>
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/CommentInput.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity/CommentInput.tsx
index b5249db69..e832a0418 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Activity/CommentInput.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/CommentInput.tsx
@@ -9,7 +9,6 @@ interface CommentInputProps {
placeholder?: string;
showCancelButton?: boolean;
buttonLabel?: string;
- user?: typeof userSelectProps | null;
autoFocus?: boolean;
disabled?: boolean;
}
@@ -20,7 +19,6 @@ const CommentInput: React.FC<CommentInputProps> = ({
placeholder,
showCancelButton = false,
buttonLabel = "Reply",
- user,
autoFocus = false,
disabled,
}) => {
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx
index 10152e2f9..63ab4aaf9 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx
@@ -18,6 +18,7 @@ import {
} from "react";
import { deleteComment } from "@/actions/videos/delete-comment";
import { newComment } from "@/actions/videos/new-comment";
+import { useCurrentUser } from "@/app/Layout/AuthContext";
import type { CommentType } from "../../../Share";
import CommentComponent from "./Comment";
import CommentInput from "./CommentInput";
@@ -28,7 +29,6 @@ export const Comments = Object.assign(
{ scrollToBottom: () => void },
{
setComments: React.Dispatch<React.SetStateAction<CommentType[]>>;
- user: typeof userSelectProps | null;
videoId: Video.VideoId;
optimisticComments: CommentType[];
setOptimisticComments: (newComment: CommentType) => void;
@@ -48,8 +48,8 @@ export const Comments = Object.assign(
} = props;
const commentParams = useSearchParams().get("comment");
const replyParams = useSearchParams().get("reply");
+ const user = useCurrentUser();
- const { user } = props;
const [replyingTo, setReplyingTo] = useState<Comment.CommentId | null>(
null,
);
@@ -80,15 +80,17 @@ export const Comments = Object.assign(
);
const handleNewComment = async (content: string) => {
+ if (!user) return;
+
// Get current video time from the video element
const videoElement = document.querySelector("video") as HTMLVideoElement;
const currentTime = videoElement?.currentTime || 0;
const optimisticComment: CommentType = {
id: Comment.CommentId.make(`temp-${Date.now()}`),
- authorId: User.UserId.make(user?.id || "anonymous"),
- authorName: user?.name || "Anonymous",
- authorImageUrlOrKey: user?.image ?? null,
+ authorId: User.UserId.make(user.id),
+ authorName: user?.name,
+ authorImage: user.imageUrl,
content,
createdAt: new Date(),
videoId: props.videoId,
@@ -118,7 +120,8 @@ export const Comments = Object.assign(
};
const handleReply = async (content: string) => {
- if (!replyingTo) return;
+ if (!replyingTo || !user) return;
+
const videoElement = document.querySelector("video") as HTMLVideoElement;
const currentTime = videoElement?.currentTime || 0;
@@ -129,9 +132,9 @@ export const Comments = Object.assign(
const optimisticReply: CommentType = {
id: Comment.CommentId.make(`temp-reply-${Date.now()}`),
- authorId: User.UserId.make(user?.id || "anonymous"),
- authorName: user?.name || "Anonymous",
- authorImageUrlOrKey: user?.image ?? null,
+ authorId: user.id,
+ authorName: user.name,
+ authorImage: user.imageUrl ?? null,
content,
createdAt: new Date(),
videoId: props.videoId,
@@ -197,7 +200,6 @@ export const Comments = Object.assign(
disabled: commentsDisabled,
}}
setShowAuthOverlay={props.setShowAuthOverlay}
- user={user}
commentsContainerRef={commentsContainerRef}
>
{commentsDisabled ? (
@@ -227,7 +229,6 @@ export const Comments = Object.assign(
handleReply={handleReply}
onCancelReply={handleCancelReply}
onDelete={handleDeleteComment}
- user={user}
onSeek={onSeek}
/>
))}
@@ -239,7 +240,6 @@ export const Comments = Object.assign(
{
Shell: (
props: PropsWithChildren<{
- user: typeof userSelectProps | null;
setShowAuthOverlay: (v: boolean) => void;
commentInputProps?: Omit<
ComponentProps<typeof CommentInput>,
@@ -247,40 +247,42 @@ export const Comments = Object.assign(
>;
commentsContainerRef?: React.RefObject<HTMLDivElement | null>;
}>,
- ) => (
- <>
- <div
- ref={props.commentsContainerRef}
- className="overflow-y-auto flex-1 min-h-0"
- >
- {props.children}
- </div>
+ ) => {
+ const user = useCurrentUser();
- {!props.commentInputProps?.disabled && (
- <div className="flex-none p-2 border-t border-gray-5 bg-gray-2">
- {props.user ? (
- <CommentInput
- {...props.commentInputProps}
- placeholder="Leave a comment"
- buttonLabel="Comment"
- user={props.user}
- />
- ) : (
- <Button
- className="min-w-full"
- variant="primary"
- onClick={() => props.setShowAuthOverlay(true)}
- >
- Sign in to leave a comment
- </Button>
- )}
+ return (
+ <>
+ <div
+ ref={props.commentsContainerRef}
+ className="overflow-y-auto flex-1 min-h-0"
+ >
+ {props.children}
</div>
- )}
- </>
+
+ {!props.commentInputProps?.disabled && (
+ <div className="flex-none p-2 border-t border-gray-5 bg-gray-2">
+ {user ? (
+ <CommentInput
+ {...props.commentInputProps}
+ placeholder="Leave a comment"
+ buttonLabel="Comment"
+ />
+ ) : (
+ <Button
+ className="min-w-full"
+ variant="primary"
+ onClick={() => props.setShowAuthOverlay(true)}
+ >
+ Sign in to leave a comment
+ </Button>
+ )}
+ </div>
+ )}
+ </>
+ );
+ },
+ Skeleton: (props: { setShowAuthOverlay: (v: boolean) => void }) => (
+ <Comments.Shell {...props} commentInputProps={{ disabled: true }} />
),
- Skeleton: (props: {
- user: typeof userSelectProps | null;
- setShowAuthOverlay: (v: boolean) => void;
- }) => <Comments.Shell {...props} commentInputProps={{ disabled: true }} />,
},
);
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/index.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity/index.tsx
index c9cce9d03..c5534c8a1 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Activity/index.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/index.tsx
@@ -1,10 +1,10 @@
"use client";
-import type { userSelectProps } from "@cap/database/auth/session";
import type { Video } from "@cap/web-domain";
import type React from "react";
import { forwardRef, type JSX, Suspense, useState } from "react";
import { CapCardAnalytics } from "@/app/(org)/dashboard/caps/components/CapCard/CapCardAnalytics";
+import { useCurrentUser } from "@/app/Layout/AuthContext";
import type { CommentType } from "../../../Share";
import { AuthOverlay } from "../../AuthOverlay";
import Analytics from "./Analytics";
@@ -14,7 +14,6 @@ interface ActivityProps {
views: MaybePromise<number>;
comments: CommentType[];
setComments: React.Dispatch<React.SetStateAction<CommentType[]>>;
- user: typeof userSelectProps | null;
onSeek?: (time: number) => void;
handleCommentSuccess: (comment: CommentType) => void;
videoId: Video.VideoId;
@@ -28,7 +27,6 @@ export const Activity = Object.assign(
forwardRef<{ scrollToBottom: () => void }, ActivityProps>(
(
{
- user,
videoId,
isOwnerOrMember,
comments,
@@ -53,7 +51,6 @@ export const Activity = Object.assign(
/>
</Suspense>
}
- user={user}
isOwnerOrMember={isOwnerOrMember}
>
{({ setShowAuthOverlay }) => (
@@ -63,7 +60,6 @@ export const Activity = Object.assign(
optimisticComments={optimisticComments}
setOptimisticComments={setOptimisticComments}
setComments={setComments}
- user={user}
videoId={videoId}
setShowAuthOverlay={setShowAuthOverlay}
onSeek={props.onSeek}
@@ -77,17 +73,17 @@ export const Activity = Object.assign(
{
Shell: (props: {
analytics?: JSX.Element;
- user: typeof userSelectProps | null;
isOwnerOrMember: boolean;
children?: (props: {
setShowAuthOverlay: (show: boolean) => void;
}) => JSX.Element;
}) => {
+ const user = useCurrentUser();
const [showAuthOverlay, setShowAuthOverlay] = useState(false);
return (
<div className="flex flex-col h-full">
- {props.user && props.isOwnerOrMember && (
+ {user && props.isOwnerOrMember && (
<div className="flex flex-row items-center p-4 h-12 border-b border-gray-200">
{props.analytics}
</div>
@@ -102,16 +98,10 @@ export const Activity = Object.assign(
</div>
);
},
- Skeleton: (props: {
- user: typeof userSelectProps | null;
- isOwnerOrMember: boolean;
- }) => (
+ Skeleton: (props: { isOwnerOrMember: boolean }) => (
<Activity.Shell {...props} analytics={<CapCardAnalytics.Skeleton />}>
{({ setShowAuthOverlay }) => (
- <Comments.Skeleton
- setShowAuthOverlay={setShowAuthOverlay}
- user={props.user}
- />
+ <Comments.Skeleton setShowAuthOverlay={setShowAuthOverlay} />
)}
</Activity.Shell>
),
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index 7fe1947d6..00b7f57ec 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -14,10 +14,16 @@ import {
import type { VideoMetadata } from "@cap/database/types";
import { buildEnv } from "@cap/env";
import { Logo } from "@cap/ui";
-import { provideOptionalAuth, Videos } from "@cap/web-backend";
+import {
+ Database,
+ ImageUploads,
+ provideOptionalAuth,
+ Videos,
+} from "@cap/web-backend";
import { VideosPolicy } from "@cap/web-backend/src/Videos/VideosPolicy";
import {
Comment,
+ type ImageUpload,
type Organisation,
Policy,
type Video,
@@ -633,15 +639,20 @@ async function AuthorizedContent({
)
: Promise.resolve([]);
- const commentsPromise = (async () => {
+ const commentsPromise = Effect.gen(function* () {
+ const db = yield* Database;
+ const imageUploads = yield* ImageUploads;
+
let toplLevelCommentId = Option.none<Comment.CommentId>();
if (Option.isSome(replyId)) {
- const [parentComment] = await db()
- .select({ parentCommentId: comments.parentCommentId })
- .from(comments)
- .where(eq(comments.id, replyId.value))
- .limit(1);
+ const [parentComment] = yield* db.use((db) =>
+ db
+ .select({ parentCommentId: comments.parentCommentId })
+ .from(comments)
+ .where(eq(comments.id, replyId.value))
+ .limit(1),
+ );
toplLevelCommentId = Option.fromNullable(parentComment?.parentCommentId);
}
@@ -650,33 +661,50 @@ async function AuthorizedContent({
() => commentId,
);
- const allComments = await db()
- .select({
- id: comments.id,
- content: comments.content,
- timestamp: comments.timestamp,
- type: comments.type,
- authorId: comments.authorId,
- videoId: comments.videoId,
- createdAt: comments.createdAt,
- updatedAt: comments.updatedAt,
- parentCommentId: comments.parentCommentId,
- authorName: users.name,
- authorImageUrlOrKey: users.image,
- })
- .from(comments)
- .leftJoin(users, eq(comments.authorId, users.id))
- .where(eq(comments.videoId, videoId))
- .orderBy(
- Option.match(commentToBringToTheTop, {
- onSome: (commentId) =>
- sql`CASE WHEN ${comments.id} = ${commentId} THEN 0 ELSE 1 END, ${comments.createdAt}`,
- onNone: () => comments.createdAt,
- }),
+ return yield* db
+ .use((db) =>
+ db
+ .select({
+ id: comments.id,
+ content: comments.content,
+ timestamp: comments.timestamp,
+ type: comments.type,
+ authorId: comments.authorId,
+ videoId: comments.videoId,
+ createdAt: comments.createdAt,
+ updatedAt: comments.updatedAt,
+ parentCommentId: comments.parentCommentId,
+ authorName: users.name,
+ authorImage: users.image,
+ })
+ .from(comments)
+ .leftJoin(users, eq(comments.authorId, users.id))
+ .where(eq(comments.videoId, videoId))
+ .orderBy(
+ Option.match(commentToBringToTheTop, {
+ onSome: (commentId) =>
+ sql`CASE WHEN ${comments.id} = ${commentId} THEN 0 ELSE 1 END, ${comments.createdAt}`,
+ onNone: () => comments.createdAt,
+ }),
+ ),
+ )
+ .pipe(
+ Effect.map((comments) =>
+ comments.map(
+ Effect.fn(function* (c) {
+ return Object.assign(c, {
+ authorImage: yield* Option.fromNullable(c.authorImage).pipe(
+ Option.map(imageUploads.resolveImageUrl),
+ Effect.transposeOption,
+ Effect.map(Option.getOrNull),
+ ),
+ });
+ }),
+ ),
+ ),
+ Effect.flatMap(Effect.all),
);
-
- return allComments;
- })();
+ }).pipe(EffectRuntime.runPromise);
const viewsPromise = getVideoAnalytics(videoId).then((v) => v.count);
@@ -714,7 +742,6 @@ async function AuthorizedContent({
? new Date(video.metadata.customCreatedAt)
: video.createdAt,
}}
- user={user}
customDomain={customDomain}
domainVerified={domainVerified}
sharedOrganizations={
@@ -728,7 +755,6 @@ async function AuthorizedContent({
<Share
data={videoWithOrganizationInfo}
videoSettings={videoWithOrganizationInfo.settings}
- user={user}
ownerIsPro={videoWithOrganizationInfo.ownerIsPro}
comments={commentsPromise}
views={viewsPromise}
diff --git a/apps/web/components/FileInput.tsx b/apps/web/components/FileInput.tsx
index 25cdfe55d..0bc5cfb95 100644
--- a/apps/web/components/FileInput.tsx
+++ b/apps/web/components/FileInput.tsx
@@ -1,6 +1,7 @@
"use client";
import { Button, Input, LoadingSpinner } from "@cap/ui";
+import { ImageUpload } from "@cap/web-domain";
import {
faCloudUpload,
faSpinner,
@@ -11,7 +12,6 @@ import clsx from "clsx";
import type React from "react";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
-import { useSignedImageUrl } from "@/lib/use-signed-image-url";
import { SignedImageUrl } from "./SignedImageUrl";
import { Tooltip } from "./Tooltip";
@@ -24,11 +24,10 @@ export interface FileInputProps {
disabled?: boolean;
id?: string;
name?: string;
- type: "user" | "organization";
containerStyle?: React.CSSProperties;
className?: string;
notDraggingClassName?: string;
- initialPreviewUrl?: string | null;
+ initialPreviewUrl?: ImageUpload.ImageUrl | null;
onRemove?: () => void;
isLoading?: boolean;
height?: string | number;
@@ -42,7 +41,6 @@ export const FileInput: React.FC<FileInputProps> = ({
disabled = false,
id = "file",
name = "file",
- type,
className = "",
notDraggingClassName = "",
initialPreviewUrl = null,
@@ -54,14 +52,11 @@ export const FileInput: React.FC<FileInputProps> = ({
}) => {
const fileInputRef = useRef<HTMLInputElement>(null);
const [isDragging, setIsDragging] = useState(false);
- const [previewUrl, setPreviewUrl] = useState<string | null>(
+ const [previewUrl, setPreviewUrl] = useState<ImageUpload.ImageUrl | null>(
initialPreviewUrl,
);
const [isLocalPreview, setIsLocalPreview] = useState(false);
- // Get signed URL for S3 keys
- const { data: signedUrl } = useSignedImageUrl(previewUrl, type);
-
const previousPreviewRef = useRef<{
url: string | null;
isLocal: boolean;
@@ -174,7 +169,7 @@ export const FileInput: React.FC<FileInputProps> = ({
// Create a new preview URL for immediate feedback
const newPreviewUrl = URL.createObjectURL(file);
- setPreviewUrl(newPreviewUrl);
+ setPreviewUrl(ImageUpload.ImageUrl.make(newPreviewUrl));
setIsLocalPreview(true);
previousPreviewRef.current = {
@@ -252,7 +247,6 @@ export const FileInput: React.FC<FileInputProps> = ({
<SignedImageUrl
image={previewUrl}
name="File preview"
- type={type}
letterClass="text-lg"
className="size-full"
/>
diff --git a/apps/web/components/SignedImageUrl.tsx b/apps/web/components/SignedImageUrl.tsx
index 4d389930a..fc63f0488 100644
--- a/apps/web/components/SignedImageUrl.tsx
+++ b/apps/web/components/SignedImageUrl.tsx
@@ -1,62 +1,23 @@
-"use client";
-
import { Avatar } from "@cap/ui";
-import { useSignedImageUrl } from "@/lib/use-signed-image-url";
+import type { ImageUpload } from "@cap/web-domain";
interface SignedImageUrlProps {
- image: string | null | undefined;
+ image: ImageUpload.ImageUrl | null | undefined;
name: string;
- type: "user" | "organization";
className?: string;
letterClass?: string;
- noFallback?: boolean;
}
-/**
- * Component that handles both S3 keys (via RPC) and direct URLs
- * For S3 keys, it uses the RPC hook to get signed URLs
- * For direct URLs, it uses them as-is
- */
export function SignedImageUrl({
image,
name,
- type,
className,
letterClass,
}: SignedImageUrlProps) {
- const { data: signedUrl, isLoading } = useSignedImageUrl(image, type);
-
- function isS3Key(imageKeyOrUrl: string | null | undefined): boolean {
- if (!imageKeyOrUrl) return false;
- return (
- imageKeyOrUrl.startsWith("users/") ||
- imageKeyOrUrl.startsWith("organizations/")
- );
- }
-
- // If it's an S3 key, use the signed URL from RPC
- // If it's a direct URL, use it as-is
- const imageUrl = isS3Key(image) ? (signedUrl as string | null) : image;
-
- if (isS3Key(image) && isLoading) {
- return (
- <div
- className={className}
- style={{
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- backgroundColor: "var(--gray-5)",
- borderRadius: "50%",
- }}
- />
- );
- }
-
return (
<Avatar
name={name}
- imageUrl={imageUrl ?? undefined}
+ imageUrl={image}
className={className}
letterClass={letterClass}
/>
diff --git a/apps/web/components/forms/NewOrganization.tsx b/apps/web/components/forms/NewOrganization.tsx
index 01d39e8b6..dfa956f9e 100644
--- a/apps/web/components/forms/NewOrganization.tsx
+++ b/apps/web/components/forms/NewOrganization.tsx
@@ -103,7 +103,6 @@ export const NewOrganization: React.FC<NewOrganizationProps> = (props) => {
<FileInput
id="icon"
name="icon"
- type="organization"
notDraggingClassName="hover:bg-gray-3"
onChange={setSelectedFile}
disabled={isUploading}
diff --git a/apps/web/components/forms/server.ts b/apps/web/components/forms/server.ts
index 2c9f677e3..212152640 100644
--- a/apps/web/components/forms/server.ts
+++ b/apps/web/components/forms/server.ts
@@ -8,9 +8,8 @@ import {
organizations,
users,
} from "@cap/database/schema";
-import { serverEnv } from "@cap/env";
import { S3Buckets } from "@cap/web-backend";
-import { Organisation, type User } from "@cap/web-domain";
+import { ImageUpload, Organisation, type User } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { Effect, Option } from "effect";
import { revalidatePath } from "next/cache";
@@ -42,7 +41,7 @@ export async function createOrganization(formData: FormData) {
id: Organisation.OrganisationId;
ownerId: User.UserId;
name: string;
- iconUrl?: string;
+ iconUrl?: ImageUpload.ImageUrlOrKey;
} = {
id: organizationId,
ownerId: user.id,
@@ -64,7 +63,9 @@ export async function createOrganization(formData: FormData) {
// Create a unique file key
const fileExtension = iconFile.name.split(".").pop();
- const fileKey = `organizations/${organizationId}/icon-${Date.now()}.${fileExtension}`;
+ const fileKey = ImageUpload.ImageKey.make(
+ `organizations/${organizationId}/icon-${Date.now()}.${fileExtension}`,
+ );
try {
await Effect.gen(function* () {
diff --git a/apps/web/components/pages/_components/ComparePlans.tsx b/apps/web/components/pages/_components/ComparePlans.tsx
index 2d39931d4..82977169a 100644
--- a/apps/web/components/pages/_components/ComparePlans.tsx
+++ b/apps/web/components/pages/_components/ComparePlans.tsx
@@ -1,13 +1,12 @@
"use client";
import { Button } from "@cap/ui";
-import { userIsPro } from "@cap/utils";
import { faCheckCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { clsx } from "clsx";
-import { use, useMemo, useRef, useState } from "react";
+import { useMemo, useRef, useState } from "react";
import { toast } from "sonner";
-import { useAuthContext } from "@/app/Layout/AuthContext";
+import { useCurrentUser } from "@/app/Layout/AuthContext";
import { useStripeContext } from "@/app/Layout/StripeContext";
import {
CommercialArt,
@@ -90,7 +89,7 @@ const PlanIcon = ({
export const ComparePlans = () => {
const commercialArtRef = useRef<CommercialArtRef>(null);
const proArtRef = useRef<ProArtRef>(null);
- const auth = use(useAuthContext().user);
+ const user = useCurrentUser();
const [proLoading, setProLoading] = useState(false);
const [guestLoading, setGuestLoading] = useState(false);
const [commercialLoading, setCommercialLoading] = useState(false);
@@ -99,11 +98,11 @@ export const ComparePlans = () => {
// Check if user is already pro or any loading state is active
const isDisabled = useMemo(
() =>
- (auth?.email && userIsPro(auth)) ||
+ (user?.email && user.isPro) ||
proLoading ||
guestLoading ||
commercialLoading,
- [auth, proLoading, guestLoading, commercialLoading],
+ [user, proLoading, guestLoading, commercialLoading],
);
const plans: Plan[] = useMemo(
diff --git a/apps/web/lib/folder.ts b/apps/web/lib/folder.ts
index 35ec3fcc2..f7222e446 100644
--- a/apps/web/lib/folder.ts
+++ b/apps/web/lib/folder.ts
@@ -11,12 +11,13 @@ import {
videos,
videoUploads,
} from "@cap/database/schema";
-import { Database } from "@cap/web-backend";
-import type { Organisation, Space, Video } from "@cap/web-domain";
+import { Database, ImageUploads } from "@cap/web-backend";
+import type { ImageUpload, Organisation, Space, Video } from "@cap/web-domain";
import { CurrentUser, Folder } from "@cap/web-domain";
import { and, desc, eq } from "drizzle-orm";
import { sql } from "drizzle-orm/sql";
import { Effect } from "effect";
+import { runPromise } from "./server";
export const getFolderById = Effect.fn(function* (folderId: string) {
if (!folderId) throw new Error("Folder ID is required");
@@ -163,6 +164,7 @@ export const getVideosByFolderId = Effect.fn(function* (
) {
if (!folderId) throw new Error("Folder ID is required");
const db = yield* Database;
+ const imageUploads = yield* ImageUploads;
const videoData = yield* db.use((db) =>
db
@@ -177,7 +179,11 @@ export const getVideosByFolderId = Effect.fn(function* (
totalComments: sql<number>`COUNT(DISTINCT CASE WHEN ${comments.type} = 'text' THEN ${comments.id} END)`,
totalReactions: sql<number>`COUNT(DISTINCT CASE WHEN ${comments.type} = 'emoji' THEN ${comments.id} END)`,
sharedOrganizations: sql<
- { id: string; name: string; iconUrl: string }[]
+ {
+ id: string;
+ name: string;
+ iconUrl: ImageUpload.ImageUrlOrKey | null;
+ }[]
>`
COALESCE(
JSON_ARRAYAGG(
@@ -242,35 +248,48 @@ export const getVideosByFolderId = Effect.fn(function* (
const sharedSpacesMap = yield* getSharedSpacesForVideos(videoIds);
// Process the video data to match the expected format
- const processedVideoData = videoData.map((video) => {
- return {
- id: video.id as Video.VideoId, // Cast to Video.VideoId branded type
- ownerId: video.ownerId,
- name: video.name,
- createdAt: video.createdAt,
- public: video.public,
- totalComments: video.totalComments,
- totalReactions: video.totalReactions,
- sharedOrganizations: Array.isArray(video.sharedOrganizations)
- ? video.sharedOrganizations.filter(
- (organization) => organization.id !== null,
- )
- : [],
- sharedSpaces: Array.isArray(sharedSpacesMap[video.id])
- ? sharedSpacesMap[video.id]
- : [],
- ownerName: video.ownerName ?? "",
- metadata: video.metadata as
- | {
- customCreatedAt?: string;
- [key: string]: unknown;
- }
- | undefined,
- hasPassword: video.hasPassword,
- hasActiveUpload: video.hasActiveUpload,
- foldersData: [], // Empty array since videos in a folder don't need folder data
- };
- });
+ const processedVideoData = yield* Effect.all(
+ videoData.map(
+ Effect.fn(function* (video) {
+ return {
+ id: video.id as Video.VideoId, // Cast to Video.VideoId branded type
+ ownerId: video.ownerId,
+ name: video.name,
+ createdAt: video.createdAt,
+ public: video.public,
+ totalComments: video.totalComments,
+ totalReactions: video.totalReactions,
+ sharedOrganizations: yield* Effect.all(
+ (video.sharedOrganizations ?? [])
+ .filter((organization) => organization.id !== null)
+ .map(
+ Effect.fn(function* (org) {
+ return {
+ ...org,
+ iconUrl: org.iconUrl
+ ? yield* imageUploads.resolveImageUrl(org.iconUrl)
+ : null,
+ };
+ }),
+ ),
+ ),
+ sharedSpaces: Array.isArray(sharedSpacesMap[video.id])
+ ? sharedSpacesMap[video.id]
+ : [],
+ ownerName: video.ownerName ?? "",
+ metadata: video.metadata as
+ | {
+ customCreatedAt?: string;
+ [key: string]: unknown;
+ }
+ | undefined,
+ hasPassword: video.hasPassword,
+ hasActiveUpload: video.hasActiveUpload,
+ foldersData: [], // Empty array since videos in a folder don't need folder data
+ };
+ }),
+ ),
+ );
return processedVideoData;
});
diff --git a/apps/web/lib/server.ts b/apps/web/lib/server.ts
index 58c85cf4e..2fefb15f0 100644
--- a/apps/web/lib/server.ts
+++ b/apps/web/lib/server.ts
@@ -7,10 +7,13 @@ import {
Database,
Folders,
HttpAuthMiddlewareLive,
+ ImageUploads,
+ Organisations,
OrganisationsPolicy,
S3Buckets,
Spaces,
SpacesPolicy,
+ Users,
Videos,
VideosPolicy,
VideosRepo,
@@ -105,7 +108,10 @@ export const Dependencies = Layer.mergeAll(
SpacesPolicy.Default,
OrganisationsPolicy.Default,
Spaces.Default,
+ Users.Default,
+ Organisations.Default,
AwsCredentials.Default,
+ ImageUploads.Default,
WorkflowRpcLive,
layerTracer,
).pipe(
diff --git a/apps/web/lib/use-signed-image-url.ts b/apps/web/lib/use-signed-image-url.ts
deleted file mode 100644
index d5d3caf3a..000000000
--- a/apps/web/lib/use-signed-image-url.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { Effect } from "effect";
-import { useEffectQuery } from "@/lib/EffectRuntime";
-import { withRpc } from "./Rpcs";
-
-/**
- * Hook to get signed URL for an S3 image key
- * @param key - S3 key
- * @param type - Type of image ("user" or "organization")
- * @returns Object with url, isLoading, error
- */
-export function useSignedImageUrl(
- key: string | null | undefined,
- type: "user" | "organization",
-) {
- return useEffectQuery({
- queryKey: ["signedImageUrl", key, type],
- queryFn: () => {
- if (!key) {
- return Effect.succeed(key);
- }
-
- return withRpc((rpc) => rpc.GetSignedImageUrl({ key, type }))
- .pipe(Effect.map((result) => result.url))
- .pipe(Effect.catchTag("InternalError", () => Effect.succeed(null)));
- },
- enabled: !!key,
- });
-}
diff --git a/infra/sst.config.ts b/infra/sst.config.ts
index 6747adb5c..0437ff74b 100644
--- a/infra/sst.config.ts
+++ b/infra/sst.config.ts
@@ -135,6 +135,8 @@ export default $config({
};
})();
+ const oidcSub = (environment: "production" | "preview" | "staging") =>
+ `owner:${VERCEL_TEAM_SLUG}:project:${VERCEL_PROJECT_NAME}:environment:${environment}`;
const vercelAwsAccessRole = new aws.iam.Role("VercelAWSAccessRole", {
assumeRolePolicy: {
Version: "2012-10-17",
@@ -150,9 +152,10 @@ export default $config({
[`${oidc.url}:aud`]: oidc.aud,
},
StringLike: {
- [`${oidc.url}:sub`]: [
- `owner:${VERCEL_TEAM_SLUG}:project:*:environment:${stage.variant === "git-branch" ? "preview" : stage.variant}`,
- ],
+ [`${oidc.url}:sub`]:
+ stage.variant === "production"
+ ? [oidcSub("production")]
+ : [oidcSub("preview"), oidcSub("staging")],
},
},
},
diff --git a/packages/database/auth/drizzle-adapter.ts b/packages/database/auth/drizzle-adapter.ts
index ec3f596a5..7edaca2ea 100644
--- a/packages/database/auth/drizzle-adapter.ts
+++ b/packages/database/auth/drizzle-adapter.ts
@@ -1,5 +1,5 @@
import { STRIPE_AVAILABLE, stripe } from "@cap/utils";
-import { Organisation, User } from "@cap/web-domain";
+import { type ImageUpload, Organisation, User } from "@cap/web-domain";
import { and, eq } from "drizzle-orm";
import type { MySql2Database } from "drizzle-orm/mysql2";
import type { Adapter } from "next-auth/adapters";
@@ -179,11 +179,14 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
const row = rows[0];
return row?.users ?? null;
},
- async updateUser({ id, ...userData }) {
+ async updateUser({ id, image, ...userData }) {
if (!id) throw new Error("User not found");
await db
.update(users)
- .set(userData)
+ .set({
+ ...userData,
+ image: image as ImageUpload.ImageUrlOrKey | null,
+ })
.where(eq(users.id, User.UserId.make(id)));
const rows = await db
.select()
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index dd2353062..6a94501f2 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -1,6 +1,7 @@
import type {
Comment,
Folder,
+ ImageUpload,
Organisation,
S3Bucket,
Space,
@@ -64,7 +65,7 @@ export const users = mysqlTable(
lastName: varchar("lastName", { length: 255 }),
email: varchar("email", { length: 255 }).unique().notNull(),
emailVerified: timestamp("emailVerified"),
- image: varchar("image", { length: 255 }),
+ image: varchar("image", { length: 255 }).$type<ImageUpload.ImageUrlOrKey>(),
stripeCustomerId: varchar("stripeCustomerId", { length: 255 }),
stripeSubscriptionId: varchar("stripeSubscriptionId", {
length: 255,
@@ -190,7 +191,9 @@ export const organizations = mysqlTable(
disableTranscript?: boolean;
disableComments?: boolean;
}>(),
- iconUrl: varchar("iconUrl", { length: 1024 }),
+ iconUrl: varchar("iconUrl", {
+ length: 1024,
+ }).$type<ImageUpload.ImageUrlOrKey>(),
createdAt: timestamp("createdAt").notNull().defaultNow(),
updatedAt: timestamp("updatedAt").notNull().defaultNow().onUpdateNow(),
workosOrganizationId: varchar("workosOrganizationId", { length: 255 }),
@@ -599,7 +602,9 @@ export const spaces = mysqlTable(
.notNull()
.$type<Organisation.OrganisationId>(),
createdById: nanoId("createdById").notNull().$type<User.UserId>(),
- iconUrl: varchar("iconUrl", { length: 255 }),
+ iconUrl: varchar("iconUrl", {
+ length: 255,
+ }).$type<ImageUpload.ImageUrlOrKey>(),
description: varchar("description", { length: 1000 }),
createdAt: timestamp("createdAt").notNull().defaultNow(),
updatedAt: timestamp("updatedAt").notNull().defaultNow().onUpdateNow(),
diff --git a/packages/utils/package.json b/packages/utils/package.json
index 4f201dfe5..cc9536c5f 100644
--- a/packages/utils/package.json
+++ b/packages/utils/package.json
@@ -1,8 +1,9 @@
{
"name": "@cap/utils",
"type": "module",
- "main": "./src/index.ts",
- "types": "./src/index.ts",
+ "exports": {
+ ".": "./src/index.ts"
+ },
"scripts": {
"typecheck": "tsc -b",
"build": "tsdown"
diff --git a/packages/web-backend/src/Auth.ts b/packages/web-backend/src/Auth.ts
index df27be4a3..fed3808c2 100644
--- a/packages/web-backend/src/Auth.ts
+++ b/packages/web-backend/src/Auth.ts
@@ -4,6 +4,7 @@ import {
CurrentUser,
type DatabaseError,
HttpAuthMiddleware,
+ type ImageUpload,
} from "@cap/web-domain";
import { HttpApiError, HttpServerRequest } from "@effect/platform";
import * as Dz from "drizzle-orm";
@@ -34,6 +35,20 @@ export const getCurrentUser = Effect.gen(function* () {
);
}).pipe(Effect.withSpan("getCurrentUser"));
+export const makeCurrentUser = (
+ user: Option.Option.Value<Effect.Effect.Success<typeof getCurrentUser>>,
+) =>
+ CurrentUser.of({
+ id: user.id,
+ email: user.email,
+ activeOrganizationId: user.activeOrganizationId,
+ iconUrlOrKey: Option.fromNullable(user.image),
+ });
+
+export const makeCurrentUserLayer = (
+ user: Option.Option.Value<Effect.Effect.Success<typeof getCurrentUser>>,
+) => Layer.succeed(CurrentUser, makeCurrentUser(user));
+
export const HttpAuthMiddlewareLive = Layer.effect(
HttpAuthMiddleware,
Effect.gen(function* () {
@@ -66,11 +81,7 @@ export const HttpAuthMiddlewareLive = Layer.effect(
}
return yield* user.pipe(
- Option.map((user) => ({
- id: user.id,
- email: user.email,
- activeOrganizationId: user.activeOrganizationId,
- })),
+ Option.map(makeCurrentUser),
Effect.catchTag(
"NoSuchElementException",
() => new HttpApiError.Unauthorized(),
@@ -98,16 +109,9 @@ export const provideOptionalAuth = <A, E, R>(
yield* Effect.log(`Providing auth for user ${user.value.id}`);
return yield* user.pipe(
- Option.map((user) =>
- CurrentUser.context({
- id: user.id,
- email: user.email,
- activeOrganizationId: user.activeOrganizationId,
- }),
- ),
Option.match({
onNone: () => app,
- onSome: (ctx) => app.pipe(Effect.provide(ctx)),
+ onSome: (user) => app.pipe(Effect.provide(makeCurrentUserLayer(user))),
}),
);
});
diff --git a/packages/web-backend/src/Database.ts b/packages/web-backend/src/Database.ts
index 9564098db..25eacdccc 100644
--- a/packages/web-backend/src/Database.ts
+++ b/packages/web-backend/src/Database.ts
@@ -2,10 +2,12 @@ import { db } from "@cap/database";
import { DatabaseError } from "@cap/web-domain";
import { Effect } from "effect";
+export type DbClient = ReturnType<typeof db>;
+
export class Database extends Effect.Service<Database>()("Database", {
effect: Effect.gen(function* () {
return {
- use: <T>(cb: (_: ReturnType<typeof db>) => Promise<T>) =>
+ use: <T>(cb: (_: DbClient) => Promise<T>) =>
Effect.tryPromise({
try: () => cb(db()),
catch: (cause) => new DatabaseError({ cause }),
diff --git a/packages/web-backend/src/Folders/FoldersRpcs.ts b/packages/web-backend/src/Folders/FoldersRpcs.ts
index 46ed37529..7a1882ba1 100644
--- a/packages/web-backend/src/Folders/FoldersRpcs.ts
+++ b/packages/web-backend/src/Folders/FoldersRpcs.ts
@@ -30,7 +30,7 @@ export const FolderRpcsLive = Folder.FolderRpcs.toLayer(
FolderUpdate: (data) =>
folders
- .update(data.id, data)
+ .update(data)
.pipe(
Effect.catchTag(
"DatabaseError",
diff --git a/packages/web-backend/src/Folders/index.ts b/packages/web-backend/src/Folders/index.ts
index 5c3933890..7adb23843 100644
--- a/packages/web-backend/src/Folders/index.ts
+++ b/packages/web-backend/src/Folders/index.ts
@@ -129,12 +129,11 @@ export class Folders extends Effect.Service<Folders>()("Folders", {
}),
update: Effect.fn("Folders.update")(function* (
- folderId: Folder.FolderId,
data: Folder.FolderUpdate,
) {
const folder = yield* (yield* repo
- .getById(folderId)
- .pipe(Policy.withPolicy(policy.canEdit(folderId)))).pipe(
+ .getById(data.id)
+ .pipe(Policy.withPolicy(policy.canEdit(data.id)))).pipe(
Effect.catchTag(
"NoSuchElementException",
() => new Folder.NotFoundError(),
@@ -145,7 +144,7 @@ export class Folders extends Effect.Service<Folders>()("Folders", {
if (data.parentId && Option.isSome(data.parentId)) {
const parentId = data.parentId.value;
// Check that we're not creating an immediate circular reference
- if (parentId === folderId)
+ if (parentId === data.id)
return yield* new Folder.RecursiveDefinitionError();
const parentFolder = yield* repo
@@ -167,7 +166,7 @@ export class Folders extends Effect.Service<Folders>()("Folders", {
// Check for circular references in the folder hierarchy
let currentParentId = parentFolder.parentId;
while (currentParentId) {
- if (currentParentId === folderId)
+ if (currentParentId === data.id)
return yield* new Folder.RecursiveDefinitionError();
const parentId = currentParentId;
@@ -192,7 +191,7 @@ export class Folders extends Effect.Service<Folders>()("Folders", {
? Option.getOrNull(data.parentId)
: undefined,
})
- .where(Dz.eq(Db.folders.id, folderId)),
+ .where(Dz.eq(Db.folders.id, data.id)),
);
}),
};
diff --git a/packages/web-backend/src/ImageUploads/index.ts b/packages/web-backend/src/ImageUploads/index.ts
new file mode 100644
index 000000000..6038c7619
--- /dev/null
+++ b/packages/web-backend/src/ImageUploads/index.ts
@@ -0,0 +1,67 @@
+import { ImageUpload } from "@cap/web-domain";
+import { Effect, Option } from "effect";
+
+import { Database, type DbClient } from "../Database";
+import { S3Buckets } from "../S3Buckets";
+
+export class ImageUploads extends Effect.Service<ImageUploads>()(
+ "ImageUploads",
+ {
+ effect: Effect.gen(function* () {
+ const s3Buckets = yield* S3Buckets;
+ const db = yield* Database;
+
+ const [s3] = yield* s3Buckets.getBucketAccess();
+
+ const applyUpdate = Effect.fn("ImageUploads.applyUpdate")(
+ function* (args: {
+ payload: ImageUpload.ImageUpdatePayload;
+ existing: Option.Option<ImageUpload.ImageUrlOrKey>;
+ keyPrefix: string;
+ update: (
+ db: DbClient,
+ urlOrKey: ImageUpload.ImageKey | null,
+ ) => Promise<unknown>;
+ }) {
+ yield* Option.match(args.payload, {
+ onSome: Effect.fn(function* (image) {
+ const fileExtension = image.fileName.split(".").pop() || "jpg";
+ const s3Key = ImageUpload.ImageKey.make(
+ `${args.keyPrefix}/${Date.now()}.${fileExtension}`,
+ );
+
+ yield* s3.putObject(s3Key, image.data, {
+ contentType: image.contentType,
+ });
+
+ yield* db.use((db) => args.update(db, s3Key));
+ }),
+ onNone: () => db.use((db) => args.update(db, null)),
+ });
+
+ yield* args.existing.pipe(
+ Option.andThen((iconKeyOrUrl) =>
+ ImageUpload.extractFileKey(iconKeyOrUrl, s3.isPathStyle),
+ ),
+ Option.map(s3.deleteObject),
+ Effect.transposeOption,
+ );
+ },
+ );
+
+ const resolveImageUrl = Effect.fn(function* (
+ urlOrKey: ImageUpload.ImageUrlOrKey,
+ ) {
+ const key = ImageUpload.extractFileKey(urlOrKey, s3.isPathStyle);
+
+ return yield* Option.match(key, {
+ onSome: (key) => s3.getSignedObjectUrl(key),
+ onNone: () => Effect.succeed(urlOrKey),
+ }).pipe(Effect.map(ImageUpload.ImageUrl.make));
+ });
+
+ return { applyUpdate, resolveImageUrl };
+ }),
+ dependencies: [S3Buckets.Default, Database.Default],
+ },
+) {}
diff --git a/packages/web-backend/src/Organisations/OrganisationsRpcs.ts b/packages/web-backend/src/Organisations/OrganisationsRpcs.ts
new file mode 100644
index 000000000..330f74e64
--- /dev/null
+++ b/packages/web-backend/src/Organisations/OrganisationsRpcs.ts
@@ -0,0 +1,19 @@
+import { InternalError, Organisation } from "@cap/web-domain";
+import { Effect } from "effect";
+import { Organisations } from ".";
+
+export const OrganisationsRpcsLive = Organisation.OrganisationRpcs.toLayer(
+ Effect.gen(function* () {
+ const orgs = yield* Organisations;
+
+ return {
+ OrganisationUpdate: (data) =>
+ orgs.update(data).pipe(
+ Effect.catchTags({
+ DatabaseError: () => new InternalError({ type: "database" }),
+ S3Error: () => new InternalError({ type: "s3" }),
+ }),
+ ),
+ };
+ }),
+);
diff --git a/packages/web-backend/src/Organisations/index.ts b/packages/web-backend/src/Organisations/index.ts
new file mode 100644
index 000000000..6022ec1a7
--- /dev/null
+++ b/packages/web-backend/src/Organisations/index.ts
@@ -0,0 +1,61 @@
+import * as Db from "@cap/database/schema";
+import { type ImageUpload, Organisation, Policy } from "@cap/web-domain";
+import * as Dz from "drizzle-orm";
+import { Array, Effect, Option } from "effect";
+
+import { Database } from "../Database";
+import { ImageUploads } from "../ImageUploads";
+import { S3Buckets } from "../S3Buckets";
+import { OrganisationsPolicy } from "./OrganisationsPolicy";
+
+export class Organisations extends Effect.Service<Organisations>()(
+ "Organisations",
+ {
+ effect: Effect.gen(function* () {
+ const db = yield* Database;
+ const policy = yield* OrganisationsPolicy;
+ const imageUploads = yield* ImageUploads;
+
+ const update = Effect.fn("Organisations.update")(function* (
+ payload: Organisation.OrganisationUpdate,
+ ) {
+ const organisation = yield* db
+ .use((db) =>
+ db
+ .select()
+ .from(Db.organizations)
+ .where(Dz.eq(Db.organizations.id, payload.id)),
+ )
+ .pipe(
+ Effect.flatMap(Array.get(0)),
+ Effect.catchTag(
+ "NoSuchElementException",
+ () => new Organisation.NotFoundError(),
+ ),
+ Policy.withPolicy(policy.isOwner(payload.id)),
+ );
+
+ if (payload.image) {
+ yield* imageUploads.applyUpdate({
+ payload: payload.image,
+ existing: Option.fromNullable(organisation.iconUrl),
+ keyPrefix: `organizations/${organisation.id}`,
+ update: (db, urlOrKey) =>
+ db
+ .update(Db.organizations)
+ .set({ iconUrl: urlOrKey })
+ .where(Dz.eq(Db.organizations.id, organisation.id)),
+ });
+ }
+ });
+
+ return { update };
+ }),
+ dependencies: [
+ ImageUploads.Default,
+ S3Buckets.Default,
+ Database.Default,
+ OrganisationsPolicy.Default,
+ ],
+ },
+) {}
diff --git a/packages/web-backend/src/Rpcs.ts b/packages/web-backend/src/Rpcs.ts
index 10bd49404..0b4fb0632 100644
--- a/packages/web-backend/src/Rpcs.ts
+++ b/packages/web-backend/src/Rpcs.ts
@@ -5,9 +5,10 @@ import {
} from "@cap/web-domain";
import { Effect, Layer, Option } from "effect";
-import { getCurrentUser } from "./Auth.ts";
+import { getCurrentUser, makeCurrentUser } from "./Auth.ts";
import { Database } from "./Database.ts";
import { FolderRpcsLive } from "./Folders/FoldersRpcs.ts";
+import { OrganisationsRpcsLive } from "./Organisations/OrganisationsRpcs.ts";
import { UsersRpcsLive } from "./Users/UsersRpcs.ts";
import { VideosRpcsLive } from "./Videos/VideosRpcs.ts";
@@ -15,6 +16,7 @@ export const RpcsLive = Layer.mergeAll(
VideosRpcsLive,
FolderRpcsLive,
UsersRpcsLive,
+ OrganisationsRpcsLive,
);
export const RpcAuthMiddlewareLive = Layer.effect(
@@ -29,12 +31,7 @@ export const RpcAuthMiddlewareLive = Layer.effect(
Effect.flatMap(
Option.match({
onNone: () => new UnauthenticatedError(),
- onSome: (user) =>
- Effect.succeed({
- id: user.id,
- email: user.email,
- activeOrganizationId: user.activeOrganizationId,
- }),
+ onSome: (user) => Effect.succeed(makeCurrentUser(user)),
}),
),
),
diff --git a/packages/web-backend/src/S3Buckets/S3BucketAccess.ts b/packages/web-backend/src/S3Buckets/S3BucketAccess.ts
index 2c7cd698d..5338c7dbe 100644
--- a/packages/web-backend/src/S3Buckets/S3BucketAccess.ts
+++ b/packages/web-backend/src/S3Buckets/S3BucketAccess.ts
@@ -38,6 +38,7 @@ export const createS3BucketAccess = Effect.gen(function* () {
const provider = yield* S3BucketClientProvider;
return {
bucketName: provider.bucket,
+ isPathStyle: provider.isPathStyle,
getSignedObjectUrl: (key: string) =>
wrapS3Promise(
provider.getPublic.pipe(
diff --git a/packages/web-backend/src/S3Buckets/S3BucketClientProvider.ts b/packages/web-backend/src/S3Buckets/S3BucketClientProvider.ts
index 37c612a93..35871b972 100644
--- a/packages/web-backend/src/S3Buckets/S3BucketClientProvider.ts
+++ b/packages/web-backend/src/S3Buckets/S3BucketClientProvider.ts
@@ -9,5 +9,6 @@ export class S3BucketClientProvider extends Context.Tag(
getInternal: Effect.Effect<S3Client, Cause.UnknownException>;
getPublic: Effect.Effect<S3Client, Cause.UnknownException>;
bucket: string;
+ isPathStyle: boolean;
}
>() {}
diff --git a/packages/web-backend/src/S3Buckets/index.ts b/packages/web-backend/src/S3Buckets/index.ts
index 240e3c8a5..67f53cabd 100644
--- a/packages/web-backend/src/S3Buckets/index.ts
+++ b/packages/web-backend/src/S3Buckets/index.ts
@@ -45,7 +45,20 @@ export class S3Buckets extends Effect.Service<S3Buckets>()("S3Buckets", {
requestStreamBufferSize: 16 * 1024,
});
- const createBucketClient = async (bucket: S3Bucket.S3Bucket) => {
+ const endpointIsPathStyle = (endpoint: string, bucket: string) => {
+ try {
+ const { hostname } = new URL(endpoint);
+ return !hostname.startsWith(`${bucket}.s3`);
+ } catch {
+ // If endpoint can't be parsed as a URL, fall back to false for safety
+ return true;
+ }
+ };
+
+ const createBucketClient = async (
+ bucket: S3Bucket.S3Bucket,
+ name: string,
+ ) => {
const endpoint = await (() => {
const v = bucket.endpoint.pipe(Option.getOrUndefined);
if (!v) return;
@@ -61,7 +74,7 @@ export class S3Buckets extends Effect.Service<S3Buckets>()("S3Buckets", {
},
forcePathStyle:
Option.fromNullable(endpoint).pipe(
- Option.map((e) => e.endsWith("s3.amazonaws.com")),
+ Option.map((e) => endpointIsPathStyle(e, name)),
Option.getOrNull,
) ?? true,
useArnRegion: false,
@@ -126,6 +139,7 @@ export class S3Buckets extends Effect.Service<S3Buckets>()("S3Buckets", {
getInternal: Effect.succeed(createDefaultClient(true)),
getPublic: Effect.succeed(createDefaultClient(false)),
bucket: defaultConfigs.bucket,
+ isPathStyle: defaultConfigs.forcePathStyle,
});
return Option.match(cloudfrontBucketAccess, {
@@ -139,12 +153,14 @@ export class S3Buckets extends Effect.Service<S3Buckets>()("S3Buckets", {
decrypt(customBucket.name),
);
+ const client = yield* Effect.promise(() =>
+ createBucketClient(customBucket, bucket),
+ );
const provider = Layer.succeed(S3BucketClientProvider, {
- getInternal: Effect.promise(() =>
- createBucketClient(customBucket),
- ),
- getPublic: Effect.promise(() => createBucketClient(customBucket)),
+ getInternal: Effect.succeed(client),
+ getPublic: Effect.succeed(client),
bucket,
+ isPathStyle: client.config.forcePathStyle ?? true,
});
return yield* createS3BucketAccess.pipe(Effect.provide(provider));
@@ -156,9 +172,9 @@ export class S3Buckets extends Effect.Service<S3Buckets>()("S3Buckets", {
return {
getBucketAccess: Effect.fn("S3Buckets.getBucketAccess")(function* (
- bucketId: Option.Option<S3Bucket.S3BucketId>,
+ bucketId?: Option.Option<S3Bucket.S3BucketId>,
) {
- const customBucket = yield* bucketId.pipe(
+ const customBucket = yield* (bucketId ?? Option.none()).pipe(
Option.map(repo.getById),
Effect.transposeOption,
Effect.map(Option.flatten),
diff --git a/packages/web-backend/src/Users/UsersOnboarding.ts b/packages/web-backend/src/Users/UsersOnboarding.ts
index 69e908e1b..90abc007a 100644
--- a/packages/web-backend/src/Users/UsersOnboarding.ts
+++ b/packages/web-backend/src/Users/UsersOnboarding.ts
@@ -5,14 +5,14 @@ import * as Dz from "drizzle-orm";
import { Effect, Option } from "effect";
import { Database } from "../Database.ts";
-import { S3Buckets } from "../S3Buckets/index.ts";
+import { ImageUploads } from "../ImageUploads/index.ts";
export class UsersOnboarding extends Effect.Service<UsersOnboarding>()(
"UsersOnboarding",
{
effect: Effect.gen(function* () {
const db = yield* Database;
- const s3Buckets = yield* S3Buckets;
+ const imageUploads = yield* ImageUploads;
return {
welcome: Effect.fn("Onboarding.welcome")(function* (data: {
@@ -164,7 +164,11 @@ export class UsersOnboarding extends Effect.Service<UsersOnboarding>()(
if (data.organizationIcon) {
const organizationIcon = data.organizationIcon;
const uploadEffect = Effect.gen(function* () {
- const { data: fileData, contentType } = organizationIcon;
+ const {
+ data: fileData,
+ contentType,
+ fileName,
+ } = organizationIcon;
const allowedExt = new Map<string, string>([
["image/png", "png"],
["image/jpeg", "jpg"],
@@ -174,21 +178,21 @@ export class UsersOnboarding extends Effect.Service<UsersOnboarding>()(
const fileExtension = allowedExt.get(contentType);
if (!fileExtension)
throw new Error("Unsupported icon content type");
- const fileKey = `organizations/${finalOrganizationId}/icon-${Date.now()}.${fileExtension}`;
- const [bucket] = yield* s3Buckets.getBucketAccess(
- Option.none(),
- );
-
- yield* bucket.putObject(fileKey, fileData, { contentType });
- const iconUrl = yield* bucket.getSignedObjectUrl(fileKey);
-
- yield* db.use((db) =>
- db
- .update(Db.organizations)
- .set({ iconUrl })
- .where(Dz.eq(Db.organizations.id, finalOrganizationId)),
- );
+ yield* imageUploads.applyUpdate({
+ payload: Option.some({
+ data: fileData,
+ contentType,
+ fileName,
+ }),
+ existing: Option.none(),
+ keyPrefix: `organizations/${finalOrganizationId}`,
+ update: (db, iconUrl) =>
+ db
+ .update(Db.organizations)
+ .set({ iconUrl })
+ .where(Dz.eq(Db.organizations.id, finalOrganizationId)),
+ });
}).pipe(
Effect.catchAll((error) =>
Effect.logError("Failed to upload organization icon", error),
@@ -313,6 +317,6 @@ export class UsersOnboarding extends Effect.Service<UsersOnboarding>()(
}),
};
}),
- dependencies: [Database.Default, S3Buckets.Default],
+ dependencies: [Database.Default, ImageUploads.Default],
},
) {}
diff --git a/packages/web-backend/src/Users/UsersRpcs.ts b/packages/web-backend/src/Users/UsersRpcs.ts
index f04182718..102db93b5 100644
--- a/packages/web-backend/src/Users/UsersRpcs.ts
+++ b/packages/web-backend/src/Users/UsersRpcs.ts
@@ -1,17 +1,15 @@
-import * as Db from "@cap/database/schema";
-import { InternalError, Organisation, User } from "@cap/web-domain";
-import * as Dz from "drizzle-orm";
-import { Effect, Layer, Option } from "effect";
+import { InternalError, User } from "@cap/web-domain";
+import { Effect, Layer } from "effect";
+
import { Database } from "../Database";
-import { S3Buckets } from "../S3Buckets";
-import { parseImageKey } from "./helpers";
+import { Users } from ".";
import { UsersOnboarding } from "./UsersOnboarding";
export const UsersRpcsLive = User.UserRpcs.toLayer(
Effect.gen(function* () {
const onboarding = yield* UsersOnboarding;
- const s3Buckets = yield* S3Buckets;
- const db = yield* Database;
+ const users = yield* Users;
+
return {
UserCompleteOnboardingStep: (payload) =>
Effect.gen(function* () {
@@ -44,120 +42,12 @@ export const UsersRpcsLive = User.UserRpcs.toLayer(
() => new InternalError({ type: "database" }),
),
),
- GetSignedImageUrl: (payload: {
- key: string;
- type: "user" | "organization";
- }) =>
- Effect.gen(function* () {
- const [bucket] = yield* s3Buckets.getBucketAccess(Option.none());
- const url = yield* bucket.getSignedObjectUrl(payload.key);
- return { url };
- }).pipe(
- Effect.catchTag("S3Error", () => new InternalError({ type: "s3" })),
- Effect.catchTag(
- "DatabaseError",
- () => new InternalError({ type: "database" }),
- ),
- Effect.catchAll(() => new InternalError({ type: "unknown" })),
- ),
- UploadImage: (payload) =>
- Effect.gen(function* () {
- const oldS3KeyOption = yield* parseImageKey(
- payload.oldImageKey,
- payload.type,
- );
- const [bucket] = yield* s3Buckets.getBucketAccess(Option.none());
-
- // Delete old image if it exists and is valid
- if (Option.isSome(oldS3KeyOption)) {
- yield* bucket.deleteObject(oldS3KeyOption.value);
- }
-
- // Generate new S3 key
- const timestamp = Date.now();
- const fileExtension = payload.fileName.split(".").pop() || "jpg";
- const s3Key = `${payload.type}s/${payload.entityId}/${timestamp}.${fileExtension}`;
-
- // Upload new image
- const buffer = Buffer.from(payload.data);
- yield* bucket.putObject(s3Key, buffer, {
- contentType: payload.contentType,
- });
-
- // Update database
- if (payload.type === "user") {
- yield* db.use((db) =>
- db
- .update(Db.users)
- .set({ image: s3Key })
- .where(Dz.eq(Db.users.id, User.UserId.make(payload.entityId))),
- );
- } else {
- yield* db.use((db) =>
- db
- .update(Db.organizations)
- .set({ iconUrl: s3Key })
- .where(
- Dz.eq(
- Db.organizations.id,
- Organisation.OrganisationId.make(payload.entityId),
- ),
- ),
- );
- }
-
- return { key: s3Key };
- }).pipe(
- Effect.catchTag("S3Error", () => new InternalError({ type: "s3" })),
- Effect.catchTag(
- "DatabaseError",
- () => new InternalError({ type: "database" }),
- ),
- Effect.catchAll(() => new InternalError({ type: "unknown" })),
- ),
- RemoveImage: (payload) =>
- Effect.gen(function* () {
- const s3KeyOption = yield* parseImageKey(
- payload.imageKey,
- payload.type,
- );
- const [bucket] = yield* s3Buckets.getBucketAccess(Option.none());
-
- // Only delete if we have a valid S3 key
- if (Option.isSome(s3KeyOption)) {
- yield* bucket.deleteObject(s3KeyOption.value);
- }
-
- // Update database
- if (payload.type === "user") {
- yield* db.use((db) =>
- db
- .update(Db.users)
- .set({ image: null })
- .where(Dz.eq(Db.users.id, User.UserId.make(payload.entityId))),
- );
- } else {
- yield* db.use((db) =>
- db
- .update(Db.organizations)
- .set({ iconUrl: null })
- .where(
- Dz.eq(
- Db.organizations.id,
- Organisation.OrganisationId.make(payload.entityId),
- ),
- ),
- );
- }
-
- return { success: true as const };
- }).pipe(
- Effect.catchTag("S3Error", () => new InternalError({ type: "s3" })),
- Effect.catchTag(
- "DatabaseError",
- () => new InternalError({ type: "database" }),
- ),
- Effect.catchAll(() => new InternalError({ type: "unknown" })),
+ UserUpdate: (data) =>
+ users.update(data).pipe(
+ Effect.catchTags({
+ DatabaseError: () => new InternalError({ type: "database" }),
+ S3Error: () => new InternalError({ type: "s3" }),
+ }),
),
};
}),
diff --git a/packages/web-backend/src/Users/helpers.ts b/packages/web-backend/src/Users/helpers.ts
deleted file mode 100644
index 4bb71240c..000000000
--- a/packages/web-backend/src/Users/helpers.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { InternalError } from "@cap/web-domain";
-import { Effect, Option } from "effect";
-import * as path from "path";
-
-export const parseImageKey = (
- imageKey: string | null | undefined,
- expectedType: "user" | "organization",
-): Effect.Effect<Option.Option<string>, InternalError> =>
- Effect.gen(function* () {
- // Return None if no image key provided
- if (!imageKey || imageKey.trim() === "") {
- return Option.none();
- }
-
- let s3Key = imageKey;
- if (imageKey.startsWith("http://") || imageKey.startsWith("https://")) {
- const url = new URL(imageKey);
- const raw = url.pathname.startsWith("/")
- ? url.pathname.slice(1)
- : url.pathname;
- const decoded = decodeURIComponent(raw);
- const normalized = path.posix.normalize(decoded);
- if (normalized.includes("..")) {
- return yield* Effect.fail(new InternalError({ type: "unknown" }));
- }
- s3Key = normalized;
- }
-
- const expectedPrefix =
- expectedType === "user" ? "users/" : "organizations/";
- if (!s3Key.startsWith(expectedPrefix)) {
- return Option.none();
- }
-
- return Option.some(s3Key);
- });
diff --git a/packages/web-backend/src/Users/index.ts b/packages/web-backend/src/Users/index.ts
index a31bcd919..16b6c04f2 100644
--- a/packages/web-backend/src/Users/index.ts
+++ b/packages/web-backend/src/Users/index.ts
@@ -1,10 +1,34 @@
+import * as Db from "@cap/database/schema";
+import { CurrentUser, type User } from "@cap/web-domain";
+import * as Dz from "drizzle-orm";
import { Effect } from "effect";
-import { Database } from "../Database";
+
+import { ImageUploads } from "../ImageUploads";
export class Users extends Effect.Service<Users>()("Users", {
effect: Effect.gen(function* () {
- yield* Database;
+ const imageUploads = yield* ImageUploads;
+
+ const update = Effect.fn("Users.update")(function* (
+ payload: User.UserUpdate,
+ ) {
+ const user = yield* CurrentUser;
+
+ if (payload.image) {
+ yield* imageUploads.applyUpdate({
+ payload: payload.image,
+ existing: user.iconUrlOrKey,
+ keyPrefix: `users/${user.id}`,
+ update: (db, urlOrKey) =>
+ db
+ .update(Db.users)
+ .set({ image: urlOrKey })
+ .where(Dz.eq(Db.users.id, user.id)),
+ });
+ }
+ });
- return {};
+ return { update };
}),
+ dependencies: [ImageUploads.Default],
}) {}
diff --git a/packages/web-backend/src/index.ts b/packages/web-backend/src/index.ts
index 2a5e1f003..b3b4382dc 100644
--- a/packages/web-backend/src/index.ts
+++ b/packages/web-backend/src/index.ts
@@ -3,12 +3,15 @@ export * from "./Aws.ts";
export * from "./Database.ts";
export { Folders } from "./Folders/index.ts";
export { HttpLive } from "./Http/Live.ts";
+export { ImageUploads } from "./ImageUploads/index.ts";
export * from "./Loom/index.ts";
+export { Organisations } from "./Organisations/index.ts";
export { OrganisationsPolicy } from "./Organisations/OrganisationsPolicy.ts";
export * from "./Rpcs.ts";
export { S3Buckets } from "./S3Buckets/index.ts";
export { Spaces } from "./Spaces/index.ts";
export { SpacesPolicy } from "./Spaces/SpacesPolicy.ts";
+export { Users } from "./Users/index.ts";
export { Videos } from "./Videos/index.ts";
export { VideosPolicy } from "./Videos/VideosPolicy.ts";
export { VideosRepo } from "./Videos/VideosRepo.ts";
diff --git a/packages/web-domain/src/Authentication.ts b/packages/web-domain/src/Authentication.ts
index 66d157828..d4a32b271 100644
--- a/packages/web-domain/src/Authentication.ts
+++ b/packages/web-domain/src/Authentication.ts
@@ -1,9 +1,9 @@
import { HttpApiError, HttpApiMiddleware } from "@effect/platform";
import { RpcMiddleware } from "@effect/rpc";
-import { Context, Schema } from "effect";
+import { Context, type Option, Schema } from "effect";
import { InternalError } from "./Errors.ts";
-import type { Organisation, User } from "./index.ts";
+import type { ImageUpload, Organisation, User } from "./index.ts";
export class CurrentUser extends Context.Tag("CurrentUser")<
CurrentUser,
@@ -11,6 +11,7 @@ export class CurrentUser extends Context.Tag("CurrentUser")<
id: User.UserId;
email: string;
activeOrganizationId: Organisation.OrganisationId;
+ iconUrlOrKey: Option.Option<ImageUpload.ImageUrlOrKey>;
}
>() {}
diff --git a/packages/web-domain/src/ImageUpload.ts b/packages/web-domain/src/ImageUpload.ts
new file mode 100644
index 000000000..a84300ef5
--- /dev/null
+++ b/packages/web-domain/src/ImageUpload.ts
@@ -0,0 +1,45 @@
+import { Option, Schema } from "effect";
+
+export const ImageKey = Schema.String.pipe(Schema.brand("ImageKey"));
+export type ImageKey = typeof ImageKey.Type;
+
+export const ImageUrl = Schema.String.pipe(Schema.brand("ImageUrl"));
+export type ImageUrl = typeof ImageUrl.Type;
+
+export type ImageUrlOrKey = ImageUrl | ImageKey;
+
+/**
+ * Extracts an S3 file key from an image key or URL.
+ * In some cases we can have image URLs from Google, so these need to be filtered out.
+ */
+export const extractFileKey = (
+ iconKeyOrURL: ImageUrlOrKey,
+ urlIsPathStyle: boolean,
+): Option.Option<ImageKey> => {
+ try {
+ const { pathname, origin } = new URL(iconKeyOrURL);
+
+ if (origin === "https://lh3.googleusercontent.com") return Option.none();
+
+ let key = pathname.slice(1);
+
+ if (urlIsPathStyle) {
+ key = key.split("/").slice(1).join("/");
+ }
+
+ if (!key.trim()) return Option.none();
+
+ return Option.some(ImageKey.make(key));
+ } catch {
+ return Option.some(ImageKey.make(iconKeyOrURL));
+ }
+};
+
+export const ImageUpdatePayload = Schema.Option(
+ Schema.Struct({
+ data: Schema.Uint8ArrayFromBase64,
+ contentType: Schema.String,
+ fileName: Schema.String,
+ }),
+);
+export type ImageUpdatePayload = typeof ImageUpdatePayload.Type;
diff --git a/packages/web-domain/src/Organisation.ts b/packages/web-domain/src/Organisation.ts
index c2c74e825..6818a6997 100644
--- a/packages/web-domain/src/Organisation.ts
+++ b/packages/web-domain/src/Organisation.ts
@@ -1,5 +1,18 @@
+import { HttpApiSchema } from "@effect/platform";
+import { Rpc, RpcGroup } from "@effect/rpc";
import { Schema } from "effect";
+import { RpcAuthMiddleware } from "./Authentication.ts";
+import { InternalError } from "./Errors.ts";
+import { ImageUpdatePayload } from "./ImageUpload.ts";
+import { PolicyDeniedError } from "./Policy.ts";
+
+export class NotFoundError extends Schema.TaggedError<NotFoundError>()(
+ "OrgNotFoundError",
+ {},
+ HttpApiSchema.annotations({ status: 404 }),
+) {}
+
export const OrganisationId = Schema.String.pipe(
Schema.brand("OrganisationId"),
);
@@ -9,3 +22,16 @@ export class Organisation extends Schema.Class<Organisation>("Organisation")({
id: OrganisationId,
name: Schema.String,
}) {}
+
+export const OrganisationUpdate = Schema.Struct({
+ id: OrganisationId,
+ image: Schema.optional(ImageUpdatePayload),
+});
+export type OrganisationUpdate = Schema.Schema.Type<typeof OrganisationUpdate>;
+
+export class OrganisationRpcs extends RpcGroup.make(
+ Rpc.make("OrganisationUpdate", {
+ payload: OrganisationUpdate,
+ error: Schema.Union(InternalError, PolicyDeniedError, NotFoundError),
+ }).middleware(RpcAuthMiddleware),
+) {}
diff --git a/packages/web-domain/src/Rpcs.ts b/packages/web-domain/src/Rpcs.ts
index 1d890286d..f4106430c 100644
--- a/packages/web-domain/src/Rpcs.ts
+++ b/packages/web-domain/src/Rpcs.ts
@@ -1,7 +1,13 @@
import { RpcGroup } from "@effect/rpc";
import { FolderRpcs } from "./Folder.ts";
+import { OrganisationRpcs } from "./Organisation.ts";
import { UserRpcs } from "./User.ts";
import { VideoRpcs } from "./Video.ts";
-export const Rpcs = RpcGroup.make().merge(VideoRpcs, FolderRpcs, UserRpcs);
+export const Rpcs = RpcGroup.make().merge(
+ VideoRpcs,
+ FolderRpcs,
+ UserRpcs,
+ OrganisationRpcs,
+);
diff --git a/packages/web-domain/src/User.ts b/packages/web-domain/src/User.ts
index 5b88c828e..d11d3a2e7 100644
--- a/packages/web-domain/src/User.ts
+++ b/packages/web-domain/src/User.ts
@@ -3,11 +3,19 @@ import { Schema } from "effect";
import { RpcAuthMiddleware } from "./Authentication.ts";
import { InternalError } from "./Errors.ts";
+import { ImageUpdatePayload } from "./ImageUpload.ts";
import { OrganisationId } from "./Organisation.ts";
+import { PolicyDeniedError } from "./Policy.ts";
export const UserId = Schema.String.pipe(Schema.brand("UserId"));
export type UserId = typeof UserId.Type;
+export const UserUpdate = Schema.Struct({
+ id: UserId,
+ image: Schema.optional(ImageUpdatePayload),
+});
+export type UserUpdate = Schema.Schema.Type<typeof UserUpdate>;
+
export const OnboardingStepPayload = Schema.Union(
Schema.Struct({
step: Schema.Literal("welcome"),
@@ -68,57 +76,14 @@ export const OnboardingStepResult = Schema.Union(
}),
);
-export const GetSignedImageUrlPayload = Schema.Struct({
- key: Schema.String,
- type: Schema.Literal("user", "organization"),
-});
-
-export const GetSignedImageUrlResult = Schema.Struct({
- url: Schema.String,
-});
-
-export const UploadImagePayload = Schema.Struct({
- data: Schema.Uint8Array,
- contentType: Schema.String,
- fileName: Schema.String,
- type: Schema.Literal("user", "organization"),
- entityId: Schema.String,
- oldImageKey: Schema.optional(Schema.NullOr(Schema.String)),
-});
-
-export const UploadImageResult = Schema.Struct({
- key: Schema.String,
-});
-
-export const RemoveImagePayload = Schema.Struct({
- imageKey: Schema.String,
- type: Schema.Literal("user", "organization"),
- entityId: Schema.String,
-});
-
-export const RemoveImageResult = Schema.Struct({
- success: Schema.Literal(true),
-});
-
export class UserRpcs extends RpcGroup.make(
Rpc.make("UserCompleteOnboardingStep", {
payload: OnboardingStepPayload,
success: OnboardingStepResult,
error: InternalError,
}).middleware(RpcAuthMiddleware),
- Rpc.make("GetSignedImageUrl", {
- payload: GetSignedImageUrlPayload,
- success: GetSignedImageUrlResult,
- error: InternalError,
- }).middleware(RpcAuthMiddleware),
- Rpc.make("UploadImage", {
- payload: UploadImagePayload,
- success: UploadImageResult,
- error: InternalError,
- }).middleware(RpcAuthMiddleware),
- Rpc.make("RemoveImage", {
- payload: RemoveImagePayload,
- success: RemoveImageResult,
- error: InternalError,
+ Rpc.make("UserUpdate", {
+ payload: UserUpdate,
+ error: Schema.Union(InternalError, PolicyDeniedError),
}).middleware(RpcAuthMiddleware),
) {}
diff --git a/packages/web-domain/src/index.ts b/packages/web-domain/src/index.ts
index e3ca89154..1b1a55303 100644
--- a/packages/web-domain/src/index.ts
+++ b/packages/web-domain/src/index.ts
@@ -5,6 +5,7 @@ export * from "./Errors.ts";
export * from "./Errors.ts";
export * as Folder from "./Folder.ts";
export * as Http from "./Http/index.ts";
+export * as ImageUpload from "./ImageUpload.ts";
export * as Loom from "./Loom.ts";
export * as Organisation from "./Organisation.ts";
export * from "./Organisation.ts";