From dfd4e230b97a563c1a0a91180b243bad09850ed6 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 19 May 2025 17:15:30 +0100 Subject: [PATCH 01/19] Use mp4 links for social embeds (#555) --- apps/web/app/s/[videoId]/page.tsx | 58 +++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx index ae3b9a6a63f..0029893df16 100644 --- a/apps/web/app/s/[videoId]/page.tsx +++ b/apps/web/app/s/[videoId]/page.tsx @@ -80,6 +80,31 @@ export async function generateMetadata( height: 630, }, ], + videos: [ + { + url: new URL( + `/api/playlist?userId=${video.ownerId}&videoId=${video.id}`, + buildEnv.NEXT_PUBLIC_WEB_URL + ).toString(), + width: 1280, + height: 720, + type: "video/mp4", + }, + ], + }, + twitter: { + card: "player", + player: new URL( + `/s/${videoId}`, + buildEnv.NEXT_PUBLIC_WEB_URL + ).toString(), + playerWidth: 1280, + playerHeight: 720, + playerStream: new URL( + `/api/playlist?userId=${video.ownerId}&videoId=${video.id}`, + buildEnv.NEXT_PUBLIC_WEB_URL + ).toString(), + playerStreamContentType: "video/mp4", }, }; } @@ -98,6 +123,39 @@ export async function generateMetadata( height: 630, }, ], + videos: [ + { + url: new URL( + `/api/playlist?userId=${video.ownerId}&videoId=${video.id}`, + buildEnv.NEXT_PUBLIC_WEB_URL + ).toString(), + width: 1280, + height: 720, + type: "video/mp4", + }, + ], + }, + twitter: { + card: "player", + player: new URL( + `/s/${videoId}`, + buildEnv.NEXT_PUBLIC_WEB_URL + ).toString(), + playerWidth: 1280, + playerHeight: 720, + playerStream: new URL( + `/api/playlist?userId=${video.ownerId}&videoId=${video.id}`, + buildEnv.NEXT_PUBLIC_WEB_URL + ).toString(), + playerStreamContentType: "video/mp4", + title: video.name + " | Cap Recording", + description: "Watch this video on Cap", + images: [ + new URL( + `/api/video/og?videoId=${videoId}`, + buildEnv.NEXT_PUBLIC_WEB_URL + ).toString(), + ], }, }; } From 2840de9d9452f770c22f827712f13958f1b001fc Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 19 May 2025 17:31:43 +0100 Subject: [PATCH 02/19] feat: Add referrer to headers and check for robots.txt --- apps/web/app/robots.ts | 48 +++++++++++++++++++++++++++++++----------- apps/web/middleware.ts | 22 +++++++++++++++++-- 2 files changed, 56 insertions(+), 14 deletions(-) diff --git a/apps/web/app/robots.ts b/apps/web/app/robots.ts index c0d4e869882..a3d037afb84 100644 --- a/apps/web/app/robots.ts +++ b/apps/web/app/robots.ts @@ -1,10 +1,43 @@ import { seoPages } from "@/lib/seo-pages"; import { MetadataRoute } from "next"; +import { headers } from "next/headers"; export const revalidate = 0; export default function robots(): MetadataRoute.Robots { const seoPageSlugs = Object.keys(seoPages); + const headersList = headers(); + const referrer = headersList.get("x-referrer") || ""; + + const allowedReferrers = [ + "x.com", + "facebook.com", + "fb.com", + "linkedin.com", + "slack.com", + "notion.so", + "reddit.com", + "youtube.com", + "quora.com", + "t.co" + ]; + + const isAllowedReferrer = allowedReferrers.some(domain => + referrer.includes(domain) + ); + + const disallowPaths = [ + "/dashboard", + "/login", + "/invite", + "/onboarding", + "/record", + "/home", + ]; + + if (!isAllowedReferrer) { + disallowPaths.push("/s/*"); + } return { rules: [ @@ -13,21 +46,12 @@ export default function robots(): MetadataRoute.Robots { allow: [ "/", "/blog/", - // Dynamically add all SEO pages ...seoPageSlugs.map((slug) => `/${slug}`), + ...(isAllowedReferrer ? ["/s/*"] : []), ], - // Be more specific about what we're disallowing under /s/ - disallow: [ - "/dashboard", - "/s/*", - "/login", - "/invite", - "/onboarding", - "/record", - "/home", - ], + disallow: disallowPaths, }, ], sitemap: "https://cap.so/sitemap.xml", }; -} +} \ No newline at end of file diff --git a/apps/web/middleware.ts b/apps/web/middleware.ts index 6a906a23034..450aaea7d5e 100644 --- a/apps/web/middleware.ts +++ b/apps/web/middleware.ts @@ -81,6 +81,15 @@ export async function middleware(request: NextRequest) { sameSite: "strict", maxAge: 3600, // Cache for 1 hour }); + + // Get the pathname and referrer + const { pathname } = request.nextUrl; + const referrer = request.headers.get('referer') || ''; + + // Add custom headers to check in generateMetadata + response.headers.set('x-pathname', pathname); + response.headers.set('x-referrer', referrer); + return response; } catch (error) { console.error("Error in middleware:", error); @@ -89,5 +98,14 @@ export async function middleware(request: NextRequest) { } export const config = { - matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"], -}; + matcher: [ + /* + * Match all request paths except for the ones starting with: + * - api (API routes) + * - _next/static (static files) + * - _next/image (image optimization files) + * - favicon.ico, robots.txt, sitemap.xml (static files) + */ + '/((?!api|_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml).*)', + ], +}; \ No newline at end of file From 31ee225c658e0a08affca73b197b5bfeba794c55 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 19 May 2025 17:40:26 +0100 Subject: [PATCH 03/19] feat: Add twitter bot check to robots.txt --- apps/web/app/robots.ts | 16 ++++++- apps/web/app/s/[videoId]/page.tsx | 80 +++++++++++++++++++++---------- apps/web/middleware.ts | 2 + 3 files changed, 72 insertions(+), 26 deletions(-) diff --git a/apps/web/app/robots.ts b/apps/web/app/robots.ts index a3d037afb84..6317bf7d1f6 100644 --- a/apps/web/app/robots.ts +++ b/apps/web/app/robots.ts @@ -7,7 +7,9 @@ export const revalidate = 0; export default function robots(): MetadataRoute.Robots { const seoPageSlugs = Object.keys(seoPages); const headersList = headers(); + const referrer = headersList.get("x-referrer") || ""; + const userAgent = headersList.get("x-user-agent") || ""; const allowedReferrers = [ "x.com", @@ -22,10 +24,20 @@ export default function robots(): MetadataRoute.Robots { "t.co" ]; + const allowedBots = [ + "Twitterbot" + ]; + const isAllowedReferrer = allowedReferrers.some(domain => referrer.includes(domain) ); + const isAllowedBot = allowedBots.some(bot => + userAgent.includes(bot) + ); + + const shouldAllowCrawling = isAllowedReferrer || isAllowedBot; + const disallowPaths = [ "/dashboard", "/login", @@ -35,7 +47,7 @@ export default function robots(): MetadataRoute.Robots { "/home", ]; - if (!isAllowedReferrer) { + if (!shouldAllowCrawling) { disallowPaths.push("/s/*"); } @@ -47,7 +59,7 @@ export default function robots(): MetadataRoute.Robots { "/", "/blog/", ...seoPageSlugs.map((slug) => `/${slug}`), - ...(isAllowedReferrer ? ["/s/*"] : []), + ...(shouldAllowCrawling ? ["/s/*"] : []), ], disallow: disallowPaths, }, diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx index 0029893df16..721dd8b860a 100644 --- a/apps/web/app/s/[videoId]/page.tsx +++ b/apps/web/app/s/[videoId]/page.tsx @@ -17,6 +17,7 @@ import { buildEnv, serverEnv } from "@cap/env"; import { getVideoAnalytics } from "@/actions/videos/get-analytics"; import { transcribeVideo } from "@/actions/videos/transcribe"; import { getScreenshot } from "@/actions/screenshots/get-screenshot"; +import { headers } from "next/headers"; export const dynamic = "auto"; export const dynamicParams = true; @@ -65,6 +66,49 @@ export async function generateMetadata( return notFound(); } + // Get the headers from the middleware + const headersList = headers(); + const referrer = headersList.get("x-referrer") || ""; + const userAgent = headersList.get("x-user-agent") || ""; + + // Check if referrer is from allowed platforms + const allowedReferrers = [ + "x.com", + "facebook.com", + "fb.com", + "slack.com", + "notion.so", + "linkedin.com", + "reddit.com", + "youtube.com", + "quora.com", + "t.co", + ]; + + // Check if user agent is from an allowed bot + const allowedBots = [ + "Twitterbot", + "facebookexternalhit", + "LinkedInBot", + "Slackbot", + "redditbot", + "Googlebot", + ]; + + const isAllowedReferrer = allowedReferrers.some((domain) => + referrer.includes(domain) + ); + + const isAllowedBot = allowedBots.some((bot) => userAgent.includes(bot)); + + // Allow indexing if either the referrer or user agent is allowed + const shouldAllowIndexing = isAllowedReferrer || isAllowedBot; + + // Set robots metadata based on whether we should allow indexing + const robotsDirective = shouldAllowIndexing + ? "index, follow" + : "noindex, nofollow"; + if (video.public === false) { return { title: "Cap: This video is private", @@ -93,19 +137,17 @@ export async function generateMetadata( ], }, twitter: { - card: "player", - player: new URL( - `/s/${videoId}`, - buildEnv.NEXT_PUBLIC_WEB_URL - ).toString(), - playerWidth: 1280, - playerHeight: 720, - playerStream: new URL( - `/api/playlist?userId=${video.ownerId}&videoId=${video.id}`, - buildEnv.NEXT_PUBLIC_WEB_URL - ).toString(), - playerStreamContentType: "video/mp4", + card: "summary_large_image", + title: "Cap: This video is private", + description: "This video is private and cannot be shared.", + images: [ + new URL( + `/api/video/og?videoId=${videoId}`, + buildEnv.NEXT_PUBLIC_WEB_URL + ).toString(), + ], }, + robots: "noindex, nofollow", }; } @@ -136,18 +178,7 @@ export async function generateMetadata( ], }, twitter: { - card: "player", - player: new URL( - `/s/${videoId}`, - buildEnv.NEXT_PUBLIC_WEB_URL - ).toString(), - playerWidth: 1280, - playerHeight: 720, - playerStream: new URL( - `/api/playlist?userId=${video.ownerId}&videoId=${video.id}`, - buildEnv.NEXT_PUBLIC_WEB_URL - ).toString(), - playerStreamContentType: "video/mp4", + card: "summary_large_image", title: video.name + " | Cap Recording", description: "Watch this video on Cap", images: [ @@ -157,6 +188,7 @@ export async function generateMetadata( ).toString(), ], }, + robots: robotsDirective, }; } diff --git a/apps/web/middleware.ts b/apps/web/middleware.ts index 450aaea7d5e..3d2a691b8c4 100644 --- a/apps/web/middleware.ts +++ b/apps/web/middleware.ts @@ -85,10 +85,12 @@ export async function middleware(request: NextRequest) { // Get the pathname and referrer const { pathname } = request.nextUrl; const referrer = request.headers.get('referer') || ''; + const userAgent = request.headers.get('user-agent') || ''; // Add custom headers to check in generateMetadata response.headers.set('x-pathname', pathname); response.headers.set('x-referrer', referrer); + response.headers.set('x-user-agent', userAgent); return response; } catch (error) { From b1bba1d17fc8a28b482e2c8fa33b8087c101ace7 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 19 May 2025 17:49:11 +0100 Subject: [PATCH 04/19] feat: Robots.txt changes --- apps/web/app/robots.ts | 28 ++++++++++++++++++++++++++-- apps/web/app/s/[videoId]/page.tsx | 31 +++++++++++++++---------------- 2 files changed, 41 insertions(+), 18 deletions(-) diff --git a/apps/web/app/robots.ts b/apps/web/app/robots.ts index 6317bf7d1f6..20a17f92ccf 100644 --- a/apps/web/app/robots.ts +++ b/apps/web/app/robots.ts @@ -11,6 +11,8 @@ export default function robots(): MetadataRoute.Robots { const referrer = headersList.get("x-referrer") || ""; const userAgent = headersList.get("x-user-agent") || ""; + console.log('ROBOTS.TXT - User Agent:', userAgent); + const allowedReferrers = [ "x.com", "facebook.com", @@ -25,19 +27,22 @@ export default function robots(): MetadataRoute.Robots { ]; const allowedBots = [ - "Twitterbot" + "twitterbot" ]; const isAllowedReferrer = allowedReferrers.some(domain => referrer.includes(domain) ); + const userAgentLower = userAgent.toLowerCase(); const isAllowedBot = allowedBots.some(bot => - userAgent.includes(bot) + userAgentLower.includes(bot.toLowerCase()) ); const shouldAllowCrawling = isAllowedReferrer || isAllowedBot; + const isTwitterBot = userAgentLower.includes('twitterbot'); + const disallowPaths = [ "/dashboard", "/login", @@ -47,6 +52,25 @@ export default function robots(): MetadataRoute.Robots { "/home", ]; + if (isTwitterBot) { + console.log('ROBOTS.TXT - Twitter bot detected, allowing /s/*'); + return { + rules: [ + { + userAgent: "*", + allow: [ + "/", + "/blog/", + ...seoPageSlugs.map((slug) => `/${slug}`), + "/s/*", + ], + disallow: disallowPaths, + }, + ], + sitemap: "https://cap.so/sitemap.xml", + }; + } + if (!shouldAllowCrawling) { disallowPaths.push("/s/*"); } diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx index 721dd8b860a..501752caa2c 100644 --- a/apps/web/app/s/[videoId]/page.tsx +++ b/apps/web/app/s/[videoId]/page.tsx @@ -66,12 +66,12 @@ export async function generateMetadata( return notFound(); } - // Get the headers from the middleware const headersList = headers(); const referrer = headersList.get("x-referrer") || ""; const userAgent = headersList.get("x-user-agent") || ""; - // Check if referrer is from allowed platforms + console.log("[generateMetadata] User Agent:", userAgent); + const allowedReferrers = [ "x.com", "facebook.com", @@ -85,30 +85,29 @@ export async function generateMetadata( "t.co", ]; - // Check if user agent is from an allowed bot - const allowedBots = [ - "Twitterbot", - "facebookexternalhit", - "LinkedInBot", - "Slackbot", - "redditbot", - "Googlebot", - ]; + const allowedBots = ["twitterbot"]; const isAllowedReferrer = allowedReferrers.some((domain) => referrer.includes(domain) ); - const isAllowedBot = allowedBots.some((bot) => userAgent.includes(bot)); + const userAgentLower = userAgent.toLowerCase(); + const isAllowedBot = allowedBots.some((bot) => + userAgentLower.includes(bot.toLowerCase()) + ); + + const isTwitterBot = userAgentLower.includes("twitterbot"); - // Allow indexing if either the referrer or user agent is allowed - const shouldAllowIndexing = isAllowedReferrer || isAllowedBot; + const shouldAllowIndexing = isAllowedReferrer || isAllowedBot || isTwitterBot; - // Set robots metadata based on whether we should allow indexing const robotsDirective = shouldAllowIndexing ? "index, follow" : "noindex, nofollow"; + if (isTwitterBot) { + console.log("[generateMetadata] Twitter bot detected, allowing indexing"); + } + if (video.public === false) { return { title: "Cap: This video is private", @@ -147,7 +146,7 @@ export async function generateMetadata( ).toString(), ], }, - robots: "noindex, nofollow", + robots: isTwitterBot ? "index, follow" : "noindex, nofollow", }; } From 8599d3cfeede7b8da59a1d0b927acb21e7e20974 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 19 May 2025 17:55:09 +0100 Subject: [PATCH 05/19] feat: use userAgent utility --- apps/web/app/robots.ts | 16 ++++++++++++---- apps/web/middleware.ts | 10 ++++++---- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/apps/web/app/robots.ts b/apps/web/app/robots.ts index 20a17f92ccf..6641beedfb1 100644 --- a/apps/web/app/robots.ts +++ b/apps/web/app/robots.ts @@ -9,9 +9,18 @@ export default function robots(): MetadataRoute.Robots { const headersList = headers(); const referrer = headersList.get("x-referrer") || ""; - const userAgent = headersList.get("x-user-agent") || ""; + const userAgentHeader = headersList.get("x-user-agent") || ""; - console.log('ROBOTS.TXT - User Agent:', userAgent); + let ua; + let userAgentString = ""; + + try { + ua = JSON.parse(userAgentHeader); + userAgentString = ua.ua || ""; + } catch (error) { + console.error('Error parsing user agent JSON:', error); + userAgentString = userAgentHeader; + } const allowedReferrers = [ "x.com", @@ -34,7 +43,7 @@ export default function robots(): MetadataRoute.Robots { referrer.includes(domain) ); - const userAgentLower = userAgent.toLowerCase(); + const userAgentLower = userAgentString.toLowerCase(); const isAllowedBot = allowedBots.some(bot => userAgentLower.includes(bot.toLowerCase()) ); @@ -53,7 +62,6 @@ export default function robots(): MetadataRoute.Robots { ]; if (isTwitterBot) { - console.log('ROBOTS.TXT - Twitter bot detected, allowing /s/*'); return { rules: [ { diff --git a/apps/web/middleware.ts b/apps/web/middleware.ts index 3d2a691b8c4..e33b7cee7eb 100644 --- a/apps/web/middleware.ts +++ b/apps/web/middleware.ts @@ -3,7 +3,7 @@ import { organizations } from "@cap/database/schema"; import { eq } from "drizzle-orm"; import { buildEnv, serverEnv } from "@cap/env"; import { notFound } from "next/navigation"; -import { NextRequest, NextResponse } from "next/server"; +import { NextRequest, NextResponse, userAgent } from "next/server"; const addHttps = (s?: string) => { if (!s) return s; @@ -85,12 +85,14 @@ export async function middleware(request: NextRequest) { // Get the pathname and referrer const { pathname } = request.nextUrl; const referrer = request.headers.get('referer') || ''; - const userAgent = request.headers.get('user-agent') || ''; - + + // Parse user agent with the userAgent utility + const ua = userAgent(request); + // Add custom headers to check in generateMetadata response.headers.set('x-pathname', pathname); response.headers.set('x-referrer', referrer); - response.headers.set('x-user-agent', userAgent); + response.headers.set('x-user-agent', JSON.stringify(ua)); return response; } catch (error) { From a9111f4d4b7c5ff656a37286fd10cadbbbb55a80 Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Tue, 20 May 2025 13:52:09 +0800 Subject: [PATCH 06/19] allow deleting split clips (#556) * allow deleting split clips * remove active preset * fix end trim marker --- apps/desktop/src/components/Toggle.tsx | 26 +-- .../src/routes/editor/ConfigSidebar.tsx | 158 +++++++++++++----- apps/desktop/src/routes/editor/Player.tsx | 14 +- .../src/routes/editor/PresetsDropdown.tsx | 7 - .../src/routes/editor/Timeline/ClipTrack.tsx | 89 +++++++--- .../src/routes/editor/Timeline/Track.tsx | 18 +- .../src/routes/editor/Timeline/ZoomTrack.tsx | 41 ++++- .../src/routes/editor/Timeline/index.tsx | 53 ++++-- apps/desktop/src/routes/editor/context.ts | 5 +- apps/desktop/src/routes/editor/index.tsx | 2 +- apps/desktop/src/routes/editor/ui.tsx | 23 +-- apps/desktop/src/styles/timeline.css | 34 +--- 12 files changed, 296 insertions(+), 174 deletions(-) diff --git a/apps/desktop/src/components/Toggle.tsx b/apps/desktop/src/components/Toggle.tsx index ca6925177ce..f537ee279cf 100644 --- a/apps/desktop/src/components/Toggle.tsx +++ b/apps/desktop/src/components/Toggle.tsx @@ -9,34 +9,36 @@ const toggleControlStyles = cva( size: { sm: "w-9 h-[1.25rem] p-[0.125rem]", md: "w-11 h-[1.5rem] p-[0.125rem]", - lg: "w-14 h-[1.75rem] p-[0.1875rem]" - } + lg: "w-14 h-[1.75rem] p-[0.1875rem]", + }, }, defaultVariants: { - size: "md" - } + size: "md", + }, } ); const toggleThumbStyles = cva( - "ui-checked:bg-solid-white bg-gray-10 rounded-full transition-transform ui-checked:translate-x-[calc(100%)]", + "bg-white rounded-full transition-transform ui-checked:translate-x-[calc(100%)]", { variants: { size: { sm: "size-[1rem]", md: "size-[1.25rem]", - lg: "size-[1.5rem]" - } + lg: "size-[1.5rem]", + }, }, defaultVariants: { - size: "md" - } + size: "md", + }, } ); -export function Toggle(props: ComponentProps & { size?: 'sm' | 'md' | 'lg' }) { - const [local, others] = splitProps(props, ['size']); - +export function Toggle( + props: ComponentProps & { size?: "sm" | "md" | "lg" } +) { + const [local, others] = splitProps(props, ["size"]); + return ( diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx index 7bde1a99757..6c544ef7e93 100644 --- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx +++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx @@ -19,6 +19,7 @@ import { cx } from "cva"; import { For, Show, + Suspense, ValidComponent, batch, createEffect, @@ -42,6 +43,7 @@ import { generalSettingsStore } from "~/store"; import { type BackgroundSource, StereoMode, + TimelineSegment, ZoomSegment, commands, } from "~/utils/tauri"; @@ -215,7 +217,7 @@ export function ConfigSidebar() { return ( - { - const selection = - editorState.timeline.selection?.type === "zoom" && - editorState.timeline.selection; - if (!selection) return; - - const segment = project.timeline?.zoomSegments?.[selection.index]; - if (!segment) return; - - return { selection, segment }; - })()} - > - {(value) => ( - + + {(selection) => ( +
+ + { + const zoomSelection = selection(); + if (zoomSelection.type !== "zoom") return; + + const segment = + project.timeline?.zoomSegments?.[zoomSelection.index]; + if (!segment) return; + + return { selection: zoomSelection, segment }; + })()} + > + {(value) => ( + + )} + + { + const clipSegment = selection(); + if (clipSegment.type !== "clip") return; + + const segment = + project.timeline?.segments?.[clipSegment.index]; + if (!segment) return; + + return { selection: clipSegment, segment }; + })()} + > + {(value) => ( + + )} + + +
)}
@@ -1613,7 +1641,6 @@ function ZoomSegmentConfig(props: { project, setProject, editorInstance, - editorState, setEditorState, projectHistory, } = useEditorContext(); @@ -1626,10 +1653,7 @@ function ZoomSegmentConfig(props: { }; return ( -
+ <>
{ - if (v === "auto") { - setProject( - "timeline", - "zoomSegments", - props.segmentIndex, - "mode", - "auto" - ); - } else { - setProject( - "timeline", - "zoomSegments", - props.segmentIndex, - "mode", - { manual: states.manual } - ); - } + setProject( + "timeline", + "zoomSegments", + props.segmentIndex, + "mode", + v === "auto" ? "auto" : { manual: states.manual } + ); }} > @@ -1716,7 +1730,7 @@ function ZoomSegmentConfig(props: { Manual -
+
@@ -1893,7 +1907,65 @@ function ZoomSegmentConfig(props: { -
+ + ); +} + +function ClipSegmentConfig(props: { + segmentIndex: number; + segment: TimelineSegment; +}) { + const { setProject, setEditorState, project } = useEditorContext(); + + return ( + <> +
+
+ setEditorState("timeline", "selection", null)} + leftIcon={} + > + Done + +
+ { + batch(() => { + setProject( + "timeline", + "segments", + produce((s) => { + if (!s) return; + return s.splice(props.segmentIndex, 1); + }) + ); + setEditorState("timeline", "selection", null); + }); + }} + disabled={ + ( + project.timeline?.segments.filter( + (s) => s.recordingSegment === props.segment.recordingSegment + ) ?? [] + ).length < 2 + } + leftIcon={} + > + Delete + +
+ + } /> + + + } + /> + + ); } diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx index 40f265a803e..a660a95fda0 100644 --- a/apps/desktop/src/routes/editor/Player.tsx +++ b/apps/desktop/src/routes/editor/Player.tsx @@ -74,7 +74,7 @@ export function Player() { }); return ( -
+
} - />{" "} + leftIcon={ + + } + />
(presets.query.data?.default ?? null); return ( @@ -55,15 +54,9 @@ export function PresetsDropdown() { onClick={() => { setShowSettings(false); setProject(reconcile(preset.config)); - setActivePreset(i()); }} > {preset.name} - - - Current - - Default diff --git a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx index 12a4d4622ad..2f3ea8128bd 100644 --- a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx @@ -1,4 +1,7 @@ -import { createEventListenerMap } from "@solid-primitives/event-listener"; +import { + createEventListener, + createEventListenerMap, +} from "@solid-primitives/event-listener"; import { cx } from "cva"; import { Accessor, @@ -8,6 +11,7 @@ import { Show, Switch, createEffect, + createMemo, createRoot, mergeProps, } from "solid-js"; @@ -25,13 +29,18 @@ import { useSegmentWidth, } from "./Track"; -export function ClipTrack(props: Pick, "ref">) { +export function ClipTrack( + props: Pick, "ref"> & { + handleUpdatePlayhead: (e: MouseEvent) => void; + } +) { const { project, setProject, editorInstance, projectHistory, editorState, + setEditorState, totalDuration, } = useEditorContext(); @@ -85,6 +94,17 @@ export function ClipTrack(props: Pick, "ref">) { position: "right", })); + const isSelected = createMemo(() => { + const selection = editorState.timeline.selection; + if (!selection || selection.type !== "clip") return false; + + const segmentIndex = project.timeline?.segments?.findIndex( + (s) => s.start === segment.start && s.end === segment.end + ); + + return segmentIndex === selection.index; + }); + return ( <> @@ -191,35 +211,50 @@ export function ClipTrack(props: Pick, "ref">) { { - if (editorState.timeline.interactMode !== "split") return; e.stopPropagation(); - const rect = e.currentTarget.getBoundingClientRect(); - const fraction = (e.clientX - rect.left) / rect.width; - - const splitTime = - segment.start + fraction * (segment.end - segment.start); - - setProject( - "timeline", - "segments", - produce((segments) => { - segments.splice(i() + 1, 0, { - start: splitTime, - end: segment.end, - timescale: 1, - recordingSegment: segment.recordingSegment, + if (editorState.timeline.interactMode === "split") { + const rect = e.currentTarget.getBoundingClientRect(); + const fraction = (e.clientX - rect.left) / rect.width; + + const splitTime = + segment.start + fraction * (segment.end - segment.start); + + setProject( + "timeline", + "segments", + produce((segments) => { + segments.splice(i() + 1, 0, { + start: splitTime, + end: segment.end, + timescale: 1, + recordingSegment: segment.recordingSegment, + }); + segments[i()].end = splitTime; + }) + ); + } else { + createRoot((dispose) => { + createEventListener(e.currentTarget, "mouseup", (e) => { + dispose(); + + setEditorState("timeline", "selection", { + type: "clip", + index: i(), + }); + props.handleUpdatePlayhead(e); }); - segments[i()].end = splitTime; - }) - ); + }); + } }} > @@ -293,14 +328,14 @@ export function ClipTrack(props: Pick, "ref">) { }); }} /> - + {(() => { const ctx = useSegmentContext(); return ( 100}>
- + {hasMultipleRecordingSegments() ? `Clip ${segment.recordingSegment}` : "Clip"} @@ -505,7 +540,7 @@ function useSectionMarker( return () => { const { segments, i, position } = props(); - if (i === 0) { + if (i === 0 && position === "left") { return segments[0].start === 0 ? null : { diff --git a/apps/desktop/src/routes/editor/Timeline/Track.tsx b/apps/desktop/src/routes/editor/Timeline/Track.tsx index 72121c1d1ea..28d6dbb697b 100644 --- a/apps/desktop/src/routes/editor/Timeline/Track.tsx +++ b/apps/desktop/src/routes/editor/Timeline/Track.tsx @@ -18,7 +18,7 @@ export function TrackRoot(props: ComponentProps<"div">) {
{props.children}
@@ -56,19 +56,6 @@ export function SegmentRoot( ) => void; } ) { - const { editorState: state, project } = useEditorContext(); - - const isSelected = createMemo(() => { - const selection = state.timeline.selection; - if (!selection || selection.type !== "zoom") return false; - - const segmentIndex = project.timeline?.zoomSegments?.findIndex( - (s) => s.start === props.segment.start && s.end === props.segment.end - ); - - return segmentIndex === selection.index; - }); - const translateX = useSegmentTranslateX(() => props.segment); const width = useSegmentWidth(() => props.segment); @@ -78,8 +65,7 @@ export function SegmentRoot( {...props} class={cx( "absolute overflow-hidden border rounded-xl inset-y-0", - props.class, - isSelected() && "wobble-wrapper border border-gray-500" + props.class )} style={{ "--segment-x": `${translateX()}px`, diff --git a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx index 0c5ba13c804..b00da7a6dc4 100644 --- a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx +++ b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx @@ -1,17 +1,25 @@ import { - createEventListener, - createEventListenerMap, + createEventListener, + createEventListenerMap, } from "@solid-primitives/event-listener"; -import { For, Show, batch, createRoot, createSignal } from "solid-js"; +import { + For, + Show, + batch, + createMemo, + createRoot, + createSignal, +} from "solid-js"; import { produce } from "solid-js/store"; import { useEditorContext } from "../context"; import { - useSegmentContext, - useTimelineContext, - useTrackContext, + useSegmentContext, + useTimelineContext, + useTrackContext, } from "./context"; import { SegmentContent, SegmentHandle, SegmentRoot, TrackRoot } from "./Track"; +import { cx } from "cva"; export type ZoomSegmentDragState = | { type: "idle" } @@ -200,9 +208,26 @@ export function ZoomTrack(props: { }; } + const isSelected = createMemo(() => { + const selection = editorState.timeline.selection; + if (!selection || selection.type !== "zoom") return false; + + const segmentIndex = project.timeline?.zoomSegments?.findIndex( + (s) => s.start === segment.start && s.end === segment.end + ); + + return segmentIndex === selection.index; + }); + return ( { @@ -355,7 +380,7 @@ export function ZoomTrack(props: { end: time() + 1, }} > - +

+

diff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsx index 72c5fc5f4a0..4a5a84a8cc8 100644 --- a/apps/desktop/src/routes/editor/Timeline/index.tsx +++ b/apps/desktop/src/routes/editor/Timeline/index.tsx @@ -5,6 +5,8 @@ import { cx } from "cva"; import { For, Show, batch, createRoot, createSignal, onMount } from "solid-js"; import { produce } from "solid-js/store"; +import "../../../styles/timeline.css"; + import { useEditorContext } from "../context"; import { formatTime } from "../utils"; import { ClipTrack } from "./ClipTrack"; @@ -85,16 +87,42 @@ export function Timeline() { createEventListener(window, "keydown", (e) => { if (e.code === "Backspace" || e.code === "Delete") { - if (editorState.timeline.selection?.type !== "zoom") return; const selection = editorState.timeline.selection; + if (!selection) return; - batch(() => { - setProject( - produce((project) => { - project.timeline?.zoomSegments.splice(selection.index, 1); - }) + if (selection.type === "zoom") { + batch(() => { + setProject( + produce((project) => { + project.timeline?.zoomSegments.splice(selection.index, 1); + }) + ); + }); + } else if (selection.type === "clip") { + const selectedSegment = project.timeline?.segments.find( + (_, i) => i === selection.index ); - }); + if (!selectedSegment || selectedSegment.recordingSegment === undefined) + return; + + const timeline = project.timeline; + if (!timeline) return; + + if ( + timeline.segments.filter( + (s) => s.recordingSegment === selectedSegment.recordingSegment + ).length < 2 + ) + return; + + batch(() => { + setProject( + produce((project) => { + project.timeline?.segments.splice(selection.index, 1); + }) + ); + }); + } } }); @@ -212,7 +240,10 @@ export function Timeline() {
- + { zoomSegmentDragState = v; @@ -239,12 +270,12 @@ function TimelineMarkings() { }; return ( -
+
{(second) => ( 0}>
-
+
{formatTime(second)}
diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts index b1b134db92f..94b50ff01a4 100644 --- a/apps/desktop/src/routes/editor/context.ts +++ b/apps/desktop/src/routes/editor/context.ts @@ -155,7 +155,10 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider( playing: false, timeline: { interactMode: "seek" as "seek" | "split", - selection: null as null | { type: "zoom"; index: number }, + selection: null as + | null + | { type: "zoom"; index: number } + | { type: "clip"; index: number }, transform: { // visible seconds zoom: zoomOutLimit(), diff --git a/apps/desktop/src/routes/editor/index.tsx b/apps/desktop/src/routes/editor/index.tsx index 87ccc0265f8..9ebffd007d5 100644 --- a/apps/desktop/src/routes/editor/index.tsx +++ b/apps/desktop/src/routes/editor/index.tsx @@ -22,7 +22,7 @@ export default function () { return (
) { return (
- + {props.icon} {props.name} {props.value &&
{props.value}
} @@ -58,9 +62,6 @@ export function Subfield( ); } - - - export function Slider( props: ComponentProps & { formatTooltip?: string | ((v: number) => string); @@ -145,7 +146,6 @@ export function Slider( ); } - export function Input(props: ComponentProps<"input">) { return ( ); }, @@ -251,9 +248,7 @@ export function DialogContent( return ( <> - - {props.title} - + {props.title} {props.children} - + Coming Soon diff --git a/apps/desktop/src/styles/timeline.css b/apps/desktop/src/styles/timeline.css index 71c060a5c74..9f85faa7cc9 100644 --- a/apps/desktop/src/styles/timeline.css +++ b/apps/desktop/src/styles/timeline.css @@ -1,42 +1,14 @@ @keyframes wobble { - 0%, 100% { + 0%, + 100% { transform: translateY(0) translateX(var(--segment-x)); } 50% { - transform: translateY(-4px) translateX(var(--segment-x)); + transform: translateY(-3px) translateX(var(--segment-x)); } } .wobble-wrapper { animation: wobble 1s ease-in-out infinite; will-change: transform; - -} - -.timeline-gradient-border::before { - content: ''; - position: absolute; - inset: 0; - padding: 1px; - border-radius: 12px; - background: linear-gradient(to bottom, #ffffff4a 50%, #ffffff00 100%); - -webkit-mask: - linear-gradient(#fff 0 0) content-box, - linear-gradient(#fff 0 0); - -webkit-mask-composite: xor; - mask-composite: exclude; } - -.zoom-gradient-border::before { - content: ''; - position: absolute; - inset: 0; - padding: 1px; - border-radius: 12px; - background: linear-gradient(to bottom, #ffffff1f 50%, #ffffff00 100%); - -webkit-mask: - linear-gradient(#fff 0 0) content-box, - linear-gradient(#fff 0 0); - -webkit-mask-composite: xor; - mask-composite: exclude; -} \ No newline at end of file From 6c6b81b4914d24dbd2c5d9d1d1f7bae859ce2468 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 20 May 2025 09:11:38 +0100 Subject: [PATCH 07/19] Fix crop normalization (#551) * Fix crop normalization logic * cleanup * add tests --------- Co-authored-by: Brendan Allan --- crates/cursor-capture/src/position.rs | 153 +++++++++++++++++++++++++- 1 file changed, 148 insertions(+), 5 deletions(-) diff --git a/crates/cursor-capture/src/position.rs b/crates/cursor-capture/src/position.rs index 13731825605..26cab0807ea 100644 --- a/crates/cursor-capture/src/position.rs +++ b/crates/cursor-capture/src/position.rs @@ -134,14 +134,14 @@ impl NormalizedCursorPosition { } pub fn with_crop(&self, position: (f32, f32), size: (f32, f32)) -> Self { - let raw_normalized = ( - self.x / self.crop_size.0 - self.crop_position.0, - self.y / self.crop_size.1 - self.crop_position.1, + let raw_px = ( + self.x * self.crop_size.0 + self.crop_position.0, + self.y * self.crop_size.1 + self.crop_position.1, ); Self { - x: raw_normalized.0 / size.0 - position.0, - y: raw_normalized.1 / size.1 - position.1, + x: (raw_px.0 - position.0) / size.0, + y: (raw_px.1 - position.1) / size.1, crop_position: position, crop_size: size, display: self.display, @@ -157,3 +157,146 @@ impl std::fmt::Debug for NormalizedCursorPosition { .finish() } } + +#[cfg(test)] +mod tests { + use super::*; + use cap_displays::Display; + + // Helper function to create a mock Display for testing + fn mock_display() -> Display { + Display::list()[0].clone() + } + + #[test] + fn test_with_crop_no_change() { + let display = mock_display(); + let original_normalized = NormalizedCursorPosition { + x: 0.5, + y: 0.5, + crop_position: (0.0, 0.0), + crop_size: (1.0, 1.0), + display, + }; + + let cropped_position = (0.0, 0.0); + let cropped_size = (1.0, 1.0); + let new_normalized = original_normalized.with_crop(cropped_position, cropped_size); + + assert_eq!(new_normalized.x, 0.5); + assert_eq!(new_normalized.y, 0.5); + assert_eq!(new_normalized.crop_position(), (0.0, 0.0)); + assert_eq!(new_normalized.crop_size(), (1.0, 1.0)); + } + + #[test] + fn test_with_crop_centered() { + let display = mock_display(); + let original_normalized = NormalizedCursorPosition { + x: 0.5, + y: 0.5, + crop_position: (0.0, 0.0), + crop_size: (1.0, 1.0), + display, + }; + + let cropped_position = (0.25, 0.25); + let cropped_size = (0.5, 0.5); + let new_normalized = original_normalized.with_crop(cropped_position, cropped_size); + + // Original point (0.5, 0.5) is in the center of the (0,0) to (1,1) range. + // The new crop is from (0.25, 0.25) to (0.75, 0.75). + // The original point (0.5, 0.5) should still be in the center of this new crop. + let expected_x = (0.5 * 1.0 + 0.0 - 0.25) / 0.5; + let expected_y = (0.5 * 1.0 + 0.0 - 0.25) / 0.5; + + assert!((new_normalized.x - expected_x).abs() < f32::EPSILON); + assert!((new_normalized.y - expected_y).abs() < f32::EPSILON); + assert_eq!(new_normalized.crop_position(), (0.25, 0.25)); + assert_eq!(new_normalized.crop_size(), (0.5, 0.5)); + } + + #[test] + fn test_with_crop_top_left_of_crop() { + let display = mock_display(); + + let cropped_position = (0.25, 0.25); + let cropped_size = (0.5, 0.5); + + let original_normalized_at_crop_tl = NormalizedCursorPosition { + x: 0.25, + y: 0.25, + crop_position: (0.0, 0.0), + crop_size: (1.0, 1.0), + display, + }; + + let new_normalized = + original_normalized_at_crop_tl.with_crop(cropped_position, cropped_size); + + // The point that was at the top-left of the crop in the original space + // should now be at (0.0, 0.0) in the new cropped space. + assert!((new_normalized.x - 0.0).abs() < f32::EPSILON); + assert!((new_normalized.y - 0.0).abs() < f32::EPSILON); + assert_eq!(new_normalized.crop_position(), (0.25, 0.25)); + assert_eq!(new_normalized.crop_size(), (0.5, 0.5)); + } + + #[test] + fn test_with_crop_bottom_right_of_crop() { + let display = mock_display(); + + let cropped_position = (0.25, 0.25); + let cropped_size = (0.5, 0.5); + + let original_normalized_at_crop_br = NormalizedCursorPosition { + x: 0.75, + y: 0.75, + crop_position: (0.0, 0.0), + crop_size: (1.0, 1.0), + display, + }; + + let new_normalized = + original_normalized_at_crop_br.with_crop(cropped_position, cropped_size); + + // The point that was at the bottom-right of the crop in the original space + // should now be at (1.0, 1.0) in the new cropped space. + assert!((new_normalized.x - 1.0).abs() < f32::EPSILON); + assert!((new_normalized.y - 1.0).abs() < f32::EPSILON); + assert_eq!(new_normalized.crop_position(), (0.25, 0.25)); + assert_eq!(new_normalized.crop_size(), (0.5, 0.5)); + } + + #[test] + fn test_with_crop_from_existing_crop() { + let display = mock_display(); + let original_normalized = NormalizedCursorPosition { + x: 0.5, // This 0.5 is within the first crop + y: 0.5, // This 0.5 is within the first crop + crop_position: (0.1, 0.1), + crop_size: (0.8, 0.8), + display, + }; + + // The raw position of the cursor is 0.5 within the 0.1 to 0.9 range. + // Raw x = 0.5 * 0.8 + 0.1 = 0.4 + 0.1 = 0.5 + // Raw y = 0.5 * 0.8 + 0.1 = 0.4 + 0.1 = 0.5 + + let second_crop_position = (0.2, 0.2); + let second_crop_size = (0.6, 0.6); + + // The second crop is from 0.2 to 0.8 in the original space. + // The raw position is (0.5, 0.5). + // In the second crop space, this should be: + // x = (0.5 - 0.2) / 0.6 = 0.3 / 0.6 = 0.5 + // y = (0.5 - 0.2) / 0.6 = 0.3 / 0.6 = 0.5 + + let new_normalized = original_normalized.with_crop(second_crop_position, second_crop_size); + + assert!((new_normalized.x - 0.5).abs() < f32::EPSILON); + assert!((new_normalized.y - 0.5).abs() < f32::EPSILON); + assert_eq!(new_normalized.crop_position(), (0.2, 0.2)); + assert_eq!(new_normalized.crop_size(), (0.6, 0.6)); + } +} From 8c0f8af53fdb929e713aa1ebf7d53ac48fbcc630 Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Thu, 22 May 2025 00:05:00 +0800 Subject: [PATCH 08/19] presets fixes (#563) * preserve timeline when switching presets * make preset deserialization a silent failure --- apps/desktop/src-tauri/src/presets.rs | 6 +++++- .../src/routes/editor/PresetsDropdown.tsx | 18 +++++++++++++----- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/apps/desktop/src-tauri/src/presets.rs b/apps/desktop/src-tauri/src/presets.rs index 3b846e94389..56ba8db4dc7 100644 --- a/apps/desktop/src-tauri/src/presets.rs +++ b/apps/desktop/src-tauri/src/presets.rs @@ -4,6 +4,7 @@ use serde_json::json; use specta::Type; use tauri::{AppHandle, Wry}; use tauri_plugin_store::StoreExt; +use tracing::error; #[derive(Serialize, Deserialize, Type, Debug, Default)] #[serde(rename_all = "camelCase")] @@ -26,7 +27,10 @@ impl PresetsStore { // Handle potential deserialization errors gracefully match serde_json::from_value(store) { Ok(settings) => Ok(Some(settings)), - Err(_) => Err("Failed to deserialize presets store".to_string()), + Err(_) => { + error!("Failed to deserialize presets store"); + Ok(None) + } } } _ => Ok(None), diff --git a/apps/desktop/src/routes/editor/PresetsDropdown.tsx b/apps/desktop/src/routes/editor/PresetsDropdown.tsx index a779d2df087..75a4e545ddb 100644 --- a/apps/desktop/src/routes/editor/PresetsDropdown.tsx +++ b/apps/desktop/src/routes/editor/PresetsDropdown.tsx @@ -14,7 +14,7 @@ import { } from "./ui"; export function PresetsDropdown() { - const { setDialog, presets, setProject } = useEditorContext(); + const { setDialog, presets, setProject, project } = useEditorContext(); return ( @@ -45,6 +45,16 @@ export function PresetsDropdown() { {(preset, i) => { const [showSettings, setShowSettings] = createSignal(false); + function applyPreset() { + setShowSettings(false); + setProject( + reconcile({ + ...preset.config, + timeline: project.timeline, + }) + ); + } + return ( @@ -52,8 +62,7 @@ export function PresetsDropdown() { class="h-[2.5rem]" onFocusIn={() => setShowSettings(false)} onClick={() => { - setShowSettings(false); - setProject(reconcile(preset.config)); + applyPreset(); }} > {preset.name} @@ -88,8 +97,7 @@ export function PresetsDropdown() { > { - setShowSettings(false); - setProject(reconcile(preset.config)); + applyPreset(); }} > Apply From bc43fbece58c74650489cbf810c45acc54bc626a Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Fri, 23 May 2025 01:54:07 +0800 Subject: [PATCH 09/19] use api keys for desktop auth (#564) * use api keys for desktop auth * add primary * fix upgrade flow * use vercel branch url * update http plugin versions --- Cargo.lock | 4 +- apps/desktop/package.json | 5 +- apps/desktop/src-tauri/src/auth.rs | 16 +- apps/desktop/src-tauri/src/lib.rs | 6 +- apps/desktop/src-tauri/src/web_api.rs | 15 +- apps/desktop/src/components/SignInButton.tsx | 140 +- .../src/routes/(window-chrome)/(main).tsx | 60 +- .../src/routes/(window-chrome)/upgrade.tsx | 358 ++--- apps/desktop/src/utils/auth.ts | 158 ++ apps/desktop/src/utils/tauri.ts | 3 +- apps/desktop/src/utils/web-api.ts | 12 +- apps/web/app/api/desktop/session/app.ts | 45 +- .../route.ts => [...route]/multipart.ts} | 9 +- apps/web/app/api/upload/[...route]/route.ts | 18 + .../{signed/route.ts => [...route]/signed.ts} | 76 +- apps/web/app/api/upload/mux/create/route.ts | 298 ---- apps/web/app/api/upload/mux/status/route.ts | 164 -- apps/web/app/api/upload/new/route.ts | 49 - apps/web/app/api/utils.ts | 55 +- .../migrations/0003_small_chamber.sql | 5 + .../database/migrations/0004_good_microbe.sql | 2 + .../migrations/meta/0003_snapshot.json | 1318 ++++++++++++++++ .../migrations/meta/0004_snapshot.json | 1332 +++++++++++++++++ .../database/migrations/meta/_journal.json | 14 + packages/database/schema.ts | 63 +- packages/env/server.ts | 1 - pnpm-lock.yaml | 213 +-- 27 files changed, 3261 insertions(+), 1178 deletions(-) create mode 100644 apps/desktop/src/utils/auth.ts rename apps/web/app/api/upload/{multipart/[...route]/route.ts => [...route]/multipart.ts} (98%) create mode 100644 apps/web/app/api/upload/[...route]/route.ts rename apps/web/app/api/upload/{signed/route.ts => [...route]/signed.ts} (79%) delete mode 100644 apps/web/app/api/upload/mux/create/route.ts delete mode 100644 apps/web/app/api/upload/mux/status/route.ts delete mode 100644 apps/web/app/api/upload/new/route.ts create mode 100644 packages/database/migrations/0003_small_chamber.sql create mode 100644 packages/database/migrations/0004_good_microbe.sql create mode 100644 packages/database/migrations/meta/0003_snapshot.json create mode 100644 packages/database/migrations/meta/0004_snapshot.json diff --git a/Cargo.lock b/Cargo.lock index cddf8da31e4..e43fa8a85cb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7584,9 +7584,9 @@ dependencies = [ [[package]] name = "tauri-plugin-http" -version = "2.2.0" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e62a9bde54d6a0218b63f5a248f02056ad4316ba6ad81dfb9e4f73715df5deb1" +checksum = "696ef548befeee6c6c17b80ef73e7c41205b6c2204e87ef78ccc231212389a5c" dependencies = [ "data-url", "http", diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 8a598bec870..ff39e3669c1 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -41,7 +41,7 @@ "@tauri-apps/plugin-deep-link": "^2.2.0", "@tauri-apps/plugin-dialog": "2.0.1", "@tauri-apps/plugin-fs": "2.2.0", - "@tauri-apps/plugin-http": "^2.0.1", + "@tauri-apps/plugin-http": "^2.4.4", "@tauri-apps/plugin-notification": "2.0.0", "@tauri-apps/plugin-opener": "^2.2.6", "@tauri-apps/plugin-os": "2.0.0", @@ -64,7 +64,8 @@ "unplugin-icons": "^0.19.2", "uuid": "^9.0.1", "vinxi": "^0.5.6", - "webcodecs": "^0.1.0" + "webcodecs": "^0.1.0", + "zod": "^3.24.2" }, "devDependencies": { "@fontsource/geist-sans": "^5.0.3", diff --git a/apps/desktop/src-tauri/src/auth.rs b/apps/desktop/src-tauri/src/auth.rs index 40984ce823f..40695416144 100644 --- a/apps/desktop/src-tauri/src/auth.rs +++ b/apps/desktop/src-tauri/src/auth.rs @@ -10,13 +10,19 @@ use crate::web_api; #[derive(Serialize, Deserialize, Type, Debug)] pub struct AuthStore { - pub token: String, + pub secret: AuthSecret, pub user_id: Option, - pub expires: i32, pub plan: Option, pub intercom_hash: Option, } +#[derive(Serialize, Deserialize, Type, Debug)] +#[serde(untagged)] +pub enum AuthSecret { + ApiKey { api_key: String }, + Session { token: String, expires: i32 }, +} + #[derive(Serialize, Deserialize, Type, Debug)] pub struct Plan { pub upgraded: bool, @@ -108,12 +114,6 @@ impl AuthStore { return Err("Store not found".to_string()); }; - let value = value.map(|mut auth| { - // Set expiration to 100 years in the future - auth.expires = (chrono::Utc::now() + chrono::Duration::days(36500)).timestamp() as i32; - auth - }); - store.set("auth", json!(value)); store.save().map_err(|e| e.to_string()) } diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 391e9f6afbf..d199d89d3a2 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -1715,7 +1715,7 @@ async fn check_upgraded_and_update(app: AppHandle) -> Result { } } - let Ok(Some(mut auth)) = AuthStore::get(&app) else { + let Ok(Some(auth)) = AuthStore::get(&app) else { println!("No auth found, clearing auth store"); AuthStore::set(&app, None).map_err(|e| e.to_string())?; return Ok(false); @@ -1732,7 +1732,6 @@ async fn check_upgraded_and_update(app: AppHandle) -> Result { "Fetching plan for user {}", auth.user_id.as_deref().unwrap_or("unknown") ); - let plan_url = app.make_app_url("/api/desktop/plan"); let response = app .authed_api_request("/api/desktop/plan", |client, url| client.get(url)) .await @@ -1759,9 +1758,8 @@ async fn check_upgraded_and_update(app: AppHandle) -> Result { .unwrap_or(false); println!("Pro status: {}", is_pro); let updated_auth = AuthStore { - token: auth.token, + secret: auth.secret, user_id: auth.user_id, - expires: auth.expires, intercom_hash: auth.intercom_hash, plan: Some(Plan { upgraded: is_pro, diff --git a/apps/desktop/src-tauri/src/web_api.rs b/apps/desktop/src-tauri/src/web_api.rs index c8478523df2..9afb4ec38ad 100644 --- a/apps/desktop/src-tauri/src/web_api.rs +++ b/apps/desktop/src-tauri/src/web_api.rs @@ -3,8 +3,8 @@ use tauri::{Emitter, Manager, Runtime}; use tauri_specta::Event; use crate::{ - auth::{AuthStore, AuthenticationInvalid}, - ArcLock, MutableState, + auth::{AuthSecret, AuthStore, AuthenticationInvalid}, + ArcLock, }; async fn do_authed_request( @@ -14,7 +14,16 @@ async fn do_authed_request( ) -> Result { let client = reqwest::Client::new(); - let mut req = build(client, url).header("Authorization", format!("Bearer {}", auth.token)); + let mut req = build(client, url).header( + "Authorization", + format!( + "Bearer {}", + match &auth.secret { + AuthSecret::ApiKey { api_key } => api_key, + AuthSecret::Session { token, .. } => token, + } + ), + ); if let Some(s) = std::option_env!("VITE_VERCEL_AUTOMATION_BYPASS_SECRET") { req = req.header("x-vercel-protection-bypass", s); diff --git a/apps/desktop/src/components/SignInButton.tsx b/apps/desktop/src/components/SignInButton.tsx index 3ef0ab41eb5..755f724ca6c 100644 --- a/apps/desktop/src/components/SignInButton.tsx +++ b/apps/desktop/src/components/SignInButton.tsx @@ -4,6 +4,7 @@ import { invoke } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import { onOpenUrl } from "@tauri-apps/plugin-deep-link"; import * as shell from "@tauri-apps/plugin-shell"; +import { z } from "zod"; import { getCurrentWindow } from "@tauri-apps/api/window"; import { ComponentProps } from "solid-js"; @@ -12,27 +13,12 @@ import { identifyUser, trackEvent } from "~/utils/analytics"; import { clientEnv } from "~/utils/env"; import { commands } from "~/utils/tauri"; import callbackTemplate from "./callback.template"; +import { createSignInMutation } from "~/utils/auth"; export function SignInButton( props: Omit, "onClick"> ) { - const signIn = createMutation(() => ({ - mutationFn: async (abort: AbortController) => { - const platform = import.meta.env.DEV ? "web" : "desktop"; - - let session; - - if (platform === "web") - session = await createLocalServerSession(abort.signal); - else session = await createDeepLinkSession(abort.signal); - - await shell.open(session.url.toString()); - - await processAuthData(await session.complete()); - - getCurrentWindow().setFocus(); - }, - })); + const signIn = createSignInMutation(); return ( - - - Previous Recordings -
- } - > + getCurrentWindow().hide(); + }} + class="flex items-center justify-center w-5 h-5 -ml-[1.5px]" + > + + + + Previous Recordings
}> - + type="button" + onClick={async () => { + await commands.showWindow({ Settings: { page: "recordings" } }); + getCurrentWindow().hide(); + }} + class="flex justify-center items-center w-5 h-5" + > + + + @@ -794,7 +782,6 @@ function MicrophoneSelect(props: { const [dbs, setDbs] = createSignal(); const [isInitialized, setIsInitialized] = createSignal(false); - const requestPermission = useRequestPermission(); const permissionGranted = () => @@ -1036,7 +1023,7 @@ function TargetSelectInfoPill(props: { ? "On" : "Off"} -); + ); } function InfoPill( @@ -1112,10 +1099,7 @@ function ChangelogButton() { }); return ( - + - }> - -
-

- Your account is upgraded to Cap Pro and already includes a - commercial license. -

-
-
- - {(license) => ( -
-

- Your License -

-
- -
-                  {license().licenseKey}
-                
-
- - {(expiry) => ( -
- - - {new Date(expiry()).toUTCString()} - -
- )} -
- - {/*

- Instance ID: {license().instanceId} -

*/} -
- -
-
- )} -
-
-
- ); -} - -function LicenseKeyActivate(props: { - onActivated: ( - value: ClientInferResponseBody< - (typeof licenseContract)["activateCommercialLicense"], - 200 - > & { licenseKey: string } - ) => void; -}) { - const [store] = createResource(() => generalSettingsStore.get()); - - return ( - - - {(generalSettings) => { - const [licenseKey, setLicenseKey] = createSignal(""); - - const activateLicenseKey = createMutation(() => ({ - mutationFn: async (vars: { licenseKey: string }) => { - const resp = await licenseApiClient.activateCommercialLicense({ - headers: { - licensekey: vars.licenseKey, - instanceid: generalSettings().instanceId!, - }, - body: { reset: false }, - }); - - if (resp.status === 200) return resp.body; - if ( - typeof resp.body === "object" && - resp.body && - "message" in resp.body - ) - throw resp.body.message; - throw new Error((resp.body as any).toString()); - }, - onSuccess: (value, { licenseKey }) => - props.onActivated({ ...value, licenseKey }), - })); - - return ( -
-

- Got a license key? Enter it below -

- setLicenseKey(e.currentTarget.value)} - /> - - {/*

- Instance ID: {generalSettings().instanceId} -

*/} -
- ); - }} -
-
- ); -} - -type CommercialLicenseType = "yearly" | "lifetime"; -function CommercialLicensePurchase() { - const openCheckoutInExternalBrowser = createMutation(() => ({ - mutationFn: async ({ type }: { type: CommercialLicenseType }) => { - const resp = await licenseApiClient.createCommercialCheckoutUrl({ - body: { type }, - }); - - if (resp.status === 200) tauriShell.open(resp.body.url); - else throw resp.body; - }, - })); - - const [type, setType] = createSignal("yearly"); - - return ( - <> -
-
-
-

- Commercial License -

-

- For professional use without cloud features. -

-
-
-

- {type() === "yearly" ? "$29/year" : "$58"} -

-
- {type() === "lifetime" && ( -

- billed once -

- )} - {type() === "lifetime" && ( -

- or, $29/year. -

- )} -
-
-
-
-
-
- - Switch to {type() === "yearly" ? "lifetime" : "yearly"} - - -
-
-
- -
-
-
-
-
    - {[ - "Commercial Use of Cap Recorder + Editor", - "Community Support", - ].map((feature) => ( -
  • -
    - -
    - - {feature} - -
  • - ))} -
-
-
-
-
-
- { - await generalSettingsStore.set({ - commercialLicense: { - activatedOn: Date.now(), - expiryDate: value.expiryDate ?? null, - refresh: value.refresh, - licenseKey: value.licenseKey, - }, - }); - }} - /> - - ); -} diff --git a/apps/desktop/src/routes/(window-chrome)/settings.tsx b/apps/desktop/src/routes/(window-chrome)/settings.tsx index 3aee9259737..c3f8864981b 100644 --- a/apps/desktop/src/routes/(window-chrome)/settings.tsx +++ b/apps/desktop/src/routes/(window-chrome)/settings.tsx @@ -46,6 +46,11 @@ export default function Settings(props: RouteSectionProps) { name: "Integrations", icon: IconLucideUnplug, }, + { + href: "license", + name: "License", + icon: IconLucideGift, + }, { href: "experimental", name: "Experimental", diff --git a/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx b/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx index c6740bcfae2..38b44c65f6b 100644 --- a/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx +++ b/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx @@ -41,10 +41,10 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
-

+

Experimental Features

-

+

These features are still in development and may not work as expected.

diff --git a/apps/desktop/src/routes/(window-chrome)/settings/license.tsx b/apps/desktop/src/routes/(window-chrome)/settings/license.tsx new file mode 100644 index 00000000000..af346be3863 --- /dev/null +++ b/apps/desktop/src/routes/(window-chrome)/settings/license.tsx @@ -0,0 +1,331 @@ +import { createRive } from "@aerofoil/rive-solid-canvas"; +import { Button } from "@cap/ui-solid"; +import { licenseContract } from "@cap/web-api-contract"; +import { useNavigate } from "@solidjs/router"; +import { createMutation, useQueryClient } from "@tanstack/solid-query"; +import * as tauriShell from "@tauri-apps/plugin-shell"; +import { ClientInferResponseBody } from "@ts-rest/core"; +import { + createResource, + createSignal, + Match, + Show, + Suspense, + Switch, +} from "solid-js"; +import { generalSettingsStore } from "~/store"; +import { createLicenseQuery } from "~/utils/queries"; +import { commands } from "~/utils/tauri"; +import { licenseApiClient } from "~/utils/web-api"; +import PricingRive from "../../../assets/rive/pricing.riv"; +import { Input } from "../../editor/ui"; + +export default function Page() { + const license = createLicenseQuery(); + const navigate = useNavigate(); + const queryClient = useQueryClient(); + + return ( +
+
+

Commercial License

+

+ Permits using Cap for commercial purposes, but without paying for + cloud features. + +
+ Need cloud features?{" "} + +
+

+
+ }> + +
+
+
+

+ Cap Pro License +

+
+

+ Your account is upgraded to{" "} + Cap Pro and + already includes a commercial license. +

+
+
+
+ + {(license) => ( +
+
+
+ +

+ Commercial License +

+
+
+ +
+                    {license().licenseKey}
+                  
+
+ + {(expiry) => ( +
+ +

+ {new Date(expiry()).toLocaleDateString()} +

+
+ )} +
+
+
+ +
+
+
+ )} + + +
+ ); +} + +function LicenseKeyActivate(props: { + onActivated: ( + value: ClientInferResponseBody< + (typeof licenseContract)["activateCommercialLicense"], + 200 + > & { licenseKey: string } + ) => void; +}) { + const [store] = createResource(() => generalSettingsStore.get()); + const queryClient = useQueryClient(); + + return ( + + + {(generalSettings) => { + const [licenseKey, setLicenseKey] = createSignal(""); + + const activateLicenseKey = createMutation(() => ({ + mutationFn: async (vars: { licenseKey: string }) => { + const resp = await licenseApiClient.activateCommercialLicense({ + headers: { + licensekey: vars.licenseKey, + instanceid: generalSettings().instanceId!, + }, + body: { reset: false }, + }); + + if (resp.status === 200) return resp.body; + if ( + typeof resp.body === "object" && + resp.body && + "message" in resp.body + ) + throw resp.body.message; + throw new Error((resp.body as any).toString()); + }, + onSuccess: (value, { licenseKey }) => { + props.onActivated({ ...value, licenseKey }); + queryClient.refetchQueries({ queryKey: ["bruh"] }); + }, + })); + + return ( +
+
+

Have a license key?

+ setLicenseKey(e.currentTarget.value)} + class="w-full bg-gray-3 border-gray-4" + /> +
+ +
+ +

+ {String(activateLicenseKey.error)} +

+
+
+
+ ); + }} +
+
+ ); +} + +type CommercialLicenseType = "yearly" | "lifetime"; +function CommercialLicensePurchase() { + const queryClient = useQueryClient(); + + const [type, setType] = createSignal("yearly"); + + const [isCommercialAnnual, setIsCommercialAnnual] = createSignal(true); + + const { rive: CommercialRive, RiveComponent: Commercial } = createRive( + () => ({ + src: PricingRive, + autoplay: true, + artboard: "commercial", + animations: ["card-stack"], + }) + ); + + const openCommercialCheckout = createMutation(() => ({ + mutationFn: async () => { + const resp = await licenseApiClient.createCommercialCheckoutUrl({ + body: { type: isCommercialAnnual() ? "yearly" : "lifetime" }, + }); + + if (resp.status === 200) { + commands.openExternalLink(resp.body.url); + } + }, + })); + + return ( + <> +
+
+ {/* Left Column */} +
{ + const riveInstance = CommercialRive(); + if (riveInstance) { + // Stop any current animations first + riveInstance.stop(); + // Play the enter animation + riveInstance.play("cards"); + } + }} + onMouseLeave={() => { + const riveInstance = CommercialRive(); + if (riveInstance) { + // Stop any current animations first + riveInstance.stop(); + // Play the leave animation + riveInstance.play("card-stack"); + } + }} + class="flex flex-col gap-4 items-center p-5 rounded-t-xl border md:rounded-tr-none md:rounded-tl-xl md:rounded-bl-xl border-gray-4 md:w-1/2 bg-gray-3" + > + +
+

+ Commercial License +

+

+ For commercial use +

+
+
+

+ {isCommercialAnnual() ? "$29" : "$58"} + .00 / +

+

+ {isCommercialAnnual() ? "billed annually" : "one-time payment"} +

+
+
setIsCommercialAnnual((v) => !v)} + class="px-3 py-2 text-center rounded-full border border-transparent transition-all duration-200 cursor-pointer w-fit bg-gray-5 hover:border-gray-400" + > +

+ Switch to {isCommercialAnnual() ? "lifetime" : "yearly"}:{" "} + + {isCommercialAnnual() ? "$58" : "$29"} + +

+
+ +
+ + {/* Right Column */} +
+
    + {[ + "Commercial Use of Cap Recorder + Editor", + "Community Support", + "Local-only features", + "Perpetual license option", + ].map((feature) => ( +
  • +
    + +
    + + {feature} + +
  • + ))} +
+
+
+
+ + { + await generalSettingsStore.set({ + commercialLicense: { + activatedOn: Date.now(), + expiryDate: value.expiryDate ?? null, + refresh: value.refresh, + licenseKey: value.licenseKey, + }, + }); + await queryClient.refetchQueries({ queryKey: ["bruh"] }); + }} + /> + + ); +} diff --git a/apps/desktop/src/routes/(window-chrome)/upgrade.tsx b/apps/desktop/src/routes/(window-chrome)/upgrade.tsx index 01a8f93394b..178e105a21a 100644 --- a/apps/desktop/src/routes/(window-chrome)/upgrade.tsx +++ b/apps/desktop/src/routes/(window-chrome)/upgrade.tsx @@ -1,7 +1,7 @@ import { createRive } from "@aerofoil/rive-solid-canvas"; import { Button } from "@cap/ui-solid"; import { action, useAction } from "@solidjs/router"; -import { createMutation } from "@tanstack/solid-query"; +import { createMutation, useQueryClient } from "@tanstack/solid-query"; import { invoke } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import { getCurrentWindow, Window } from "@tauri-apps/api/window"; @@ -284,34 +284,32 @@ export default function Page() { {!upgradeComplete() && ( <> {license.data?.type === "commercial" ? ( -
+
-
-

- Your Commercial License -

-

- License details for Cap commercial use +

+

Commercial License

+

+ Your license details for Cap commercial use

-
-