Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Smooth stop recording func, open cap.so/share URL
Richie McIlroy1530c2413f72
diff --git a/.env.example b/.env.exampleindex 444a34722..6cce076d6 100644--- a/.env.example+++ b/.env.example@@ -10,25 +10,31 @@# Update these with your Supabase details from your project settings > API# https://app.supabase.com/project/_/settings/api+###+### TODO: Consolidate next and vite env variables into one set of variables.+###+NEXT_PUBLIC_SUPABASE_URL=NEXT_PUBLIC_SUPABASE_ANON_KEY=-## Vite also needs their own values to expose them to the clientVITE_SUPABASE_URL=VITE_SUPABASE_ANON_KEY=-SUPABASE_SERVICE_ROLE_KEY=-NEXT_PUBLIC_ENVIRONMENT=developmentNEXT_PUBLIC_URL=http://localhost:3000+# For use with linking to web app+VITE_PUBLIC_URL=http://localhost:3000+## For use with AWS S3, to upload recorded caps. You can retrieve these credentials from your own AWS account.-AWS_ACCESS_KEY=-AWS_SECRET_KEY=-AWS_REGION=+## Uses CAP_ prefix to avoid conflict with env variables set in hosting environment. (e.g. Vercel)+CAP_AWS_ACCESS_KEY=+CAP_AWS_SECRET_KEY=+CAP_AWS_REGION=VITE_AWS_BUCKET=VITE_AWS_REGION=# - MISC, NOT REQUIRED FOR DEV ****************+SUPABASE_SERVICE_ROLE_KEY=NEXT_LOOPS_KEY=\ No newline at end of filediff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rsindex dc6071bd0..db6ae9940 100644--- a/apps/desktop/src-tauri/src/main.rs+++ b/apps/desktop/src-tauri/src/main.rs@@ -1,6 +1,7 @@#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]use std::sync::{Arc};+use std::sync::atomic::{AtomicBool};use tokio::sync::Mutex;use std::env;use tauri::{Manager};@@ -81,7 +82,7 @@ fn main() {upload_file,list_devices])- .manage(Arc::new(Mutex::new(RecordingState { screen_process: None, video_process: None, tx: None })))+ .manage(Arc::new(Mutex::new(RecordingState { screen_process: None, video_process: None, recording_options: None, upload_handles: Mutex::new(vec![]), shutdown_flag: Arc::new(AtomicBool::new(false))}))).plugin(tauri_plugin_context_menu::init()).run(tauri::generate_context!()).expect("Error while running tauri application");diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 4dcada8cb..5ce34608f 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -1,19 +1,25 @@use std::path::{Path, PathBuf};-use std::time::SystemTime;+use std::collections::HashSet;+use std::io::{self, BufReader, BufRead, ErrorKind};+use std::fs::File;use std::sync::Arc;use std::process::Stdio;-use tokio::sync::{Mutex, mpsc};+use std::sync::atomic::{AtomicBool, Ordering};+use tokio::sync::{Semaphore, Mutex};+use tokio::task::JoinHandle;+use tokio::time::{timeout, Duration};use serde::{Serialize, Deserialize};use tauri::State;use crate::utils::ffmpeg_path_as_str;use crate::upload::upload_file;-#[warn(dead_code)]pub struct RecordingState {pub screen_process: Option<tokio::process::Child>,pub video_process: Option<tokio::process::Child>,- pub tx: Option<mpsc::Sender<()>>,+ pub upload_handles: Mutex<Vec<JoinHandle<Result<(), String>>>>,+ pub recording_options: Option<RecordingOptions>,+ pub shutdown_flag: Arc<AtomicBool>,}#[derive(Debug, Serialize, Deserialize, Clone)]@@ -28,8 +34,6 @@ pub struct RecordingOptions {pub resolution: String,}-const FILE_MODIFICATION_THRESHOLD: u64 = 5;-#[tauri::command]pub async fn start_dual_recording(state: State<'_, Arc<Mutex<RecordingState>>>,@@ -37,6 +41,8 @@ pub async fn start_dual_recording() -> Result<(), String> {println!("Starting screen recording...");+ let shutdown_flag = Arc::new(AtomicBool::new(false));+let ffmpeg_binary_path_str = ffmpeg_path_as_str()?;let screen_chunks_dir = std::env::current_dir()@@ -77,51 +83,102 @@ pub async fn start_dual_recording(tokio::spawn(log_output(screen_stdout, "Screen stdout".to_string()));tokio::spawn(log_output(screen_stderr, "Screen stderr".to_string()));- // Video recording processlet video_stdout = video_child.stdout.take().unwrap();let video_stderr = video_child.stderr.take().unwrap();tokio::spawn(log_output(video_stdout, "Video stdout".to_string()));tokio::spawn(log_output(video_stderr, "Video stderr".to_string()));- let (tx, _rx) = mpsc::channel::<()>(1);-let mut guard = state.lock().await;- *guard = RecordingState {- screen_process: None,- video_process: None,- tx: Some(tx),- };+ guard.screen_process = Some(screen_child);+ guard.video_process = Some(video_child);+ guard.upload_handles = Mutex::new(vec![]);+ guard.recording_options = Some(options.clone());+ guard.shutdown_flag = shutdown_flag.clone();+drop(guard);tokio::join!(- start_upload_loop(screen_chunks_dir, options.clone(), "screen".to_string()),- start_upload_loop(video_chunks_dir, options.clone(), "video".to_string()),+ start_upload_loop(state.clone(), screen_chunks_dir, options.clone(), "screen".to_string(), shutdown_flag.clone()),+ start_upload_loop(state.clone(), video_chunks_dir, options.clone(), "video".to_string(), shutdown_flag.clone()),);Ok(())}#[tauri::command]-pub async fn stop_all_recordings(- state: State<'_, Arc<Mutex<RecordingState>>>,-) -> Result<(), String> {+pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -> Result<(), String> {+ println!("!!STOPPING screen recording...");+let mut guard = state.lock().await;- if let Some(screen_process) = guard.screen_process.take() {- screen_process.kill().await.map_err(|e| format!("Failed to stop screen recording: {}", e))?;+ guard.shutdown_flag.store(true, Ordering::SeqCst);++ if let Some(child_process) = &mut guard.screen_process {+ if let Err(e) = child_process.kill().await {+ eprintln!("Failed to kill the child process: {}", e);+ } else {+ println!("Child process terminated successfully.");+ }}+ if let Some(child_process) = &mut guard.video_process {+ if let Err(e) = child_process.kill().await {+ eprintln!("Failed to kill the child process: {}", e);+ } else {+ println!("Child process terminated successfully.");+ }+ }++ guard.screen_process = None;+ guard.video_process = None;++ let chunks_dir_screen = std::env::current_dir()+ .map_err(|e| format!("Cannot get current directory: {}", e))?+ .join("chunks/screen");++ let chunks_dir_video = std::env::current_dir()+ .map_err(|e| format!("Cannot get current directory: {}", e))?+ .join("chunks/video");- if let Some(video_process) = guard.video_process.take() {- video_process.kill().await.map_err(|e| format!("Failed to stop video recording: {}", e))?;+ let recording_options = guard.recording_options.clone();++ drop(guard);++ // Create join handles for the final uploads+ let handle_screen = upload_remaining_chunks(&chunks_dir_screen, recording_options.clone(), "screen");+ let handle_video = upload_remaining_chunks(&chunks_dir_video, recording_options.clone(), "video");++ // Await the final upload tasks+ tokio::select! {+ // Await either completion or an error from the screen upload task+ result = handle_screen => {+ if let Err(e) = result {+ eprintln!("Error uploading remaining screen chunks: {}", e);+ }+ }+ // Await either completion or an error from the video upload task+ result = handle_video => {+ if let Err(e) = result {+ eprintln!("Error uploading remaining video chunks: {}", e);+ }+ }}- // This code sends a stop message to the channel which is being listened to in the upload loop.- // This will allow you to terminate the loop gracefully, which is useful to ensure that all- // currently processed files are finished uploading before the recording stops.- if let Some(tx) = guard.tx.take() {- let _ = tx.send(()).await;+ let guard = state.lock().await;+ let mut upload_handles = guard.upload_handles.lock().await;++ // Drain the upload_handles to get ownership of the JoinHandles+ let handles: Vec<_> = upload_handles.drain(..).collect();++ // Explicitly drop the locks before awaiting the handles+ drop(upload_handles);+ drop(guard);++ // Await each of the JoinHandles to completion+ for handle in handles {+ let _ = handle.await.map_err(|e| e.to_string())?;}+ // All checks and uploads are done, return Ok(())Ok(())}@@ -155,13 +212,19 @@ async fn construct_recording_args(input_index: &str,) -> Result<Vec<String>, String> {let output_filename_pattern = format!("{}/recording_chunk_%03d.mkv", chunks_dir.display());+ let segment_list_filename = format!("{}/segment_list.txt", chunks_dir.display());++ ensure_segment_list_exists(PathBuf::from(&segment_list_filename))+ .map_err(|e| format!("Failed to ensure segment list file exists: {}", e))?;+let fps = if video_type == "screen" { "60" } else { &options.framerate };let preset = "ultrafast".to_string();- let crf = "23".to_string();+ let crf = "28".to_string();let pix_fmt = "nv12".to_string();let codec = "libx264".to_string();let gop = "30".to_string();- let segment_time = "10".to_string();+ let segment_time = "3".to_string();+ let segment_list_type = "flat".to_string();let input_string = format!("{}:none", input_index);match std::env::consts::OS {@@ -172,7 +235,6 @@ async fn construct_recording_args("-framerate".to_string(), fps.to_string(),"-i".to_string(), input_string.to_string(),"-c:v".to_string(), codec,- "-crf".to_string(), crf,"-preset".to_string(), preset,"-pix_fmt".to_string(), pix_fmt,"-g".to_string(), gop,@@ -180,6 +242,8 @@ async fn construct_recording_args("-f".to_string(), "segment".to_string(),"-segment_time".to_string(), segment_time,"-segment_format".to_string(), "matroska".to_string(),+ "-segment_list".to_string(), segment_list_filename,+ "-segment_list_type".to_string(), segment_list_type,"-reset_timestamps".to_string(), "1".to_string(),output_filename_pattern,])@@ -192,10 +256,13 @@ async fn construct_recording_args("-c:v".to_string(), codec,"-preset".to_string(), preset,"-pix_fmt".to_string(), pix_fmt,- "-fps_mode".to_string(), "vfr".to_string(),+ "-g".to_string(), gop,+ "-r".to_string(), fps.to_string(),"-f".to_string(), "segment".to_string(),"-segment_time".to_string(), segment_time,"-segment_format".to_string(), "matroska".to_string(),+ "-segment_list".to_string(), segment_list_filename,+ "-segment_list_type".to_string(), segment_list_type,"-reset_timestamps".to_string(), "1".to_string(),output_filename_pattern,])@@ -216,6 +283,8 @@ async fn construct_recording_args("-f".to_string(), "segment".to_string(),"-segment_time".to_string(), segment_time,"-segment_format".to_string(), "mpegts".to_string(),+ "-segment_list".to_string(), segment_list_filename,+ "-segment_list_type".to_string(), segment_list_type,"-reset_timestamps".to_string(), "1".to_string(),output_filename_pattern,])@@ -232,6 +301,8 @@ async fn construct_recording_args("-f".to_string(), "segment".to_string(),"-segment_time".to_string(), segment_time,"-segment_format".to_string(), "mpegts".to_string(),+ "-segment_list".to_string(), segment_list_filename,+ "-segment_list_type".to_string(), segment_list_type,"-reset_timestamps".to_string(), "1".to_string(),output_filename_pattern,])@@ -251,6 +322,8 @@ async fn construct_recording_args("-f".to_string(), "segment".to_string(),"-segment_time".to_string(), segment_time,"-segment_format".to_string(), "mpegts".to_string(),+ "-segment_list".to_string(), segment_list_filename,+ "-segment_list_type".to_string(), segment_list_type,"-reset_timestamps".to_string(), "1".to_string(),output_filename_pattern,])@@ -267,6 +340,8 @@ async fn construct_recording_args("-f".to_string(), "segment".to_string(),"-segment_time".to_string(), segment_time,"-segment_format".to_string(), "mpegts".to_string(),+ "-segment_list".to_string(), segment_list_filename,+ "-segment_list_type".to_string(), segment_list_type,"-reset_timestamps".to_string(), "1".to_string(),output_filename_pattern,])@@ -276,62 +351,195 @@ async fn construct_recording_args(}}-async fn start_upload_loop(chunks_dir: PathBuf, options: RecordingOptions, video_type: String) {- println!("Starting upload loop for {}...", video_type);+async fn start_upload_loop(+ state: State<'_, Arc<Mutex<RecordingState>>>,+ chunks_dir: PathBuf,+ options: RecordingOptions,+ video_type: String,+ shutdown_flag: Arc<AtomicBool>,+) {+ let segment_list_path = chunks_dir.join("segment_list.txt");- let upload_interval = std::time::Duration::from_secs(10);+ let mut watched_segments: HashSet<String> = HashSet::new();+ let upload_interval = std::time::Duration::from_secs(3);loop {- let chunks_dir_path = chunks_dir.clone();- let entries = match std::fs::read_dir(&chunks_dir_path) {- Ok(entries) => entries,- Err(e) => {- eprintln!("Failed to read chunks dir for {}: {}", video_type, e);- tokio::time::sleep(upload_interval).await;- continue;- }- };-- for entry in entries {- let entry = match entry {- Ok(e) => e,- Err(e) => {- eprintln!("ReadDir entry error for {}: {}", video_type, e);- continue;- }- };- let path = entry.path();- if path.is_file() && path.extension().map_or(false, |e| e == "mkv") {- // Skip files that have been recently modified- if let Ok(metadata) = std::fs::metadata(&path) {- if let Ok(modified) = metadata.modified() {- if SystemTime::now().duration_since(modified).unwrap_or_default().as_secs() < FILE_MODIFICATION_THRESHOLD {- println!("Skipping recently modified file: {}", path.display());- continue;- }- }- }+ if shutdown_flag.load(Ordering::SeqCst) {+ println!("Shutdown flag set, exiting upload loop for {}", video_type);+ break;+ }++ match load_segment_list(&segment_list_path) {+ Ok(new_segments) => {+ for segment_filename in new_segments {+ let segment_path = chunks_dir.join(&segment_filename);++ // Check if the segment is new and schedule it for upload+ if segment_path.is_file() && watched_segments.insert(segment_filename.clone()) {+ let filepath_str = segment_path.to_str().unwrap_or_default().to_owned();+ let options_clone = options.clone();+ let video_type_clone = video_type.clone();- let filepath_str = path.to_str().unwrap_or_default().to_owned();-- // Log the file path, and the video type in one print, starting with "Uploading video from"- println!("Uploading video for {}: {}", video_type, filepath_str);-- match upload_file(- options.clone(),- filepath_str.clone(),- video_type.clone(),- ).await {- Ok(file_key) => {- println!("Chunk uploaded: {}", file_key);- },- Err(e) => {- eprintln!("Failed to upload chunk {}: {}", filepath_str, e);+ let handle = tokio::spawn(async move {+ // Log the file path and the video type in one print, starting with "Uploading video from"+ println!("Uploading video for {}: {}", video_type_clone, filepath_str);++ match upload_file(Some(options_clone.clone()), filepath_str.clone(), video_type_clone.clone()).await {+ Ok(file_key) => {+ println!("Chunk uploaded: {}", file_key);+ },+ Err(e) => {+ eprintln!("Failed to upload chunk {}: {}", filepath_str, e);+ }+ }++ Ok(())+ });++ // Store the handle in the state for later awaits or cancels if required.+ let guard = state.lock().await;+ guard.upload_handles.lock().await.push(handle);}}}+ Err(e) => eprintln!("Failed to read segment list for {}: {}", video_type, e),}+ // Sleep for the interval before checking the segment list againtokio::time::sleep(upload_interval).await;}+}++fn ensure_segment_list_exists(file_path: PathBuf) -> io::Result<()> {+ match File::open(&file_path) {+ Ok(_) => (),+ Err(ref e) if e.kind() == ErrorKind::NotFound => {+ File::create(&file_path)?;+ },+ Err(e) => {+ return Err(e);+ },+ }+ Ok(())+}++fn load_segment_list(segment_list_path: &Path) -> io::Result<HashSet<String>> {+ let file = File::open(segment_list_path)?;+ let reader = BufReader::new(file);++ let mut segments = HashSet::new();+ for line_result in reader.lines() {+ let line = line_result?;+ if !line.is_empty() {+ segments.insert(line);+ }+ }++ Ok(segments)+}++async fn upload_remaining_chunks(+ chunks_dir: &PathBuf,+ options: Option<RecordingOptions>,+ video_type: &str,+) -> Result<(), String> {+ if let Some(actual_options) = options {+ tokio::time::sleep(Duration::from_secs(1)).await;++ let retry_interval = Duration::from_secs(2);+ let upload_timeout = Duration::from_secs(15);+ let file_stability_timeout = Duration::from_secs(1);+ let file_stability_checks = 2;++ // Get directory entries+ let entries = std::fs::read_dir(chunks_dir).map_err(|e| format!("Error reading directory: {}", e))?;++ // A semaphore to limit the number of concurrent uploads+ let semaphore = Arc::new(Semaphore::new(8));++ // Create upload tasks for each file entry+ let tasks: Vec<_> = entries.filter_map(|entry| entry.ok())+ .map(|entry| {+ let path = entry.path();+ if path.is_file() && path.extension().map_or(false, |e| e == "mkv") {+ let video_type = video_type.to_string();+ let semaphore_clone = semaphore.clone();+ let actual_options_clone = actual_options.clone();++ // Spawn a task to upload the file+ Some(tokio::spawn(async move {+ let _permit = semaphore_clone.acquire().await;+ let filepath_str = path.to_str().unwrap_or_default().to_owned();++ // Check for file size stability+ let mut last_size = 0;+ let mut stable_count = 0;+ while stable_count < file_stability_checks {+ if !path.exists() {+ eprintln!("File does not exist: {}", path.display());+ break; // Exit the loop if the file does not exist+ }+ match std::fs::metadata(&path) {+ Ok(metadata) => {+ let current_size = metadata.len();+ if last_size == current_size {+ stable_count += 1;+ } else {+ last_size = current_size;+ stable_count = 0;+ }+ },+ Err(e) => {+ eprintln!("Failed to get file metadata: {}", e);+ break; // Exit the loop if any other error occurs+ }+ }+ tokio::time::sleep(file_stability_timeout).await;+ }++ println!("File size stable: {}", filepath_str);++ // Proceed with upload after confirming file stability+ let mut attempts = 0;+ // Retry loop with timeout+ while attempts < 3 {+ attempts += 1;+ match timeout(upload_timeout, upload_file(Some(actual_options_clone.clone()), filepath_str.clone(), video_type.clone())).await {+ Ok(Ok(_)) => {+ // Upload succeeded+ println!("Successful upload on attempt {}", attempts);+ break; // Break out of the loop on success+ }+ Ok(Err(e)) => {+ // Upload failed but did not timeout+ eprintln!("Failed to upload (attempt {}): {}", attempts, e);+ }+ Err(_) => {+ // Upload attempt timed out+ eprintln!("Upload attempt timed out (attempt {})", attempts);+ }+ }+ // Wait for retry_interval before retrying+ tokio::time::sleep(retry_interval).await;+ }+ }))+ } else {+ None+ }+ })+ .collect();++ // Wait for all the tasks to finish+ for task in tasks {+ if let Some(handle) = task {+ if let Err(e) = handle.await {+ eprintln!("Failed to join task: {:?}", e);+ }+ }+ }++ Ok(())+ } else {+ Err("No recording options provided".to_string())+ }}\ No newline at end of filediff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex f4884a35e..39d85f6cc 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -6,105 +6,109 @@ use crate::recording::RecordingOptions;#[tauri::command]pub async fn upload_file(- options: RecordingOptions,+ options: Option<RecordingOptions>,file_path: String,- file_type: String+ file_type: String,) -> Result<String, String> {- println!("Uploading video...");-- let file_name = Path::new(&file_path)- .file_name()- .and_then(|name| name.to_str())- .ok_or("Invalid file path")?- .to_string();-- let file_key = format!("{}/{}/{}/{}", options.user_id, file_type, options.video_id, file_name);-- // Here we assume your server listens on localhost:3000 and the route is `api/upload/new`- let server_url = format!("http://localhost:3000/api/upload/new");-- // Create the request body for the Next.js handler- let body = serde_json::json!({- "userId": options.user_id,- "fileKey": file_key,- "awsBucket": options.aws_bucket,- "awsRegion": options.aws_region,- });-- let client = reqwest::Client::new();- let server_response = client.post(server_url)- .json(&body)- .send()- .await- .map_err(|e| format!("Failed to send request to Next.js handler: {}", e))?- .text()- .await- .map_err(|e| format!("Failed to read response from Next.js handler: {}", e))?;-- println!("Server response: {}", server_response);--- // Deserialize the server response- let presigned_post_data: JsonValue = serde_json::from_str(&server_response)- .map_err(|e| format!("Failed to deserialize server response: {}", e))?;-- // Construct the multipart form for the file upload- let fields = presigned_post_data["presignedPostData"]["fields"].as_object()- .ok_or("Fields object is missing or not an object")?;-- let mut form = reqwest::multipart::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());- }-- println!("Uploading file: {}", file_path);-- let file_bytes = tokio::fs::read(&file_path).await.map_err(|e| format!("Failed to read file: {}", e))?;- let file_part = reqwest::multipart::Part::bytes(file_bytes)- .file_name(file_name.clone())- .mime_str("application/octet-stream")- .map_err(|e| format!("Error setting MIME type: {}", e))?;-- form = form.part("file", file_part);-- let post_url = presigned_post_data["presignedPostData"]["url"].as_str()- .ok_or("URL is missing or not a string")?;-- println!("Uploading file to: {}", post_url);-- let response = client.post(post_url)- .multipart(form)- .send()- .await;-- match response {- Ok(response) if response.status().is_success() => {- println!("File uploaded successfully");+ if let Some(ref options) = options {+ println!("Uploading video...");++ let file_name = Path::new(&file_path)+ .file_name()+ .and_then(|name| name.to_str())+ .ok_or("Invalid file path")?+ .to_string();++ let file_key = format!("{}/{}/{}/{}", options.user_id, file_type, options.video_id, file_name);++ // Here we assume your server listens on localhost:3000 and the route is `api/upload/new`+ let server_url = format!("http://localhost:3000/api/upload/new");++ // Create the request body for the Next.js handler+ let body = serde_json::json!({+ "userId": options.user_id,+ "fileKey": file_key,+ "awsBucket": options.aws_bucket,+ "awsRegion": options.aws_region,+ });++ let client = reqwest::Client::new();+ let server_response = client.post(server_url)+ .json(&body)+ .send()+ .await+ .map_err(|e| format!("Failed to send request to Next.js handler: {}", e))?+ .text()+ .await+ .map_err(|e| format!("Failed to read response from Next.js handler: {}", e))?;++ println!("Server response: {}", server_response);+++ // Deserialize the server response+ let presigned_post_data: JsonValue = serde_json::from_str(&server_response)+ .map_err(|e| format!("Failed to deserialize server response: {}", e))?;++ // Construct the multipart form for the file upload+ let fields = presigned_post_data["presignedPostData"]["fields"].as_object()+ .ok_or("Fields object is missing or not an object")?;++ let mut form = reqwest::multipart::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(response) => {- // The response was received without a network error, but the status code isn't a success.- let status = response.status(); // Get the status before consuming the response- let error_body = response.text().await.unwrap_or_else(|_| "<no response body>".to_string());- eprintln!("Failed to upload file. Status: {}. Body: {}", status, error_body);- return Err(format!("Failed to upload file. Status: {}. Body: {}", status, error_body));++ println!("Uploading file: {}", file_path);++ let file_bytes = tokio::fs::read(&file_path).await.map_err(|e| format!("Failed to read file: {}", e))?;+ let file_part = reqwest::multipart::Part::bytes(file_bytes)+ .file_name(file_name.clone())+ .mime_str("application/octet-stream")+ .map_err(|e| format!("Error setting MIME type: {}", e))?;++ form = form.part("file", file_part);++ let post_url = presigned_post_data["presignedPostData"]["url"].as_str()+ .ok_or("URL is missing or not a string")?;++ println!("Uploading file to: {}", post_url);++ let response = client.post(post_url)+ .multipart(form)+ .send()+ .await;++ match response {+ Ok(response) if response.status().is_success() => {+ println!("File uploaded successfully");+ }+ Ok(response) => {+ // The response was received without a network error, but the status code isn't a success.+ let status = response.status(); // Get the status before consuming the response+ let error_body = response.text().await.unwrap_or_else(|_| "<no response body>".to_string());+ eprintln!("Failed to upload file. Status: {}. Body: {}", status, error_body);+ return Err(format!("Failed to upload file. Status: {}. Body: {}", status, error_body));+ }+ Err(e) => {+ // The send operation failed before we got any response at all (e.g., a network error).+ return Err(format!("Failed to send upload file request: {}", e));+ }}- Err(e) => {- // The send operation failed before we got any response at all (e.g., a network error).- return Err(format!("Failed to send upload file request: {}", e));++ // Clean up the uploaded file+ println!("Removing file after upload: {}", file_path);+ let remove_result = tokio::fs::remove_file(&file_path).await;+ match &remove_result {+ Ok(_) => println!("File removed successfully"),+ Err(e) => println!("Failed to remove file after upload: {}", e),}- }+ remove_result.map_err(|e| format!("Failed to remove file after upload: {}", e))?;- // Clean up the uploaded file- println!("Removing file after upload: {}", file_path);- let remove_result = tokio::fs::remove_file(&file_path).await;- match &remove_result {- Ok(_) => println!("File removed successfully"),- Err(e) => println!("Failed to remove file after upload: {}", e),+ Ok(file_key)+ } else {+ return Err("No recording options provided".to_string());}- remove_result.map_err(|e| format!("Failed to remove file after upload: {}", e))?;-- Ok(file_key)}\ No newline at end of filediff --git a/apps/desktop/src/components/Button.tsx b/apps/desktop/src/components/Button.tsxindex d9f385566..16f256704 100644--- a/apps/desktop/src/components/Button.tsx+++ b/apps/desktop/src/components/Button.tsx@@ -3,11 +3,13 @@ export const Button = ({handler,label,className,+ spinner,}: {handler: () => void;label: string;variant: "primary" | "secondary" | "tertiary" | "white";className?: string;+ spinner?: boolean;}) => {let classes ="w-full border-2 min-h-[50px] text-center py-2 px-4 bg-gray-200 font-medium flex items-center justify-center rounded-[15px] transition-all";@@ -27,6 +29,32 @@ export const Button = ({return (<button onClick={handler} className={classes}>{label}+ {spinner && (+ <div className="ml-2">+ <svg+ xmlns="http://www.w3.org/2000/svg"+ className="w-6 h-6"+ viewBox="0 0 24 24"+ >+ <style>+ {"@keyframes spinner_AtaB{to{transform:rotate(360deg)}}"}+ </style>+ <path+ fill="#FFF"+ d="M12 1a11 11 0 1 0 11 11A11 11 0 0 0 12 1Zm0 19a8 8 0 1 1 8-8 8 8 0 0 1-8 8Z"+ opacity={0.25}+ />+ <path+ fill="#FFF"+ d="M10.14 1.16a11 11 0 0 0-9 8.92A1.59 1.59 0 0 0 2.46 12a1.52 1.52 0 0 0 1.65-1.3 8 8 0 0 1 6.66-6.61A1.42 1.42 0 0 0 12 2.69a1.57 1.57 0 0 0-1.86-1.53Z"+ style={{+ transformOrigin: "center",+ animation: "spinner_AtaB .75s infinite linear",+ }}+ />+ </svg>+ </div>+ )}</button>);};diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsxindex a86d3c643..072346dc0 100644--- a/apps/desktop/src/components/windows/inner/Recorder.tsx+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useState, useEffect } from "react";import { useMediaDevices } from "@/utils/recording/MediaDeviceContext";import { Video } from "@/components/icons/Video";import { Microphone } from "@/components/icons/Microphone";@@ -9,14 +9,14 @@ import { emit } from "@tauri-apps/api/event";import { showMenu } from "tauri-plugin-context-menu";import { invoke } from "@tauri-apps/api/tauri";import { Countdown } from "./Countdown";-// import { appWindow, WebviewWindow } from "@tauri-apps/api/window";import { AuthSession } from "@supabase/supabase-js";import { supabase } from "@/utils/database/client";import type { Database } from "@cap/utils";-// import { getVideoSettings } from "@/utils/helpers";import { useAudioRecorder } from "@/utils/recording/useAudioRecorder";import { getSelectedVideoProperties } from "@/utils/recording/utils";import { getLatestVideoId, saveLatestVideoId } from "@/utils/database/utils";+import { openLinkInBrowser } from "@/utils/helpers";+import { uuidParse } from "@cap/utils";export const Recorder = ({ session }: { session: AuthSession | null }) => {const {@@ -27,6 +27,9 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {setIsRecording,} = useMediaDevices();const [countdownActive, setCountdownActive] = useState(false);+ const [stoppingRecording, setStoppingRecording] = useState(false);+ const [currentStoppingMessage, setCurrentStoppingMessage] =+ useState("Stopping Recording");const { startAudioRecording, stopAudioRecording } = useAudioRecorder();const handleContextClick = async (option: string) => {@@ -70,14 +73,93 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {setCountdownActive(false);};+ const prepareVideoData = async () => {+ return await supabase+ .from("videos")+ .insert({+ owner_id: session?.user?.id,+ aws_region: import.meta.env.VITE_AWS_REGION,+ aws_bucket: import.meta.env.VITE_AWS_BUCKET,+ })+ .select()+ .single()+ .then(+ ({+ data,+ error,+ }: {+ data: Database["public"]["Tables"]["videos"]["Row"] | null;+ error: any;+ }) => {+ if (error) {+ console.error("Error fetching video data:", error);+ return null;+ }+ if (!data) {+ console.error("No video data received");+ return null;+ }+ saveLatestVideoId(data.id);+ return data;+ }+ );+ };++ const startDualRecording = async (videoData: {+ id: any;+ aws_region: any;+ aws_bucket: any;+ }) => {+ // Extracted from the useEffect hook; this starts the video recording+ const mediaSettings = await getSelectedVideoProperties();+ if (mediaSettings?.resolution && mediaSettings?.framerate) {+ await invoke("start_dual_recording", {+ options: {+ user_id: session?.user?.id,+ video_id: videoData.id,+ aws_region: videoData.aws_region,+ aws_bucket: videoData.aws_bucket,+ screen_index: "Capture screen 0",+ video_index: String(selectedVideoDevice?.index),+ ...mediaSettings,+ },+ }).catch((error) => {+ console.error("Error invoking start_screen_recording:", error);+ });+ } else {+ console.error("Invalid media settings for dual recording");+ }+ };+const handleStartAllRecordings = async () => {setCountdownActive(true);++ try {+ const videoData = await prepareVideoData();+ if (videoData) {+ await startAudioRecording(selectedAudioDevice);+ await startDualRecording(videoData);+ } else {+ throw new Error("Failed to prepare video data.");+ }+ } catch (error) {+ console.error("Error starting recordings:", error);+ setCountdownActive(false);+ }};const handleStopAllRecordings = async () => {+ setStoppingRecording(true);+const recordedAudioFilePath = await stopAudioRecording();if (recordedAudioFilePath) {try {+ console.log("Stopping recordings...");++ await invoke("stop_all_recordings");++ console.log("Recordings stopped...");+await invoke("upload_file", {options: {user_id: session?.user?.id,@@ -92,6 +174,18 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {filePath: recordedAudioFilePath,fileType: "audio",});++ console.log("Opening window...");++ await openLinkInBrowser(+ `${import.meta.env.VITE_PUBLIC_URL}/share/${uuidParse(+ await getLatestVideoId()+ )}`+ );++ setIsRecording(false);+ setCountdownActive(false);+ setStoppingRecording(false);} catch (error) {console.error("Error invoking upload_file:", error);}@@ -100,78 +194,28 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {}setIsRecording(false);setCountdownActive(false);+ setStoppingRecording(false);};useEffect(() => {- const startRecording = async () => {- if (isRecording) {- const mediaSettings = await getSelectedVideoProperties();- const {- data: videoData,- error: videoError,- }: {- data: Database["public"]["Tables"]["videos"]["Row"] | null;- error: any;- } = await supabase- .from("videos")- .insert({- owner_id: session?.user?.id,- aws_region: import.meta.env.VITE_AWS_REGION,- aws_bucket: import.meta.env.VITE_AWS_BUCKET,- })- .select()- .single();-- if (session?.user?.id === undefined) {- console.error("session.user.id is undefined");- setIsRecording(false);- return;- }+ if (stoppingRecording) {+ const messages = ["Processing video", "Almost there", "Hang tight"];+ let messageIndex = 0;- if (videoError) {- console.error("videoError:", videoError);- setIsRecording(false);- return;- }+ const nextMessage = () => {+ setCurrentStoppingMessage(messages[messageIndex % messages.length]);+ messageIndex++;+ };- if (videoData === null) {- console.error("videoData is null");- setIsRecording(false);- return;- }+ nextMessage();- await saveLatestVideoId(videoData.id);- await startAudioRecording(selectedAudioDevice);+ const intervalId = setInterval(nextMessage, 1500);- console.log("mediaSettings:", mediaSettings);- console.log("videoData:", videoData);-- if (- videoData.id &&- mediaSettings?.resolution &&- mediaSettings?.framerate- ) {- await invoke("start_dual_recording", {- options: {- user_id: session?.user?.id,- video_id: videoData.id,- aws_region: videoData.aws_region,- aws_bucket: videoData.aws_bucket,- screen_index: "Capture screen 0",- video_index: String(selectedVideoDevice?.index),- ...mediaSettings,- },- }).catch((error) => {- console.error("Error invoking start_screen_recording:", error);- });- } else {- console.error("videoData is null or does not contain any elements");- }- }- };-- startRecording();- }, [isRecording]);+ return () => clearInterval(intervalId);+ } else {+ setCurrentStoppingMessage("");+ }+ }, [stoppingRecording]);return (<div@@ -184,7 +228,7 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {>{countdownActive && (<Countdown- countdownFrom={1}+ countdownFrom={3}onCountdownFinish={handleOverlayFinished}/>)}@@ -216,7 +260,10 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {<Buttonvariant="primary"handler={handleStopAllRecordings}- label="Stop Recording"+ label={+ stoppingRecording ? currentStoppingMessage : "Stop Recording"+ }+ spinner={stoppingRecording}/>) : (<Buttondiff --git a/apps/desktop/src/utils/helpers.ts b/apps/desktop/src/utils/helpers.tsindex 1c3f66008..cfe2dfc6c 100644--- a/apps/desktop/src/utils/helpers.ts+++ b/apps/desktop/src/utils/helpers.ts@@ -31,16 +31,8 @@ export const setWindowPosition = (});};-export const uuidParse = (uuid: string) => {- return uuid.replace(/-/g, "");-};--export const uuidFormat = (uuid: string) => {- return uuid.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");-};--export const openLinkInBrowser = (url: string) => {- open(url);+export const openLinkInBrowser = async (url: string) => {+ await open(url);return;};diff --git a/apps/web/app/api/upload/new/route.ts b/apps/web/app/api/upload/new/route.tsindex f2e7c330f..1ae89d2c8 100644--- a/apps/web/app/api/upload/new/route.ts+++ b/apps/web/app/api/upload/new/route.ts@@ -6,8 +6,8 @@ import { NextRequest } from "next/server";const s3Client = new S3Client({region: process.env.AWS_REGION || "",credentials: {- accessKeyId: process.env.AWS_ACCESS_KEY || "",- secretAccessKey: process.env.AWS_SECRET_KEY || "",+ accessKeyId: process.env.CAP_AWS_ACCESS_KEY || "",+ secretAccessKey: process.env.CAP_AWS_SECRET_KEY || "",},});diff --git a/apps/web/app/share/page.tsx b/apps/web/app/share/page.tsxnew file mode 100644index 000000000..e69de29bbdiff --git a/apps/web/utils/database/supabase/browser.ts b/apps/web/utils/database/supabase/browser.tsindex 084b17dbc..a1dec7b0f 100644--- a/apps/web/utils/database/supabase/browser.ts+++ b/apps/web/utils/database/supabase/browser.ts@@ -1,4 +1,4 @@import { createPagesBrowserClient } from "@supabase/auth-helpers-nextjs";-import { Database } from "./types";+import type { Database } from "@cap/utils";export const createBrowserClient = () => createPagesBrowserClient<Database>();diff --git a/apps/web/utils/database/supabase/server.ts b/apps/web/utils/database/supabase/server.tsindex e0e2d0f90..35bb8c096 100644--- a/apps/web/utils/database/supabase/server.ts+++ b/apps/web/utils/database/supabase/server.ts@@ -3,7 +3,7 @@ import {createServerComponentClient,createRouteHandlerClient,} from "@supabase/auth-helpers-nextjs";-import { Database } from "./types";+import type { Database } from "@cap/utils";export const createServerClient = () =>createServerComponentClient<Database>({diff --git a/packages/utils/src/helpers.ts b/packages/utils/src/helpers.tsnew file mode 100644index 000000000..18e770179--- /dev/null+++ b/packages/utils/src/helpers.ts@@ -0,0 +1,7 @@+export const uuidParse = (uuid: string) => {+ return uuid.replace(/-/g, "");+};++export const uuidFormat = (uuid: string) => {+ return uuid.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");+};diff --git a/packages/utils/src/index.tsx b/packages/utils/src/index.tsxindex 70222e74f..852d0d070 100644--- a/packages/utils/src/index.tsx+++ b/packages/utils/src/index.tsx@@ -1 +1,2 @@export * from "./types/database";+export * from "./helpers";