Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Screenshot upload share/metadata
Richie McIlroydda04448d3e6
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 562529daa..cce34a33d 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -1478,7 +1478,7 @@ async fn upload_rendered_video(#[tauri::command]#[specta::specta]-async fn upload_screenshot(app: AppHandle, screenshot_path: PathBuf) -> Result<(), String> {+async fn upload_screenshot(app: AppHandle, screenshot_path: PathBuf) -> Result<String, String> {let Ok(Some(auth)) = AuthStore::get(&app) else {println!("not authenticated!");return Err("Not authenticated".to_string());@@ -1486,32 +1486,40 @@ async fn upload_screenshot(app: AppHandle, screenshot_path: PathBuf) -> Result<(println!("Uploading screenshot: {:?}", screenshot_path);- let uploaded_screenshot = upload_image(auth.token, screenshot_path.clone(), true)- .await- .unwrap();-let screenshot_dir = screenshot_path.parent().unwrap().to_path_buf();- let meta_path = screenshot_dir.join("recording-meta.json");+ let mut meta = RecordingMeta::load_for_project(&screenshot_dir).unwrap();- let mut meta = RecordingMeta::load_for_project(&meta_path).unwrap();+ let share_link = if let Some(sharing) = meta.sharing.as_ref() {+ // Screenshot already uploaded, use existing link+ println!("Screenshot already uploaded, using existing link");+ sharing.link.clone()+ } else {+ // Upload the screenshot+ let uploaded = upload_image(auth.token, screenshot_path.clone())+ .await+ .map_err(|e| e.to_string())?;- meta.sharing = Some(SharingMeta {- link: uploaded_screenshot.link.clone(),- id: uploaded_screenshot.id.clone(),- });- meta.save_for_project();- RecordingMetaChanged {- id: screenshot_path- .file_stem()- .unwrap()- .to_str()- .unwrap()- .to_string(),- }- .emit(&app)- .ok();+ meta.sharing = Some(SharingMeta {+ link: uploaded.link.clone(),+ id: uploaded.id.clone(),+ });+ meta.save_for_project();- println!("Copying to clipboard: {:?}", uploaded_screenshot.link);+ RecordingMetaChanged {+ id: screenshot_path+ .file_stem()+ .unwrap()+ .to_str()+ .unwrap()+ .to_string(),+ }+ .emit(&app)+ .ok();++ uploaded.link+ };++ println!("Copying to clipboard: {:?}", share_link);#[cfg(target_os = "macos")]{@@ -1525,7 +1533,7 @@ async fn upload_screenshot(app: AppHandle, screenshot_path: PathBuf) -> Result<(let pasteboard: id = NSPasteboard::generalPasteboard(nil);NSPasteboard::clearContents(pasteboard);- let ns_string = NSString::alloc(nil).init_str(&uploaded_screenshot.link);+ let ns_string = NSString::alloc(nil).init_str(&share_link);let objects: id = NSArray::arrayWithObject(nil, ns_string);@@ -1534,7 +1542,7 @@ async fn upload_screenshot(app: AppHandle, screenshot_path: PathBuf) -> Result<(}}- Ok(())+ Ok(share_link)}#[tauri::command]@@ -1733,23 +1741,14 @@ struct RecordingMetaChanged {#[tauri::command(async)]#[specta::specta]-fn get_recording_meta(- app: AppHandle,- id: String,- file_type: String,-) -> Result<RecordingMeta, String> {- println!(- "get_recording_meta called with id: {}, file_type: {}",- id, file_type- );+fn get_recording_meta(app: AppHandle, id: String, file_type: String) -> RecordingMeta {let meta_path = match file_type.as_str() {"recording" => recording_path(&app, &id),"screenshot" => screenshot_path(&app, &id),- _ => return Err(format!("Invalid file type: {}", file_type)),+ _ => panic!("Invalid file type: {}", file_type),};- RecordingMeta::load_for_project(&meta_path)- .map_err(|e| format!("Failed to load recording meta for {}: {}", id, e))+ RecordingMeta::load_for_project(&meta_path).unwrap()}#[cfg_attr(mobile, tauri::mobile_entry_point)]diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex 0309ab315..2dc14e5c4 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -167,11 +167,7 @@ pub async fn upload_video())}-pub async fn upload_image(- auth_token: String,- file_path: PathBuf,- solo_screenshot: bool,-) -> Result<UploadedImage, String> {+pub async fn upload_image(auth_token: String, file_path: PathBuf) -> Result<UploadedImage, String> {let file_name = file_path.file_name().and_then(|name| name.to_str())@@ -181,16 +177,9 @@ pub async fn upload_image(let client = reqwest::Client::new();let server_url_base: &'static str = dotenvy_macro::dotenv!("NEXT_PUBLIC_URL");- let s3_config = get_s3_config(&client, server_url_base, &auth_token, solo_screenshot).await?;+ let s3_config = get_s3_config(&client, server_url_base, &auth_token, true).await?;- let file_key: String = if solo_screenshot {- format!("{}/{}/{}", s3_config.user_id, s3_config.id, file_name)- } else {- format!(- "{}/{}/screenshot/screen-capture.jpg",- s3_config.user_id, s3_config.id- )- };+ let file_key = format!("{}/{}/{}", s3_config.user_id, s3_config.id, file_name);println!("File key: {file_key}");diff --git a/apps/desktop/src/routes/prev-recordings.tsx b/apps/desktop/src/routes/prev-recordings.tsxindex b30c441fc..5d0766974 100644--- a/apps/desktop/src/routes/prev-recordings.tsx+++ b/apps/desktop/src/routes/prev-recordings.tsx@@ -10,6 +10,7 @@ import {Suspense,Switch,createEffect,+ createMemo,createResource,createSignal,onCleanup,@@ -18,7 +19,6 @@ import {import Tooltip from "@corvu/tooltip";import { Button } from "@cap/ui-solid";import { createElementBounds } from "@solid-primitives/bounds";-import { save } from "@tauri-apps/plugin-dialog";import { TransitionGroup } from "solid-transition-group";import { createStore, produce } from "solid-js/store";import { makePersisted } from "@solid-primitives/storage";@@ -26,24 +26,28 @@ import { makePersisted } from "@solid-primitives/storage";import { commands, events } from "~/utils/tauri";import { DEFAULT_PROJECT_CONFIG } from "./editor/projectConfig";import { createPresets } from "~/utils/createPresets";-import { basename } from "@tauri-apps/api/path";type MediaEntry = {path: string;prettyName: string;isNew: boolean;- type: "recording" | "screenshot";+ type?: "recording" | "screenshot";};export default function () {const presets = createPresets();- const [mediaEntries, setMediaEntries] = makePersisted(+ const [recordings, setRecordings] = makePersisted(createStore<MediaEntry[]>([]),- { name: "media-entries-store" }+ { name: "recordings-store" }+ );+ const [screenshots, setScreenshots] = makePersisted(+ createStore<MediaEntry[]>([]),+ { name: "screenshots-store" });- const addMediaEntry = (path: string, type: "recording" | "screenshot") => {- setMediaEntries(+ const addMediaEntry = (path: string, type?: "recording" | "screenshot") => {+ const setMedia = type === "screenshot" ? setScreenshots : setRecordings;+ setMedia(produce((state) => {if (state.some((entry) => entry.path === path)) return;const fileName = path.split("/").pop() || "";@@ -56,7 +60,7 @@ export default function () {);setTimeout(() => {- setMediaEntries(+ setMedia(produce((state) => {const index = state.findIndex((entry) => entry.path === path);if (index !== -1) {@@ -77,6 +81,8 @@ export default function () {addMediaEntry(event.payload.path, "screenshot");});+ const allMedia = createMemo(() => [...recordings, ...screenshots]);+return (<div class="w-screen h-[100vh] bg-transparent relative"><div class="w-full relative left-0 bottom-0 flex flex-col-reverse pl-[40px] pb-[80px] gap-4 h-full overflow-y-auto">@@ -88,17 +94,27 @@ export default function () {exitClass="opacity-100 translate-x-0"exitActiveClass="absolute">- <For each={mediaEntries}>- {(media, i) => {+ <For each={allMedia()}>+ {(media) => {const [ref, setRef] = createSignal<HTMLElement | null>(null);-+ console.log(media);const mediaId = media.path.split("/").pop()?.split(".")[0]!;-- const isRecording = media.type === "recording";+ const fileId =+ media.type === "recording"+ ? mediaId+ : media.path+ .split("screenshots/")[1]+ .split("/")[0]+ .replace(".cap", "");+ const isRecording = media.type !== "screenshot";const recordingMeta = createQuery(() => ({- queryKey: ["recordingMeta", mediaId],- queryFn: () => commands.getRecordingMeta(mediaId, media.type),+ queryKey: ["recordingMeta", fileId],+ queryFn: () =>+ commands.getRecordingMeta(+ fileId,+ isRecording ? "recording" : "screenshot"+ ),enabled: true,}));@@ -119,7 +135,6 @@ export default function () {},}));- //TODO: Use pretty name for cap recordingconst saveMedia = createMutation(() => ({mutationFn: async () => {const newFileName = isRecording@@ -275,13 +290,21 @@ export default function () {class="absolute left-3 top-3 z-20"tooltipText="Close"tooltipPlacement="right"- onClick={() =>- setMediaEntries(+ onClick={() => {+ const setMedia = isRecording+ ? setRecordings+ : setScreenshots;+ setMedia(produce((state) => {- state.splice(i(), 1);+ const index = state.findIndex(+ (entry) => entry.path === media.path+ );+ if (index !== -1) {+ state.splice(index, 1);+ }})- )- }+ );+ }}><IconCapCircleX class="size-[1rem]" /></TooltipIconButton>@@ -354,7 +377,10 @@ export default function () {tooltipPlacement="left"onClick={() => uploadMedia.mutate()}disabled={- copyMedia.isPending || saveMedia.isPending+ copyMedia.isPending ||+ saveMedia.isPending ||+ recordingMeta.isLoading ||+ recordingMeta.isError}><Switchdiff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 84aa37fe4..05a6832b3 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -192,7 +192,7 @@ async uploadRenderedVideo(videoId: string, project: ProjectConfiguration) : Promelse return { status: "error", error: e as any };}},-async uploadScreenshot(screenshotPath: string) : Promise<Result<null, string>> {+async uploadScreenshot(screenshotPath: string) : Promise<Result<string, string>> {try {return { status: "ok", data: await TAURI_INVOKE("upload_screenshot", { screenshotPath }) };} catch (e) {@@ -200,13 +200,8 @@ async uploadScreenshot(screenshotPath: string) : Promise<Result<null, string>> {else return { status: "error", error: e as any };}},-async getRecordingMeta(id: string, fileType: string) : Promise<Result<RecordingMeta, string>> {- try {- return { status: "ok", data: await TAURI_INVOKE("get_recording_meta", { id, fileType }) };-} catch (e) {- if(e instanceof Error) throw e;- else return { status: "error", error: e as any };-}+async getRecordingMeta(id: string, fileType: string) : Promise<RecordingMeta> {+ return await TAURI_INVOKE("get_recording_meta", { id, fileType });},async openFeedbackWindow() : Promise<void> {await TAURI_INVOKE("open_feedback_window");diff --git a/apps/web/app/api/desktop/video/create/route.ts b/apps/web/app/api/desktop/video/create/route.tsindex 9e15dd661..9501df19d 100644--- a/apps/web/app/api/desktop/video/create/route.ts+++ b/apps/web/app/api/desktop/video/create/route.ts@@ -20,8 +20,6 @@ export async function OPTIONS(req: NextRequest) {const origin = params.get("origin") || null;const originalOrigin = req.nextUrl.origin;- console.log("OPTIONS request received:", { origin, originalOrigin });-return new Response(null, {status: 200,headers: {@@ -88,7 +86,7 @@ export async function GET(req: NextRequest) {await db.insert(videos).values({id: id,- name: `My Cap Recording - ${formattedDate}`,+ name: `Cap ${isScreenshot ? "Screenshot" : "Recording"} - ${formattedDate}`,ownerId: user.id,awsRegion: awsRegion,awsBucket: awsBucket,