Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Upload webcam footage alongside screen

Richie McIlroy707b920e34af
diff --git a/apps/desktop/src-tauri/.env b/apps/desktop/src-tauri/.env
deleted file mode 100644
index b3709691f..000000000
--- a/apps/desktop/src-tauri/.env
+++ /dev/null
@@ -1,3 +0,0 @@
-CLOUDFLARE_ACCESS_KEY=f013c6ebb42ad1982b833c999b6d4c65
-CLOUDFLARE_SECRET_KEY=d6aec8c6909a75669406d9469d17a699bbbb461616bcfe2145203474fac245ac
-CLOUDFLARE_R2_ENDPOINT=https://88f6b7a748cf91dbfe65479d1855aea7.eu.r2.cloudflarestorage.com
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/.gitignore b/apps/desktop/src-tauri/.gitignore
index 055c11391..08b526419 100644
--- a/apps/desktop/src-tauri/.gitignore
+++ b/apps/desktop/src-tauri/.gitignore
@@ -1,4 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
-/recordings/*
\ No newline at end of file
+/recordings/*
+src/capture/target/*
+.env
+.env*
\ No newline at end of file
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index cd1eff7d0..7d0543440 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -13,7 +13,7 @@ edition = "2021"
tauri-build = { version = "1.5.0", features = [] }
[dependencies]
-tauri = { version = "1.5.0", features = [ "window-set-position", "fs-write-file", "fs-remove-file", "fs-read-file", "fs-rename-file", "fs-exists", "fs-remove-dir", "fs-read-dir", "fs-copy-file", "fs-create-dir", "window-set-ignore-cursor-events", "macos-private-api", "window-unminimize", "window-minimize", "window-close", "window-show", "window-start-dragging", "window-hide", "window-unmaximize", "window-maximize", "window-set-always-on-top", "shell-open"] }
+tauri = { version = "1.5.0", features = [ "window-set-position", "fs-write-file", "fs-remove-file", "fs-read-file", "fs-rename-file", "fs-exists", "fs-remove-dir", "fs-read-dir", "fs-copy-file", "fs-create-dir", "window-set-ignore-cursor-events", "macos-private-api", "window-unminimize", "window-minimize", "window-close", "window-show", "window-start-dragging", "window-hide", "window-unmaximize", "window-maximize", "window-set-always-on-top", "shell-open", "devtools"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tauri-plugin-context-menu = "0.5.0"
diff --git a/apps/desktop/src-tauri/src/capture/Cargo.lock b/apps/desktop/src-tauri/src/capture/Cargo.lock
new file mode 100644
index 000000000..b469c2469
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture/Cargo.lock
@@ -0,0 +1,37 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "block"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
+
+[[package]]
+name = "capture"
+version = "0.0.1"
+dependencies = [
+ "block",
+ "cfg-if",
+ "libc",
+ "winapi",
+]
+
+[[package]]
+name = "cfg-if"
+version = "0.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
+
+[[package]]
+name = "libc"
+version = "0.2.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4"
+
+[[package]]
+name = "winapi"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a"
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 7e2a4daf5..6ed8897f2 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -70,7 +70,7 @@ async fn setup_s3_client() -> Result<Bucket, S3Error> {
}
#[tauri::command]
-async fn upload_video(window: Window, user_id: String, file_path: String) -> Result<String, String> {
+async fn upload_video(window: Window, user_id: String, file_path: String, unique_id: String, final_call: bool) -> Result<String, String> {
let window = window.clone();
let bucket_result = setup_s3_client().await;
@@ -80,8 +80,13 @@ async fn upload_video(window: Window, user_id: String, file_path: String) -> Res
let bucket = bucket_result.unwrap();
- // Generate a random UUID for the new folder name
- let video_folder_uuid = Uuid::new_v4().to_string();
+ // Use the provided unique_id if it's not empty, otherwise generate a random UUID
+ let video_folder_uuid = if unique_id.is_empty() {
+ Uuid::new_v4().to_string()
+ } else {
+ unique_id
+ };
+
let file_name = file_path.split('/').last().ok_or("Invalid file path")?.to_string();
// Update the file key to include the random UUID
@@ -95,9 +100,16 @@ async fn upload_video(window: Window, user_id: String, file_path: String) -> Res
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");
+ if !final_call {
+ println!("Video uploaded successfully. Not a final call.");
+ window.emit("video-uploaded", &video_folder_uuid)
+ .expect("Failed to send the video-uploaded event");
+ } else {
+ println!("Video uploaded successfully. Final call.");
+ }
+
Ok(file_key)
+
} else {
let error_message = format!("Failed to upload file: HTTP Status Code {}", data.status_code());
Err(error_message)
@@ -107,6 +119,13 @@ async fn upload_video(window: Window, user_id: String, file_path: String) -> Res
}
}
+#[tauri::command]
+fn open_external(window: tauri::Window, url: String) -> Result<(), String> {
+ let shell_scope = window.shell_scope();
+
+ tauri::api::shell::open(&shell_scope, &url, None).map_err(|e| e.to_string())
+}
+
fn main() {
dotenv().ok();
@@ -188,7 +207,8 @@ fn main() {
.invoke_handler(tauri::generate_handler![
start_screen_recording,
stop_screen_recording,
- upload_video
+ upload_video,
+ open_external
])
.plugin(tauri_plugin_context_menu::init())
.run(tauri::generate_context!())
diff --git a/apps/desktop/src-tauri/src/recorder.rs b/apps/desktop/src-tauri/src/recorder.rs
index 3fa8d4580..3f9184551 100644
--- a/apps/desktop/src-tauri/src/recorder.rs
+++ b/apps/desktop/src-tauri/src/recorder.rs
@@ -77,7 +77,7 @@ impl ScreenRecorder {
// Define paths for recordings and temp data
let recordings_dir = Path::new("recordings");
let tmp_file_path = recordings_dir.join("temporary_capture.raw");
- let output_path = recordings_dir.join("recording.mp4").to_owned();
+ let output_path = recordings_dir.join("screen.mp4").to_owned();
fs::create_dir_all(&recordings_dir).map_err(|e| format!("Failed to create recordings directory: {}", e))?;
@@ -182,7 +182,7 @@ impl ScreenRecorder {
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())) {
+ match tauri::async_runtime::block_on(upload_video(window.clone(), user_id.clone(), output_path_str.clone(), String::new(), false)) {
Ok(_) => println!("Video uploaded successfully."),
Err(e) => eprintln!("Video upload encountered an error: {}", e),
}
diff --git a/apps/desktop/src/components/windows/Options.tsx b/apps/desktop/src/components/windows/Options.tsx
index 872c8f70f..76c9b744a 100644
--- a/apps/desktop/src/components/windows/Options.tsx
+++ b/apps/desktop/src/components/windows/Options.tsx
@@ -1,12 +1,19 @@
import { Recorder } from "@/components/windows/inner/Recorder";
import { SignIn } from "@/components/windows/inner/SignIn";
import { supabase } from "@/utils/database/client";
+import { openLinkInBrowser, uuidParse } from "@/utils/helpers";
+import { useMediaDevices } from "@/utils/recording/MediaDeviceContext";
+import { recordingFileLocation } from "@/utils/recording/client";
import { AuthSession } from "@supabase/supabase-js";
+import { invoke } from "@tauri-apps/api";
import { UnlistenFn, listen } from "@tauri-apps/api/event";
+import { exists } from "@tauri-apps/api/fs";
import { useEffect, useState } from "react";
+import toast from "react-hot-toast";
export const Options = () => {
const [session, setSession] = useState<AuthSession | null>(null);
+ const { setIsRecording } = useMediaDevices();
useEffect(() => {
supabase.auth.getSession().then(({ data: { session } }) => {
@@ -16,34 +23,95 @@ export const Options = () => {
supabase.auth.onAuthStateChange((_event, session) => {
setSession(session);
});
+ }, []);
+ useEffect(() => {
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);
+ if (
+ !event.payload ||
+ !session?.user?.id ||
+ session?.user?.id === null ||
+ session?.user?.id === undefined
+ ) {
+ console.error("Payload is empty, or user is not logged in.");
+ setIsRecording(false);
+ toast.error("An error occurred while uploading the video.");
+ return;
}
+
+ const filePath = await recordingFileLocation();
+
+ const checkFileExists = async () => {
+ const fileExists = await exists(filePath);
+
+ if (!fileExists) {
+ console.error("File does not exist.");
+ setTimeout(checkFileExists, 100);
+ }
+
+ console.log("Calling upload_video for the final time...");
+
+ if (
+ fileExists &&
+ session?.user?.id !== undefined &&
+ session?.user?.id !== null
+ ) {
+ await invoke("upload_video", {
+ userId: session.user.id,
+ filePath: filePath,
+ uniqueId: event.payload,
+ finalCall: true,
+ });
+ }
+
+ 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);
+ toast.error("An error occurred while uploading the video.");
+ setIsRecording(false);
+ } else {
+ console.log("Video inserted:", data);
+
+ if (data) {
+ console.log(
+ "Opening link in browser: ",
+ `https://cap.so/share/${uuidParse(event.payload as string)}`
+ );
+
+ openLinkInBrowser(
+ `https://cap.so/share/${uuidParse(event.payload as string)}`
+ );
+ }
+
+ setIsRecording(false);
+ }
+ };
+
+ checkFileExists();
});
};
setupEventListener();
- }, []);
- console.log("session:");
- console.log(session);
+ return () => {
+ if (unlistenFn) {
+ unlistenFn();
+ }
+ };
+ }, []);
- if (session) {
+ if (session?.user?.id) {
+ console.log("session?.user?.id: ", session?.user?.id);
return <Recorder session={session} />;
}
diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsx
index f5b701d54..55995d04f 100644
--- a/apps/desktop/src/components/windows/inner/Recorder.tsx
+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx
@@ -14,9 +14,14 @@ import { appWindow, WebviewWindow } from "@tauri-apps/api/window";
import { AuthSession } from "@supabase/supabase-js";
export const Recorder = ({ session }: { session: AuthSession | null }) => {
- const { devices, selectedVideoDevice, selectedAudioDevice, getDevices } =
- useMediaDevices();
- const [isRecording, setIsRecording] = useState(false);
+ const {
+ devices,
+ selectedVideoDevice,
+ selectedAudioDevice,
+ getDevices,
+ isRecording,
+ setIsRecording,
+ } = useMediaDevices();
const [countdownActive, setCountdownActive] = useState(false);
useEffect(() => {
@@ -70,7 +75,7 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {
? { deviceId: selectedAudioDevice.deviceId }
: undefined
}
- render={({ status, startRecording, stopRecording }) => {
+ render={({ startRecording, stopRecording }) => {
const handleOverlayFinished = () => {
appWindow.minimize();
WebviewWindow.getByLabel("camera")?.minimize();
@@ -85,7 +90,6 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {
const handleStopAllRecordings = async () => {
stopRecording();
await invoke("stop_screen_recording");
- setIsRecording(false);
};
useEffect(() => {
@@ -134,7 +138,7 @@ export const Recorder = ({ session }: { session: AuthSession | null }) => {
/>
</div>
</div>
- {status === "recording" ? (
+ {isRecording === true ? (
<Button
variant="primary"
handler={handleStopAllRecordings}
diff --git a/apps/desktop/src/utils/helpers.ts b/apps/desktop/src/utils/helpers.ts
index b57063461..9cc361e43 100644
--- a/apps/desktop/src/utils/helpers.ts
+++ b/apps/desktop/src/utils/helpers.ts
@@ -1,4 +1,5 @@
import { appWindow, LogicalPosition } from "@tauri-apps/api/window";
+import { open } from "@tauri-apps/api/shell";
export const setWindowPosition = (
position: "bottom_center" | "bottom_right"
@@ -28,3 +29,17 @@ 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);
+
+ return;
+};
diff --git a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
index 329841c89..13ac7d569 100644
--- a/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
+++ b/apps/desktop/src/utils/recording/MediaDeviceContext.tsx
@@ -20,6 +20,8 @@ interface MediaDeviceContextData {
>;
devices: MediaDeviceInfo[];
getDevices: () => Promise<void>;
+ isRecording: boolean;
+ setIsRecording: React.Dispatch<React.SetStateAction<boolean>>;
}
export const MediaDeviceContext = createContext<
@@ -34,6 +36,7 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
const [selectedAudioDevice, setSelectedAudioDevice] =
useState<MediaDeviceInfo | null>(null);
const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
+ const [isRecording, setIsRecording] = useState(false);
const getDevices = useCallback(async () => {
const fetchedDevices = await navigator.mediaDevices.enumerateDevices();
@@ -108,6 +111,8 @@ export const MediaDeviceProvider: React.FC<React.PropsWithChildren<{}>> = ({
setSelectedAudioDevice,
devices,
getDevices,
+ isRecording,
+ setIsRecording,
}}
>
{children}
diff --git a/apps/desktop/src/utils/recording/client.ts b/apps/desktop/src/utils/recording/client.ts
index c8e1fd3e5..9601d291c 100644
--- a/apps/desktop/src/utils/recording/client.ts
+++ b/apps/desktop/src/utils/recording/client.ts
@@ -378,7 +378,7 @@ export function useReactMediaRecorder({
export const recordingFileLocation = async () => {
const dir = await appDataDir();
- const filePath = `${dir}/recording.mp4`.replace(/\/\//g, "/");
+ const filePath = `${dir}/video.mp4`.replace(/\/\//g, "/");
return filePath;
};