Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
use presigned put instead of presigned post (#612)
Brendan Allan7cbd8f688d36
diff --git a/.gitignore b/.gitignoreindex 85a6803fa..b88fcb3f4 100644--- a/.gitignore+++ b/.gitignore@@ -45,4 +45,5 @@ tauri.windows.conf.json.sst# Cursor-.cursor\ No newline at end of file+.cursor+.env*.localdiff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex a25ba6013..c3a16f8f1 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -620,25 +620,12 @@ async fn handle_recording_finish(let _ = screenshot_task.await;if video_upload_succeeded {- let (screenshot_url, screenshot_form) = match prepare_screenshot_upload(+ let resp = prepare_screenshot_upload(&app,&video_upload_info.config.clone(),display_screenshot,)- .await- {- Ok(v) => v,- Err(e) => {- error!("Failed to prepare screenshot upload: {e}");- return;- }- };-- let resp = reqwest::Client::new()- .post(screenshot_url)- .multipart(screenshot_form)- .send()- .await;+ .await;match resp {Ok(r)diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex 65b9d40d6..6be5d9067 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -1,13 +1,18 @@// credit @filleduchaos+use axum::http::{HeaderMap, HeaderName, HeaderValue};use cap_utils::spawn_actor;use flume::Receiver;use futures::{stream, StreamExt};use image::codecs::jpeg::JpegEncoder;use image::ImageReader;+use reqwest::header::CONTENT_LENGTH;use reqwest::{multipart::Form, StatusCode};+use serde_json::json;+use std::collections::HashMap;use std::io::SeekFrom;use std::path::PathBuf;+use std::str::FromStr;use std::sync::Arc;use std::time::Duration;use tauri::{AppHandle, Manager, Runtime};@@ -226,7 +231,7 @@ pub async fn upload_video(},)?;- let (upload_url, form) = presigned_s3_url(app, body).await?;+ let presigned_put = presigned_s3_put(app, body).await?;let file = tokio::fs::File::open(&file_path).await@@ -258,36 +263,24 @@ pub async fn upload_video(}});- // Create a stream that reports progress- let file_part = reqwest::multipart::Part::stream_with_length(- reqwest::Body::wrap_stream(progress_stream),- total_size as u64,- )- .file_name(file_name.clone())- .mime_str("video/mp4")- .map_err(|e| format!("Error setting MIME type: {}", e))?;-- let form = form.part("file", file_part);-let screenshot_upload = match screenshot_path {Some(screenshot_path) if screenshot_path.exists() => {- Some(prepare_screenshot_upload(app, &s3_config, screenshot_path).await?)+ Some(prepare_screenshot_upload(app, &s3_config, screenshot_path))}_ => None,};+ let video_upload = client+ .put(presigned_put)+ .body(reqwest::Body::wrap_stream(progress_stream))+ .header(CONTENT_LENGTH, metadata.len());+let (video_upload, screenshot_result): (Result<reqwest::Response, reqwest::Error>,- Option<Result<reqwest::Response, reqwest::Error>>,- ) = tokio::join!(client.post(upload_url).multipart(form).send(), async {- if let Some((screenshot_url, screenshot_form)) = screenshot_upload {- Some(- client- .post(screenshot_url)- .multipart(screenshot_form)- .send()- .await,- )+ Option<Result<reqwest::Response, String>>,+ ) = tokio::join!(video_upload.send(), async {+ if let Some(screenshot_req) = screenshot_upload {+ Some(screenshot_req.await)} else {None}@@ -357,21 +350,16 @@ pub async fn upload_image(app: &AppHandle, file_path: PathBuf) -> Result<Uploade},};- let (upload_url, mut form) = presigned_s3_url_image(app, body).await?;+ let presigned_put = presigned_s3_put(app, body).await?;let file_content = tokio::fs::read(&file_path).await.map_err(|e| format!("Failed to read file: {}", e))?;- let file_part = reqwest::multipart::Part::bytes(file_content)- .file_name(file_name.clone())- .mime_str("image/jpeg")- .map_err(|e| format!("Error setting MIME type: {}", e))?;- form = form.part("file", file_part);-let response = client- .post(upload_url)- .multipart(form)+ .put(presigned_put)+ .header(CONTENT_LENGTH, file_content.len())+ .body(file_content).send().await.map_err(|e| format!("Failed to send upload file request: {}", e))?;@@ -400,81 +388,6 @@ pub async fn upload_image(app: &AppHandle, file_path: PathBuf) -> Result<Uploade))}-pub async fn upload_audio(app: &AppHandle, file_path: PathBuf) -> Result<UploadedAudio, String> {- let file_name = file_path- .file_name()- .and_then(|name| name.to_str())- .ok_or("Invalid file path")?- .to_string();-- let client = reqwest::Client::new();- let s3_config = create_or_get_video(app, false, None, None).await?;-- let file_key = format!("{}/{}/{}", s3_config.user_id, s3_config.id, file_name);-- println!("File key: {file_key}");-- let body = build_audio_upload_body(- &file_path,- S3UploadBody {- user_id: s3_config.user_id.clone(),- file_key: file_key.clone(),- aws_bucket: s3_config.aws_bucket.clone(),- aws_region: s3_config.aws_region.clone(),- aws_endpoint: s3_config.aws_endpoint.clone(),- },- )?;-- let (upload_url, mut form) = presigned_s3_url_audio(app, body).await?;-- let file_content = tokio::fs::read(&file_path)- .await- .map_err(|e| format!("Failed to read file: {}", e))?;-- let mime_type = if file_name.ends_with(".mp3") {- "audio/mpeg"- } else {- "audio/wav"- };-- let file_part = reqwest::multipart::Part::bytes(file_content)- .file_name(file_name.clone())- .mime_str(mime_type)- .map_err(|e| format!("Error setting MIME type: {}", e))?;- form = form.part("file", file_part);-- let response = client- .post(upload_url)- .multipart(form)- .send()- .await- .map_err(|e| format!("Failed to send upload file request: {}", e))?;-- if response.status().is_success() {- println!("Audio file uploaded successfully");- return Ok(UploadedAudio {- link: app.make_app_url(format!("/s/{}", &s3_config.id)).await,- id: s3_config.id.clone(),- config: s3_config,- });- }-- let status = response.status();- let error_body = response- .text()- .await- .unwrap_or_else(|_| "<no response body>".to_string());- tracing::error!(- "Failed to upload audio file. Status: {}. Body: {}",- status,- error_body- );- Err(format!(- "Failed to upload audio file. Status: {}. Body: {}",- status, error_body- ))-}-pub async fn create_or_get_video(app: &AppHandle,is_screenshot: bool,@@ -518,116 +431,38 @@ pub async fn create_or_get_video(Ok(config)}-async fn presigned_s3_url(- app: &AppHandle,- body: S3VideoUploadBody,-) -> Result<(String, Form), String> {- let response = app- .authed_api_request("/api/upload/signed", |client, url| {- client.post(url).json(&serde_json::json!(body))- })- .await- .map_err(|e| format!("Failed to send request to Next.js handler: {}", e))?;-- if response.status() == StatusCode::UNAUTHORIZED {- return Err("Failed to authenticate request; please log in again".into());+async fn presigned_s3_put(app: &AppHandle, body: impl Serialize) -> Result<String, String> {+ #[derive(Deserialize, Debug)]+ struct Data {+ url: String,}- let presigned_post_data = response- .json::<serde_json::Value>()- .await- .map_err(|e| format!("Failed to deserialize server response: {}", e))?;-- let fields = presigned_post_data["presignedPostData"]["fields"]- .as_object()- .ok_or("Fields object is missing or not an object")?;- let post_url = presigned_post_data["presignedPostData"]["url"]- .as_str()- .ok_or("URL is missing or not a string")?- .to_string();-- let mut form = Form::new();-- for (key, value) in fields.iter() {- let value_str = value- .as_str()- .ok_or(format!("Value for key '{}' is not a string", key))?;- form = form.text(key.to_string(), value_str.to_owned());+ #[derive(Deserialize, Debug)]+ #[serde(rename_all = "camelCase")]+ struct Wrapper {+ presigned_put_data: Data,}- Ok((post_url, form))-}--async fn presigned_s3_url_image(- app: &AppHandle,- body: S3ImageUploadBody,-) -> Result<(String, Form), String> {let response = app.authed_api_request("/api/upload/signed", |client, url| {- client.post(url).json(&serde_json::json!(body))+ let mut body_json = json!(body);+ let a = body_json.as_object_mut().unwrap();+ a.insert("method".to_string(), json!("put"));+ client.post(url).json(&json!(body_json))}).await.map_err(|e| format!("Failed to send request to Next.js handler: {}", e))?;- let presigned_post_data = response- .json::<serde_json::Value>()- .await- .map_err(|e| format!("Failed to deserialize server response: {}", e))?;-- let fields = presigned_post_data["presignedPostData"]["fields"]- .as_object()- .ok_or("Fields object is missing or not an object")?;- let post_url = presigned_post_data["presignedPostData"]["url"]- .as_str()- .ok_or("URL is missing or not a string")?- .to_string();-- let mut form = Form::new();-- for (key, value) in fields.iter() {- let value_str = value- .as_str()- .ok_or(format!("Value for key '{}' is not a string", key))?;- form = form.text(key.to_string(), value_str.to_owned());+ if response.status() == StatusCode::UNAUTHORIZED {+ return Err("Failed to authenticate request; please log in again".into());}- Ok((post_url, form))-}--async fn presigned_s3_url_audio(- app: &AppHandle,- body: S3AudioUploadBody,-) -> Result<(String, Form), String> {- let response = app- .authed_api_request("/api/upload/signed", |client, url| {- client.post(url).json(&serde_json::json!(body))- })- .await- .map_err(|e| format!("Failed to send request to Next.js handler: {}", e))?;-- let presigned_post_data = response- .json::<serde_json::Value>()+ let Wrapper { presigned_put_data } = response+ .json::<Wrapper>().await.map_err(|e| format!("Failed to deserialize server response: {}", e))?;- let fields = presigned_post_data["presignedPostData"]["fields"]- .as_object()- .ok_or("Fields object is missing or not an object")?;- let post_url = presigned_post_data["presignedPostData"]["url"]- .as_str()- .ok_or("URL is missing or not a string")?- .to_string();-- let mut form = Form::new();-- for (key, value) in fields.iter() {- let value_str = value- .as_str()- .ok_or(format!("Value for key '{}' is not a string", key))?;- form = form.text(key.to_string(), value_str.to_owned());- }-- Ok((post_url, form))+ Ok(presigned_put_data.url)}fn build_video_upload_body(@@ -692,81 +527,11 @@ fn build_audio_upload_body(})}-pub async fn upload_individual_file(- app: &AppHandle,- file_path: PathBuf,- s3_config: S3UploadMeta,- file_name: &str,- is_audio: bool,-) -> Result<(), String> {- let client = reqwest::Client::new();-- let file_key = format!(- "{}/{}/individual/{}",- s3_config.user_id, s3_config.id, file_name- );-- let base_upload_body = S3UploadBody {- user_id: s3_config.user_id.clone(),- file_key: file_key.clone(),- aws_bucket: s3_config.aws_bucket.clone(),- aws_region: s3_config.aws_region.clone(),- aws_endpoint: s3_config.aws_endpoint.clone(),- };-- let (upload_url, mut form) = if is_audio {- let audio_body = build_audio_upload_body(&file_path, base_upload_body)?;- presigned_s3_url_audio(app, audio_body).await?- } else {- let video_body = build_video_upload_body(&file_path, base_upload_body)?;- presigned_s3_url(app, video_body).await?- };-- let file_content = tokio::fs::read(&file_path)- .await- .map_err(|e| format!("Failed to read file: {}", e))?;-- let mime_type = if is_audio { "audio/mpeg" } else { "video/mp4" };-- let file_part = reqwest::multipart::Part::bytes(file_content)- .file_name(file_name.to_string())- .mime_str(mime_type)- .map_err(|e| format!("Error setting MIME type: {}", e))?;- form = form.part("file", file_part);-- let response = client- .post(upload_url)- .multipart(form)- .send()- .await- .map_err(|e| format!("Failed to send upload file request: {}", e))?;-- if response.status().is_success() {- println!("Individual file uploaded successfully");- Ok(())- } else {- let status = response.status();- let error_body = response- .text()- .await- .unwrap_or_else(|_| "<no response body>".to_string());- Err(format!(- "Failed to upload individual file. Status: {}. Body: {}",- status, error_body- ))- }-}-pub async fn prepare_screenshot_upload(app: &AppHandle,s3_config: &S3UploadMeta,screenshot_path: PathBuf,-) -> Result<(String, Form), String> {- let file_name = screenshot_path- .file_name()- .and_then(|name| name.to_str())- .ok_or("Invalid screenshot file path")?- .to_string();+) -> Result<reqwest::Response, String> {let file_key = format!("{}/{}/screenshot/screen-capture.jpg",s3_config.user_id, s3_config.id@@ -782,17 +547,17 @@ pub async fn prepare_screenshot_upload(},};- let (upload_url, mut form) = presigned_s3_url_image(app, body).await?;+ let presigned_put = presigned_s3_put(app, body).await?;let compressed_image = compress_image(screenshot_path).await?;- let file_part = reqwest::multipart::Part::bytes(compressed_image)- .file_name(file_name)- .mime_str("image/jpeg")- .map_err(|e| format!("Error setting MIME type for screenshot: {}", e))?;- form = form.part("file", file_part);-- Ok((upload_url, form))+ reqwest::Client::new()+ .put(presigned_put)+ .header(CONTENT_LENGTH, compressed_image.len())+ .body(compressed_image)+ .send()+ .await+ .map_err(|e| format!("Error uploading screenshot: {}", e))}async fn compress_image(path: PathBuf) -> Result<Vec<u8>, String> {diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 06aa70dde..d7b0bcaa6 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -321,7 +321,7 @@ export type ExportEstimates = { duration_seconds: number; estimated_time_secondsexport type ExportSettings = { fps: number; resolution_base: XY<number>; compression: ExportCompression }export type Flags = { captions: boolean }export type FramesRendered = { renderedCount: number; totalFrames: number; type: "FramesRendered" }-export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; hapticsEnabled?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; customCursorCapture?: boolean; serverUrl?: string;+export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; hapticsEnabled?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; customCursorCapture?: boolean; serverUrl?: string;/*** @deprecated*/diff --git a/apps/web/app/api/upload/[...route]/signed.ts b/apps/web/app/api/upload/[...route]/signed.tsindex 54f879e2c..0846370c6 100644--- a/apps/web/app/api/upload/[...route]/signed.ts+++ b/apps/web/app/api/upload/[...route]/signed.ts@@ -8,18 +8,16 @@ import {CreateInvalidationCommand,} from "@aws-sdk/client-cloudfront";import { db } from "@cap/database";-import { getCurrentUser } from "@cap/database/auth/session";import { s3Buckets } from "@cap/database/schema";import { eq } from "drizzle-orm";-import { cookies } from "next/headers";-import type { NextRequest } from "next/server";import { serverEnv } from "@cap/env";import { Hono } from "hono";import { zValidator } from "@hono/zod-validator";import { z } from "zod";-import { handle } from "hono/vercel";-import { corsMiddleware, withAuth } from "../../utils";+import { withAuth } from "../../utils";+import { getSignedUrl } from "@aws-sdk/s3-request-presigner";+import { PutObjectCommand } from "@aws-sdk/client-s3";export const app = new Hono().use(withAuth);@@ -34,12 +32,20 @@ app.post(resolution: z.string().optional(),videoCodec: z.string().optional(),audioCodec: z.string().optional(),+ method: z.union([z.literal("post"), z.literal("put")]).default("post"),})),async (c) => {const user = c.get("user");- const { fileKey, duration, bandwidth, resolution, videoCodec, audioCodec } =- c.req.valid("json");+ const {+ fileKey,+ duration,+ bandwidth,+ resolution,+ videoCodec,+ audioCodec,+ method,+ } = c.req.valid("json");try {const [bucket] = await db()@@ -116,33 +122,48 @@ app.post(? "application/x-mpegURL": "video/mp2t";- const Fields = {- "Content-Type": contentType,- "x-amz-meta-userid": user.id,- "x-amz-meta-duration": duration ?? "",- "x-amz-meta-bandwidth": bandwidth ?? "",- "x-amz-meta-resolution": resolution ?? "",- "x-amz-meta-videocodec": videoCodec ?? "",- "x-amz-meta-audiocodec": audioCodec ?? "",- };-const bucketName = await getS3Bucket(bucket);- const presignedPostData: PresignedPost = await createPresignedPost(- s3Client,- { Bucket: bucketName, Key: fileKey, Fields, Expires: 1800 }- );+ let data;+ if (method === "post") {+ const Fields = {+ "Content-Type": contentType,+ "x-amz-meta-userid": user.id,+ "x-amz-meta-duration": duration ?? "",+ "x-amz-meta-bandwidth": bandwidth ?? "",+ "x-amz-meta-resolution": resolution ?? "",+ "x-amz-meta-videocodec": videoCodec ?? "",+ "x-amz-meta-audiocodec": audioCodec ?? "",+ };++ data = await createPresignedPost(s3Client, {+ Bucket: bucketName,+ Key: fileKey,+ Fields,+ Expires: 1800,+ });+ } else if (method === "put") {+ const presignedUrl = await getSignedUrl(+ s3Client,+ new PutObjectCommand({+ Bucket: bucketName,+ Key: fileKey,+ ContentType: contentType,+ Metadata: {+ userid: user.id,+ duration: duration ?? "",+ bandwidth: bandwidth ?? "",+ resolution: resolution ?? "",+ videocodec: videoCodec ?? "",+ audiocodec: audioCodec ?? "",+ },+ }),+ { expiresIn: 1800 }+ );- // When not using aws s3, we need to transform the url to the local endpoint- if (- serverEnv().CAP_AWS_BUCKET_URL &&- !serverEnv().CAP_AWS_ENDPOINT?.endsWith("s3-accelerate.amazonaws.com")- ) {- const endpoint = serverEnv().CAP_AWS_ENDPOINT;- const bucket = serverEnv().CAP_AWS_BUCKET;- const newUrl = `${endpoint}/${bucket}/`;- presignedPostData.url = newUrl;+ data = { url: presignedUrl, fields: {} };}+ console.log({ data });console.log("Presigned URL created successfully");@@ -162,7 +183,8 @@ app.post(}}- return c.json({ presignedPostData });+ if (method === "post") return c.json({ presignedPostData: data });+ else return c.json({ presignedPutData: data });} catch (s3Error) {console.error("S3 operation failed:", s3Error);throw new Error(diff --git a/packages/database/auth/auth-options.ts b/packages/database/auth/auth-options.tsindex 3ed529711..19dae215f 100644--- a/packages/database/auth/auth-options.ts+++ b/packages/database/auth/auth-options.ts@@ -103,20 +103,20 @@ export const authOptions = (): NextAuthOptions => {async signIn({ user, account, isNewUser }) {if (isNewUser) {const organizationId = nanoId();-+await db().insert(organizations).values({id: organizationId,name: "My Organization",ownerId: user.id,});-+await db().insert(organizationMembers).values({id: nanoId(),userId: user.id,organizationId: organizationId,role: "owner",});-+await db().update(users).set({ activeOrganizationId: organizationId })@@ -160,5 +160,5 @@ export const authOptions = (): NextAuthOptions => {};},},- }+ };};