Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Desktop recording file upload
Richie McIlroyfa3d4470dd4f
diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lockindex 22892c205..b38fcf9cd 100644--- a/apps/desktop/src-tauri/Cargo.lock+++ b/apps/desktop/src-tauri/Cargo.lock@@ -484,6 +484,8 @@ dependencies = ["tauri-build","tauri-plugin-context-menu","tauri-plugin-positioner",+ "tokio",+ "uuid","which",]@@ -4338,11 +4340,25 @@ dependencies = ["libc","mio","num_cpus",+ "parking_lot","pin-project-lite",+ "signal-hook-registry","socket2 0.5.5",+ "tokio-macros","windows-sys 0.48.0",]+[[package]]+name = "tokio-macros"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.41",+]+[[package]]name = "tokio-native-tls"version = "0.3.1"diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex 8e1e18f2c..cd1eff7d0 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -23,7 +23,9 @@ ffmpeg-sidecar = "0.5.1"which = "4.2.2"rust-s3 = "0.34.0-rc3"dotenv = "0.15.0"+tokio = { version = "1", features = ["full"] }capture = { path = "./src/capture" }+uuid = { version = "1.0", features = ["v4"] }[dev-dependencies]shuteye = "0.3.3"diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rsindex 3bce94aa5..7e2a4daf5 100644--- a/apps/desktop/src-tauri/src/main.rs+++ b/apps/desktop/src-tauri/src/main.rs@@ -7,6 +7,7 @@ use s3::bucket::Bucket;use s3::creds::Credentials;use s3::region::Region;use s3::error::S3Error;+use uuid::Uuid;use tauri::{Manager, Window};use tauri_plugin_positioner::{WindowExt, Position};@@ -22,14 +23,22 @@ mod recorder;use recorder::ScreenRecorder;#[tauri::command]-fn start_screen_recording(window: Window, recorder: tauri::State<'_, Arc<Mutex<ScreenRecorder>>>) {+fn start_screen_recording(window: Window, user_id: String, recorder: tauri::State<'_, Arc<Mutex<ScreenRecorder>>>) {let window = window.clone();let recorder = recorder.inner().clone();std::thread::spawn(move || {- let recorder = recorder.lock().expect("Failed to lock recorder.");- if let Err(e) = recorder.start_recording() {- window.emit("recording-error", &e.to_string()).expect("Failed to send recording-error event.");+ println!("Thread for recording started");+ match recorder.lock() {+ Ok(mut recorder) => {+ recorder.set_user_id(user_id);+ match recorder.start_recording() {+ Ok(()) => println!("Recording started successfully"),+ Err(e) => window.emit("recording-error", &e.to_string()).expect("Failed to send recording-error event."),+ }+ },+ Err(e) => window.emit("recording-error", &format!("Failed to lock recorder: {}", e)).expect("Failed to send recording-error event."),}+ println!("Thread for recording ended");});}@@ -61,33 +70,40 @@ async fn setup_s3_client() -> Result<Bucket, S3Error> {}#[tauri::command]-async fn upload_video(file_path: String) -> Result<String, String> {+async fn upload_video(window: Window, user_id: String, file_path: String) -> Result<String, String> {+ let window = window.clone();let bucket_result = setup_s3_client().await;if let Err(e) = bucket_result {return Err(format!("Failed to setup S3 client: {}", e));}-+let bucket = bucket_result.unwrap();- let file_key = file_path.split('/').last().ok_or("Invalid file path")?.to_string();+ // Generate a random UUID for the new folder name+ let video_folder_uuid = Uuid::new_v4().to_string();+ let file_name = file_path.split('/').last().ok_or("Invalid file path")?.to_string();++ // Update the file key to include the random UUID+ let file_key = format!("{}/{}/{}", user_id, video_folder_uuid, file_name);let content = match std::fs::read(&file_path) {Ok(data) => data,Err(e) => return Err(format!("Failed to read video file: {}", e)),};- let response_data = match bucket.put_object(&file_key, &content).await {- Ok(data) => data,+ match bucket.put_object(&file_key, &content).await {+ Ok(data) => {+ if data.status_code() == 200 {+ window.emit("video-uploaded", &video_folder_uuid)+ .expect("Failed to send the video-uploaded event");+ Ok(file_key)+ } else {+ let error_message = format!("Failed to upload file: HTTP Status Code {}", data.status_code());+ Err(error_message)+ }+ },Err(e) => return Err(format!("Failed to upload file: {}", e)),- };-- // If the response indicates success, return the file key, else return an error message.- match response_data.status_code() {- 200 => Ok(file_key),- 403 => Err("Forbidden: Check your S3 permissions and credentials".into()),- 404 => Err("Not Found: The specified bucket does not exist".into()),- status => Err(format!("Failed to upload file: HTTP Status Code {}", status)),}}@@ -147,10 +163,13 @@ fn main() {// Fetch the full path to the FFmpeg binarylet ffmpeg_binary_path = sidecar_dir()?.join(if cfg!(target_os = "windows") { "ffmpeg.exe" } else { "ffmpeg" });++ let window = app.get_window("options").ok_or("Failed to get options window")?;// Create an instance of ScreenRecorder with the ffmpeg_binary_pathlet recorder = ScreenRecorder::new(ffmpeg_binary_path,+ window.clone());let shared_recorder = Arc::new(Mutex::new(recorder));diff --git a/apps/desktop/src-tauri/src/recorder.rs b/apps/desktop/src-tauri/src/recorder.rsindex 1edbe09e8..3fa8d4580 100644--- a/apps/desktop/src-tauri/src/recorder.rs+++ b/apps/desktop/src-tauri/src/recorder.rs@@ -8,6 +8,8 @@ use std::fs;use std::fs::File;use std::sync::atomic::{AtomicBool, Ordering};use capture::{Capturer, Display};+use tauri::{Window};+use super::upload_video;#[derive(Clone, PartialEq)]pub enum RecordingState {@@ -21,25 +23,37 @@ pub struct ScreenRecorder {ffmpeg_handle: Mutex<Option<thread::JoinHandle<Result<(), String>>>>,ffmpeg_path: PathBuf,should_stop: Arc<AtomicBool>,+ user_id: Option<String>,+ window: Window}const BYTES_PER_PIXEL: usize = 4;impl ScreenRecorder {- pub fn new(ffmpeg_path: PathBuf) -> Self {+ pub fn new(ffmpeg_path: PathBuf, window: Window) -> Self {Self {state: Arc::new(Mutex::new(RecordingState::Idle)),ffmpeg_handle: Mutex::new(None),ffmpeg_path,should_stop: Arc::new(AtomicBool::new(false)),+ user_id: None,+ window}}+ pub fn set_user_id(&mut self, user_id: String) {+ self.user_id = Some(user_id);+ }+pub fn start_recording(&self) -> Result<(), String> {let state = self.state.clone();- let should_stop = self.should_stop.clone();+ let should_stop = Arc::clone(&self.should_stop);let ffmpeg_path = self.ffmpeg_path.clone();+ let user_id = self.user_id.clone();+ let window = self.window.clone();++ println!("Start recording requested.");// Ensure we have a primary display to capturelet display = Display::primary().map_err(|_| "Failed to find primary display".to_string())?;@@ -48,6 +62,8 @@ impl ScreenRecorder {let capture_size = w * adjusted_height * BYTES_PER_PIXEL;let framerate = 60;+ println!("Display: {}x{}", w, h);+// Check current recording statelet mut state_guard = state.lock().map_err(|_| "Failed to acquire state lock".to_string())?;if *state_guard != RecordingState::Idle {@@ -56,19 +72,32 @@ impl ScreenRecorder {*state_guard = RecordingState::Recording;drop(state_guard);+ println!("Starting recording...");+// Define paths for recordings and temp datalet recordings_dir = Path::new("recordings");- fs::create_dir_all(&recordings_dir).map_err(|e| format!("Failed to create recordings directory: {}", e))?;let tmp_file_path = recordings_dir.join("temporary_capture.raw");let output_path = recordings_dir.join("recording.mp4").to_owned();- // Delete existing files if necessary+ fs::create_dir_all(&recordings_dir).map_err(|e| format!("Failed to create recordings directory: {}", e))?;++ println!("Temporary file path: {}", tmp_file_path.to_str().ok_or_else(|| "Failed to convert temporary file path to string".to_owned())?);++ // Delete existing temporary and final output files if they exist+ if tmp_file_path.exists() {+ std::fs::remove_file(&tmp_file_path).map_err(|e| format!("Failed to delete existing temp file: {}", e))?;+ }if output_path.exists() {- fs::remove_file(&output_path).map_err(|e| format!("Failed to delete existing recording file: {}", e))?;+ std::fs::remove_file(&output_path).map_err(|e| format!("Failed to delete existing final output file: {}", e))?;}++ println!("Output file path: {}", output_path.to_str().ok_or_else(|| "Failed to convert output file path to string".to_owned())?);+let output_path_str = output_path.to_str().ok_or_else(|| "Failed to construct output file path string".to_string())?.to_owned();let ffmpeg_handle = thread::spawn(move || {+ println!("Starting capture...");+let mut capturer = Capturer::new(display).expect("Failed to start capture");let (sender, receiver) = std::sync::mpsc::channel::<Vec<u8>>();let frame_duration = Duration::from_secs_f64(1.0 / framerate as f64);@@ -116,10 +145,14 @@ impl ScreenRecorder {sender.send(frame_data).expect("Failed to send frame data to the writer thread");}+ println!("Capture stopped.");+// End capture loopdrop(sender); // Send the terminating signal to the writing thread.write_handle.join().expect("Failed to join the writer handle");+ println!("Encoding video...");+// Encoding with FFmpeglet status = Command::new(&ffmpeg_path).args(&[@@ -138,11 +171,23 @@ impl ScreenRecorder {]).output();+ println!("Encoding finished.");// Handle the FFmpeg outputmatch status {Ok(output) if output.status.success() => {// Encoding succeeded, remove the temporary filelet _ = fs::remove_file(&tmp_file_path);+ println!("Encoding succeeded.");++ if let Some(user_id) = &user_id {+ println!("Uploading video...");++ match tauri::async_runtime::block_on(upload_video(window.clone(), user_id.clone(), output_path_str.clone())) {+ Ok(_) => println!("Video uploaded successfully."),+ Err(e) => eprintln!("Video upload encountered an error: {}", e),+ }+ }+Ok(())},Ok(output) => {diff --git a/apps/desktop/src/components/windows/Options.tsx b/apps/desktop/src/components/windows/Options.tsxindex 43a1676c8..872c8f70f 100644--- a/apps/desktop/src/components/windows/Options.tsx+++ b/apps/desktop/src/components/windows/Options.tsx@@ -2,10 +2,12 @@ import { Recorder } from "@/components/windows/inner/Recorder";import { SignIn } from "@/components/windows/inner/SignIn";import { supabase } from "@/utils/database/client";import { AuthSession } from "@supabase/supabase-js";+import { UnlistenFn, listen } from "@tauri-apps/api/event";import { useEffect, useState } from "react";export const Options = () => {const [session, setSession] = useState<AuthSession | null>(null);+useEffect(() => {supabase.auth.getSession().then(({ data: { session } }) => {setSession(session);@@ -14,10 +16,35 @@ export const Options = () => {supabase.auth.onAuthStateChange((_event, session) => {setSession(session);});++ let unlistenFn: UnlistenFn | undefined;++ const setupEventListener = async () => {+ unlistenFn = await listen("video-uploaded", async (event) => {+ console.log("video-uploaded event received:", event);++ const { data, error } = await supabase+ .from("videos")+ .insert([+ { unique_cap_id: event.payload, owner_id: session?.user?.id },+ ]);++ if (error) {+ console.error("Error inserting video:", error);+ } else {+ console.log("Video inserted:", data);+ }+ });+ };++ setupEventListener();}, []);+ console.log("session:");+ console.log(session);+if (session) {- return <Recorder />;+ return <Recorder session={session} />;}return <SignIn />;diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsxindex 4ab0e59cc..f5b701d54 100644--- a/apps/desktop/src/components/windows/inner/Recorder.tsx+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx@@ -1,8 +1,5 @@import { useEffect, useState } from "react";-import {- ReactMediaRecorder,- recordingFileLocation,-} from "@/utils/recording/client";+import { ReactMediaRecorder } from "@/utils/recording/client";import { useMediaDevices } from "@/utils/recording/MediaDeviceContext";import { Video } from "@/components/icons/Video";import { Microphone } from "@/components/icons/Microphone";@@ -14,8 +11,9 @@ 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";-export const Recorder = () => {+export const Recorder = ({ session }: { session: AuthSession | null }) => {const { devices, selectedVideoDevice, selectedAudioDevice, getDevices } =useMediaDevices();const [isRecording, setIsRecording] = useState(false);@@ -87,18 +85,13 @@ export const Recorder = () => {const handleStopAllRecordings = async () => {stopRecording();await invoke("stop_screen_recording");- const filePath = await recordingFileLocation();- const upload = await invoke("upload_video", {- filePath: filePath.toString(),- });- console.log("Upload response:", upload);setIsRecording(false);};useEffect(() => {if (isRecording) {startRecording();- invoke("start_screen_recording");+ invoke("start_screen_recording", { userId: session?.user?.id });}}, [isRecording]);diff --git a/apps/desktop/src/utils/hooks/useDidMount.ts b/apps/desktop/src/utils/hooks/useDidMount.tsindex 54d8a8a4f..b730618c6 100644--- a/apps/desktop/src/utils/hooks/useDidMount.ts+++ b/apps/desktop/src/utils/hooks/useDidMount.ts@@ -1,6 +1,5 @@import { DependencyList, useEffect, useRef } from "react";-// USE ONLY IF YOU DON'T HAVE A WAY TO UNMOUNTexport const useDidMountEffect = (func: () => void,deps: DependencyList | undefineddiff --git a/apps/desktop/src/utils/recording/client.ts b/apps/desktop/src/utils/recording/client.tsindex 432c8a70c..c8e1fd3e5 100644--- a/apps/desktop/src/utils/recording/client.ts+++ b/apps/desktop/src/utils/recording/client.ts@@ -7,7 +7,7 @@ import { ReactElement, useCallback, useEffect, useRef, useState } from "react";import { connect } from "extendable-media-recorder-wav-encoder";import { useMediaDevices } from "@/utils/recording/MediaDeviceContext";import { useDidMountEffect } from "@/utils/hooks/useDidMount";-import { writeBinaryFile, createDir } from "@tauri-apps/api/fs";+import { writeBinaryFile, createDir, removeFile } from "@tauri-apps/api/fs";import { appDataDir } from "@tauri-apps/api/path";export type ReactMediaRecorderRenderProps = {@@ -244,6 +244,16 @@ export function useReactMediaRecorder({if (!mediaStream.current.active) {return;}++ // Delete the old file+ const filePath = await recordingFileLocation();+ try {+ await removeFile(filePath);+ console.log("Old recording deleted successfully");+ } catch (error) {+ console.error("Failed to delete old recording:", error);+ }+mediaRecorder.current = new ExtendableMediaRecorder(mediaStream.current,mediaRecorderOptions || undefineddiff --git a/apps/web/schema/schema.sql b/apps/web/schema/schema.sqlindex 524d8379d..4a6917fcd 100644--- a/apps/web/schema/schema.sql+++ b/apps/web/schema/schema.sql@@ -47,11 +47,12 @@ CREATE TABLE space_members (CREATE TABLE videos (id UUID PRIMARY KEY DEFAULT gen_random_uuid(),owner_id UUID REFERENCES users(id) ON DELETE CASCADE,- name VARCHAR(255) NOT NULL,- s3_url TEXT NOT NULL, -- AWS S3 URL to the video+ name VARCHAR(255) NOT NULL default 'My Video: ' || to_char(now(), 'YYYY-MM-DD HH24:MI:SS'),+ s3_url TEXT default null, -- AWS S3 URL to the videothumbnail_url TEXT, -- URL to the video's thumbnailduration NUMERIC, -- The length of the videometadata JSONB, -- Any additional metadata about the video+ unique_cap_id UUID default NULL unique,complete BOOLEAN NOT NULL DEFAULT true, -- Whether video is fully processedis_public BOOLEAN NOT NULL DEFAULT false, -- Can be shared to spacescreated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),