Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: New custom date input + new video metadata defined

Richie McIlroyc761aa658cda
diff --git a/apps/web/app/api/video/date/route.ts b/apps/web/app/api/video/date/route.ts
new file mode 100644
index 000000000..cf0c49127
--- /dev/null
+++ b/apps/web/app/api/video/date/route.ts
@@ -0,0 +1,71 @@
+import { type NextRequest } from "next/server";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { videos } from "@cap/database/schema";
+import { db } from "@cap/database";
+import { eq } from "drizzle-orm";
+import { headers } from "next/headers";
+import { rateLimitMiddleware } from "@/utils/helpers";
+import { VideoMetadata } from "@cap/database/types";
+
+export async function handlePut(request: NextRequest) {
+ const user = await getCurrentUser();
+ const { date, videoId } = await request.json();
+ const userId = user?.id as string;
+
+ if (!user || !date || !videoId) {
+ console.error("Missing required data in /api/video/date/route.ts");
+ return Response.json({ error: true }, { status: 401 });
+ }
+
+ const query = await db.select().from(videos).where(eq(videos.id, videoId));
+
+ if (query.length === 0) {
+ return Response.json({ error: true }, { status: 401 });
+ }
+
+ const video = query[0];
+ if (!video) {
+ return Response.json({ error: true }, { status: 401 });
+ }
+
+ if (video.ownerId !== userId) {
+ return Response.json({ error: true }, { status: 401 });
+ }
+
+ try {
+ const newDate = new Date(date);
+ const currentDate = new Date();
+
+ // Prevent future dates
+ if (newDate > currentDate) {
+ return Response.json(
+ { error: "Cannot set a date in the future" },
+ { status: 400 }
+ );
+ }
+
+ // Store the custom date in the metadata field
+ const currentMetadata = video.metadata as VideoMetadata || {};
+ const updatedMetadata: VideoMetadata = {
+ ...currentMetadata,
+ customCreatedAt: newDate.toISOString(),
+ };
+
+ await db
+ .update(videos)
+ .set({
+ metadata: updatedMetadata,
+ })
+ .where(eq(videos.id, videoId));
+
+ return Response.json(true, { status: 200 });
+ } catch (error) {
+ console.error("Error updating video date:", error);
+ return Response.json({ error: true }, { status: 500 });
+ }
+}
+
+export const PUT = (request: NextRequest) => {
+ const headersList = headers();
+ return rateLimitMiddleware(10, handlePut(request), headersList);
+};
\ No newline at end of file
diff --git a/apps/web/app/dashboard/caps/Caps.tsx b/apps/web/app/dashboard/caps/Caps.tsx
index b34de2555..ef7a2072c 100644
--- a/apps/web/app/dashboard/caps/Caps.tsx
+++ b/apps/web/app/dashboard/caps/Caps.tsx
@@ -7,6 +7,7 @@ import { CapCard } from "./components/CapCard";
import { EmptyCapState } from "./components/EmptyCapState";
import { CapPagination } from "./components/CapPagination";
import { apiClient } from "@/utils/web-api";
+import { VideoMetadata } from "@cap/database/types";
type VideoData = {
id: string;
@@ -17,6 +18,7 @@ type VideoData = {
totalReactions: number;
sharedSpaces: { id: string; name: string }[];
ownerName: string;
+ metadata?: VideoMetadata;
}[];
export const Caps = ({
diff --git a/apps/web/app/dashboard/caps/components/CapCard.tsx b/apps/web/app/dashboard/caps/components/CapCard.tsx
index 131ce4a8f..cfc93c6f7 100644
--- a/apps/web/app/dashboard/caps/components/CapCard.tsx
+++ b/apps/web/app/dashboard/caps/components/CapCard.tsx
@@ -10,6 +10,8 @@ import { SharingDialog } from "@/app/dashboard/caps/components/SharingDialog";
import { useRouter } from "next/navigation"; // Add this import
import { serverEnv, clientEnv, NODE_ENV } from "@cap/env";
import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayout";
+import { VideoMetadata } from "@cap/database/types";
+
interface CapCardProps {
cap: {
id: string;
@@ -20,6 +22,7 @@ interface CapCardProps {
totalReactions: number;
sharedSpaces: { id: string; name: string }[];
ownerName: string;
+ metadata?: VideoMetadata;
};
analytics: number;
onDelete: (videoId: string) => Promise<void>;
@@ -34,10 +37,19 @@ export const CapCard: React.FC<CapCardProps> = ({
userId,
userSpaces,
}) => {
+ const effectiveDate = cap.metadata?.customCreatedAt
+ ? new Date(cap.metadata.customCreatedAt)
+ : cap.createdAt;
+
const [isEditing, setIsEditing] = useState(false);
const [title, setTitle] = useState(cap.name);
const [isSharingDialogOpen, setIsSharingDialogOpen] = useState(false);
const [sharedSpaces, setSharedSpaces] = useState(cap.sharedSpaces);
+ const [isDateEditing, setIsDateEditing] = useState(false);
+ const [dateValue, setDateValue] = useState(
+ moment(effectiveDate).format("YYYY-MM-DD HH:mm:ss")
+ );
+ const [showFullDate, setShowFullDate] = useState(false);
const router = useRouter();
const { activeSpace } = useSharedContext();
@@ -113,6 +125,72 @@ export const CapCard: React.FC<CapCardProps> = ({
router.refresh(); // Add this line to refresh the page
};
+ const handleDateClick = () => {
+ if (userId === cap.ownerId) {
+ if (!isDateEditing) {
+ setIsDateEditing(true);
+ }
+ } else {
+ setShowFullDate(!showFullDate);
+ }
+ };
+
+ const handleDateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ setDateValue(e.target.value);
+ };
+
+ const handleDateBlur = async () => {
+ const isValidDate = moment(dateValue).isValid();
+
+ if (!isValidDate) {
+ toast.error("Invalid date format. Please use YYYY-MM-DD HH:mm:ss");
+ setDateValue(moment(effectiveDate).format("YYYY-MM-DD HH:mm:ss"));
+ setIsDateEditing(false);
+ return;
+ }
+
+ const selectedDate = moment(dateValue);
+ const currentDate = moment();
+
+ if (selectedDate.isAfter(currentDate)) {
+ toast.error("Cannot set a date in the future");
+ setDateValue(moment(effectiveDate).format("YYYY-MM-DD HH:mm:ss"));
+ setIsDateEditing(false);
+ return;
+ }
+
+ const response = await fetch(
+ `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/video/date`,
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ date: moment(dateValue).toISOString(),
+ videoId: cap.id,
+ }),
+ }
+ );
+
+ if (!response.ok) {
+ toast.error("Failed to update date - please try again.");
+ return;
+ }
+
+ toast.success("Video date updated");
+ setIsDateEditing(false);
+ router.refresh();
+ };
+
+ const handleDateKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleDateBlur();
+ } else if (e.key === "Escape") {
+ setDateValue(moment(effectiveDate).format("YYYY-MM-DD HH:mm:ss"));
+ setIsDateEditing(false);
+ }
+ };
+
return (
<div
className="rounded-xl border-[1px] border-gray-200 relative"
@@ -136,7 +214,7 @@ export const CapCard: React.FC<CapCardProps> = ({
/>
</a>
<div className="flex flex-col p-4">
- <div className="mb-2">
+ <div className="mb-1">
<div>
<span className="text-[0.875rem] leading-[1.25rem] text-gray-400">
{isOwner ? cap.ownerName : cap.sharedSpaces[0]?.name}
@@ -154,11 +232,11 @@ export const CapCard: React.FC<CapCardProps> = ({
onBlur={handleTitleBlur}
onKeyDown={handleTitleKeyDown}
autoFocus
- className="text-[0.875rem] leading-[1.25rem] text-gray-500 font-medium box-border"
+ className="text-[0.875rem] leading-[1.25rem] text-gray-500 font-medium box-border mb-1"
/>
) : (
<p
- className="text-[0.875rem] leading-[1.25rem] text-gray-500 font-medium"
+ className="text-[0.875rem] leading-[1.25rem] text-gray-500 font-medium mb-1"
onClick={() => {
if (userId === cap.ownerId) {
setIsEditing(true);
@@ -168,15 +246,33 @@ export const CapCard: React.FC<CapCardProps> = ({
{title}
</p>
)}
- <p>
- <span
- className="text-[0.875rem] leading-[1.25rem] text-gray-400"
- data-tooltip-id={cap.id + "_createdAt"}
- data-tooltip-content={`Cap created at ${cap.createdAt}`}
- >
- {moment(cap.createdAt).fromNow()}
- </span>
- <Tooltip id={cap.id + "_createdAt"} />
+ <p className="mb-1">
+ {isDateEditing ? (
+ <div className="flex items-center">
+ <input
+ type="text"
+ value={dateValue}
+ onChange={handleDateChange}
+ onBlur={handleDateBlur}
+ onKeyDown={handleDateKeyDown}
+ autoFocus
+ className="text-[0.875rem] leading-[1.25rem] text-gray-400 bg-transparent focus:outline-none"
+ placeholder="YYYY-MM-DD HH:mm:ss"
+ />
+ </div>
+ ) : (
+ <span
+ className="text-[0.875rem] leading-[1.25rem] text-gray-400 cursor-pointer flex items-center"
+ onClick={handleDateClick}
+ data-tooltip-id={cap.id + "_createdAt"}
+ data-tooltip-content={`Cap created at ${effectiveDate}`}
+ >
+ {showFullDate
+ ? moment(effectiveDate).format("YYYY-MM-DD HH:mm:ss")
+ : moment(effectiveDate).fromNow()}
+ </span>
+ )}
+ <Tooltip className="z-50" id={cap.id + "_createdAt"} />
</p>
<CapCardAnalytics
capId={cap.id}
diff --git a/apps/web/app/dashboard/caps/page.tsx b/apps/web/app/dashboard/caps/page.tsx
index 272bec771..de61d4dca 100644
--- a/apps/web/app/dashboard/caps/page.tsx
+++ b/apps/web/app/dashboard/caps/page.tsx
@@ -52,6 +52,7 @@ export default async function CapsPage({
ownerId: videos.ownerId,
name: videos.name,
createdAt: videos.createdAt,
+ metadata: videos.metadata,
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)`,
sharedSpaces: sql<{ id: string; name: string }[]>`
@@ -66,6 +67,12 @@ export default async function CapsPage({
)
`,
ownerName: users.name,
+ effectiveDate: sql<string>`
+ COALESCE(
+ JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.customCreatedAt')),
+ ${videos.createdAt}
+ )
+ `,
})
.from(videos)
.leftJoin(comments, eq(videos.id, comments.videoId))
@@ -78,9 +85,15 @@ export default async function CapsPage({
videos.ownerId,
videos.name,
videos.createdAt,
+ videos.metadata,
users.name
)
- .orderBy(desc(videos.createdAt))
+ .orderBy(
+ desc(sql`COALESCE(
+ JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.customCreatedAt')),
+ ${videos.createdAt}
+ )`)
+ )
.limit(limit)
.offset(offset);
@@ -93,11 +106,21 @@ export default async function CapsPage({
.leftJoin(spaceMembers, eq(spaces.id, spaceMembers.spaceId))
.where(eq(spaceMembers.userId, userId));
- const processedVideoData = videoData.map((video) => ({
- ...video,
- sharedSpaces: video.sharedSpaces.filter((space) => space.id !== null),
- ownerName: video.ownerName ?? "",
- }));
+ const processedVideoData = videoData.map((video) => {
+ const { effectiveDate, ...videoWithoutEffectiveDate } = video;
+
+ return {
+ ...videoWithoutEffectiveDate,
+ sharedSpaces: video.sharedSpaces.filter((space) => space.id !== null),
+ ownerName: video.ownerName ?? "",
+ metadata: video.metadata as
+ | {
+ customCreatedAt?: string;
+ [key: string]: any;
+ }
+ | undefined,
+ };
+ });
return (
<Caps
diff --git a/apps/web/app/dashboard/shared-caps/SharedCaps.tsx b/apps/web/app/dashboard/shared-caps/SharedCaps.tsx
index adbf1e4f6..5bc503478 100644
--- a/apps/web/app/dashboard/shared-caps/SharedCaps.tsx
+++ b/apps/web/app/dashboard/shared-caps/SharedCaps.tsx
@@ -5,6 +5,7 @@ import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayou
import { SharedCapCard } from "./components/SharedCapCard";
import { EmptySharedCapState } from "./components/EmptySharedCapState";
import { CapPagination } from "../caps/components/CapPagination";
+import { VideoMetadata } from "@cap/database/types";
type SharedVideoData = {
id: string;
@@ -14,6 +15,7 @@ type SharedVideoData = {
totalComments: number;
totalReactions: number;
ownerName: string | null;
+ metadata?: VideoMetadata;
}[];
export const SharedCaps = ({
diff --git a/apps/web/app/dashboard/shared-caps/components/SharedCapCard.tsx b/apps/web/app/dashboard/shared-caps/components/SharedCapCard.tsx
index 156bec6ee..5ae361166 100644
--- a/apps/web/app/dashboard/shared-caps/components/SharedCapCard.tsx
+++ b/apps/web/app/dashboard/shared-caps/components/SharedCapCard.tsx
@@ -5,6 +5,8 @@ import moment from "moment";
import { Tooltip } from "react-tooltip";
import { serverEnv, clientEnv, NODE_ENV } from "@cap/env";
import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayout";
+import { VideoMetadata } from "@cap/database/types";
+
interface SharedCapCardProps {
cap: {
id: string;
@@ -14,6 +16,7 @@ interface SharedCapCardProps {
totalComments: number;
totalReactions: number;
ownerName: string | null;
+ metadata?: VideoMetadata;
};
analytics: number;
spaceName: string;
@@ -24,6 +27,11 @@ export const SharedCapCard: React.FC<SharedCapCardProps> = ({
analytics,
spaceName,
}) => {
+ // Get the effective date (custom or original)
+ const effectiveDate = cap.metadata?.customCreatedAt
+ ? new Date(cap.metadata.customCreatedAt)
+ : cap.createdAt;
+
const [isEditing, setIsEditing] = useState(false);
const [title, setTitle] = useState(cap.name);
const { activeSpace } = useSharedContext();
@@ -76,9 +84,9 @@ export const SharedCapCard: React.FC<SharedCapCardProps> = ({
<span
className="text-[0.875rem] leading-[1.25rem] text-gray-400"
data-tooltip-id={cap.id + "_createdAt"}
- data-tooltip-content={`Cap created at ${cap.createdAt}`}
+ data-tooltip-content={`Cap created at ${effectiveDate}`}
>
- {moment(cap.createdAt).fromNow()}
+ {moment(effectiveDate).fromNow()}
</span>
<Tooltip id={cap.id + "_createdAt"} />
</p>
diff --git a/apps/web/app/dashboard/shared-caps/page.tsx b/apps/web/app/dashboard/shared-caps/page.tsx
index d2c08c32c..b3294e830 100644
--- a/apps/web/app/dashboard/shared-caps/page.tsx
+++ b/apps/web/app/dashboard/shared-caps/page.tsx
@@ -62,9 +62,16 @@ export default async function SharedCapsPage({
ownerId: videos.ownerId,
name: videos.name,
createdAt: videos.createdAt,
+ metadata: videos.metadata,
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)`,
ownerName: users.name,
+ effectiveDate: sql<string>`
+ COALESCE(
+ JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.customCreatedAt')),
+ ${videos.createdAt}
+ )
+ `,
})
.from(sharedVideos)
.innerJoin(videos, eq(sharedVideos.videoId, videos.id))
@@ -76,14 +83,36 @@ export default async function SharedCapsPage({
videos.ownerId,
videos.name,
videos.createdAt,
+ videos.metadata,
users.name
)
- .orderBy(desc(videos.createdAt))
+ .orderBy(
+ desc(sql`COALESCE(
+ JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.customCreatedAt')),
+ ${videos.createdAt}
+ )`)
+ )
.limit(limit)
.offset(offset);
+ // Process the data to clean it up and remove the temporary effectiveDate field
+ const processedSharedVideoData = sharedVideoData.map((video) => {
+ const { effectiveDate, ...videoWithoutEffectiveDate } = video;
+
+ return {
+ ...videoWithoutEffectiveDate,
+ ownerName: video.ownerName ?? null,
+ metadata: video.metadata as
+ | {
+ customCreatedAt?: string;
+ [key: string]: any;
+ }
+ | undefined,
+ };
+ });
+
console.log("sharedVideoData:");
- console.log(sharedVideoData);
+ console.log(processedSharedVideoData);
// Debug: Check if there are any shared videos for this space
const debugSharedVideos = await db
@@ -115,7 +144,7 @@ export default async function SharedCapsPage({
return (
<SharedCaps
- data={sharedVideoData}
+ data={processedSharedVideoData}
count={totalCount}
activeSpaceId={activeSpaceId}
/>
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index 5bff02c02..7c1e2f04e 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -14,6 +14,7 @@ import {
} from "drizzle-orm/mysql-core";
import { relations } from "drizzle-orm/relations";
import { nanoIdLength } from "./helpers";
+import { VideoMetadata } from "./types";
const nanoId = customType<{ data: string; notNull: true }>({
dataType() {
@@ -198,7 +199,7 @@ export const videos = mysqlTable(
awsRegion: varchar("awsRegion", { length: 255 }),
awsBucket: varchar("awsBucket", { length: 255 }),
bucket: nanoIdNullable("bucket"),
- metadata: json("metadata"),
+ metadata: json("metadata").$type<VideoMetadata>(),
public: boolean("public").notNull().default(true),
videoStartTime: varchar("videoStartTime", { length: 255 }),
audioStartTime: varchar("audioStartTime", { length: 255 }),
diff --git a/packages/database/types/index.ts b/packages/database/types/index.ts
new file mode 100644
index 000000000..d5079365c
--- /dev/null
+++ b/packages/database/types/index.ts
@@ -0,0 +1 @@
+export * from './metadata';
\ No newline at end of file
diff --git a/packages/database/types/metadata.ts b/packages/database/types/metadata.ts
new file mode 100644
index 000000000..3ee362794
--- /dev/null
+++ b/packages/database/types/metadata.ts
@@ -0,0 +1,29 @@
+/**
+ * Type definitions for JSON metadata fields
+ */
+
+/**
+ * Video metadata structure
+ */
+export interface VideoMetadata {
+ /**
+ * Custom created date that can be edited by the user
+ * This overrides the display of the actual createdAt timestamp
+ */
+ customCreatedAt?: string;
+ [key: string]: any;
+}
+
+/**
+ * Space metadata structure
+ */
+export interface SpaceMetadata {
+ [key: string]: any;
+}
+
+/**
+ * User metadata structure
+ */
+export interface UserMetadata {
+ [key: string]: any;
+}
\ No newline at end of file