Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

upload rendered files to s3

Brendan Allan62e94059c4c9
diff --git a/Cargo.lock b/Cargo.lock
index 79773c9f8..31afd3c04 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1534,6 +1534,7 @@ dependencies = [
"core-foundation 0.10.0",
"core-graphics 0.24.0",
"cpal",
+ "dotenvy_macro",
"ffmpeg-next",
"ffmpeg-sidecar 1.1.0 (git+https://github.com/CapSoftware/ffmpeg-sidecar?branch=main)",
"futures",
@@ -1547,6 +1548,7 @@ dependencies = [
"num-traits",
"objc",
"objc2-app-kit",
+ "reqwest",
"scap",
"serde",
"serde_json",
@@ -1641,6 +1643,24 @@ dependencies = [
"litrs",
]
+[[package]]
+name = "dotenvy"
+version = "0.15.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
+
+[[package]]
+name = "dotenvy_macro"
+version = "0.15.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb0235d912a8c749f4e0c9f18ca253b4c28cfefc1d2518096016d6e3230b6424"
+dependencies = [
+ "dotenvy",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
[[package]]
name = "dpi"
version = "0.1.1"
@@ -2507,6 +2527,25 @@ dependencies = [
"syn 2.0.75",
]
+[[package]]
+name = "h2"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "524e8ac6999421f49a846c2d4411f337e53497d8ec55d67753beffa43c5d9205"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "fnv",
+ "futures-core",
+ "futures-sink",
+ "http",
+ "indexmap 2.5.0",
+ "slab",
+ "tokio",
+ "tokio-util",
+ "tracing",
+]
+
[[package]]
name = "half"
version = "2.4.1"
@@ -2668,6 +2707,7 @@ dependencies = [
"bytes",
"futures-channel",
"futures-util",
+ "h2",
"http",
"http-body",
"httparse",
@@ -2679,6 +2719,39 @@ dependencies = [
"want",
]
+[[package]]
+name = "hyper-rustls"
+version = "0.27.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08afdbb5c31130e3034af566421053ab03787c640246a446327f550d11bcb333"
+dependencies = [
+ "futures-util",
+ "http",
+ "hyper",
+ "hyper-util",
+ "rustls",
+ "rustls-pki-types",
+ "tokio",
+ "tokio-rustls",
+ "tower-service",
+]
+
+[[package]]
+name = "hyper-tls"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"
+dependencies = [
+ "bytes",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "native-tls",
+ "tokio",
+ "tokio-native-tls",
+ "tower-service",
+]
+
[[package]]
name = "hyper-util"
version = "0.1.7"
@@ -3330,6 +3403,16 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
+[[package]]
+name = "mime_guess"
+version = "2.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
+dependencies = [
+ "mime",
+ "unicase",
+]
+
[[package]]
name = "minimal-lexical"
version = "0.2.1"
@@ -3464,6 +3547,23 @@ dependencies = [
"jobserver",
]
+[[package]]
+name = "native-tls"
+version = "0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8614eb2c83d59d1c8cc974dd3f920198647674a0a035e1af1fa58707e317466"
+dependencies = [
+ "libc",
+ "log",
+ "openssl",
+ "openssl-probe",
+ "openssl-sys",
+ "schannel",
+ "security-framework",
+ "security-framework-sys",
+ "tempfile",
+]
+
[[package]]
name = "ndk"
version = "0.7.0"
@@ -3934,6 +4034,50 @@ dependencies = [
"pathdiff",
]
+[[package]]
+name = "openssl"
+version = "0.10.66"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9529f4786b70a3e8c61e11179af17ab6188ad8d0ded78c5529441ed39d4bd9c1"
+dependencies = [
+ "bitflags 2.6.0",
+ "cfg-if 1.0.0",
+ "foreign-types 0.3.2",
+ "libc",
+ "once_cell",
+ "openssl-macros",
+ "openssl-sys",
+]
+
+[[package]]
+name = "openssl-macros"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.75",
+]
+
+[[package]]
+name = "openssl-probe"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
+
+[[package]]
+name = "openssl-sys"
+version = "0.9.103"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f9e8deee91df40a943c71b917e5874b951d32a802526c85721ce3b776c929d6"
+dependencies = [
+ "cc",
+ "libc",
+ "pkg-config",
+ "vcpkg",
+]
+
[[package]]
name = "option-ext"
version = "0.2.0"
@@ -4695,25 +4839,34 @@ checksum = "f8f4955649ef5c38cc7f9e8aa41761d48fb9677197daea9984dc54f56aad5e63"
dependencies = [
"base64 0.22.1",
"bytes",
+ "encoding_rs",
"futures-core",
"futures-util",
+ "h2",
"http",
"http-body",
"http-body-util",
"hyper",
+ "hyper-rustls",
+ "hyper-tls",
"hyper-util",
"ipnet",
"js-sys",
"log",
"mime",
+ "mime_guess",
+ "native-tls",
"once_cell",
"percent-encoding",
"pin-project-lite",
+ "rustls-pemfile",
"serde",
"serde_json",
"serde_urlencoded",
"sync_wrapper 1.0.1",
+ "system-configuration",
"tokio",
+ "tokio-native-tls",
"tokio-util",
"tower-service",
"url",
@@ -4757,6 +4910,21 @@ dependencies = [
"bytemuck",
]
+[[package]]
+name = "ring"
+version = "0.17.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d"
+dependencies = [
+ "cc",
+ "cfg-if 1.0.0",
+ "getrandom 0.2.15",
+ "libc",
+ "spin",
+ "untrusted",
+ "windows-sys 0.52.0",
+]
+
[[package]]
name = "rustc-demangle"
version = "0.1.24"
@@ -4791,6 +4959,46 @@ dependencies = [
"windows-sys 0.52.0",
]
+[[package]]
+name = "rustls"
+version = "0.23.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2dabaac7466917e566adb06783a81ca48944c6898a1b08b9374106dd671f4c8"
+dependencies = [
+ "once_cell",
+ "rustls-pki-types",
+ "rustls-webpki",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-pemfile"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "196fe16b00e106300d3e45ecfcb764fa292a535d7326a29a5875c579c7417425"
+dependencies = [
+ "base64 0.22.1",
+ "rustls-pki-types",
+]
+
+[[package]]
+name = "rustls-pki-types"
+version = "1.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc0a2ce646f8655401bb81e7927b812614bd5d91dbc968696be50603510fcaf0"
+
+[[package]]
+name = "rustls-webpki"
+version = "0.102.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
+]
+
[[package]]
name = "rustversion"
version = "1.0.17"
@@ -4832,6 +5040,15 @@ dependencies = [
"windows-capture",
]
+[[package]]
+name = "schannel"
+version = "0.1.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e9aaafd5a2b6e3d657ff009d82fbd630b6bd54dd4eb06f21693925cdf80f9b8b"
+dependencies = [
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "schemars"
version = "0.8.21"
@@ -4893,6 +5110,29 @@ dependencies = [
"once_cell",
]
+[[package]]
+name = "security-framework"
+version = "2.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"
+dependencies = [
+ "bitflags 2.6.0",
+ "core-foundation 0.9.4",
+ "core-foundation-sys 0.8.7",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75da29fe9b9b08fe9d6b22b5b4bcbc75d8db3aa31e639aa56bb62e9d46bfceaf"
+dependencies = [
+ "core-foundation-sys 0.8.7",
+ "libc",
+]
+
[[package]]
name = "selectors"
version = "0.22.0"
@@ -5355,6 +5595,12 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
[[package]]
name = "swift-rs"
version = "1.0.6"
@@ -5427,6 +5673,27 @@ dependencies = [
"windows 0.52.0",
]
+[[package]]
+name = "system-configuration"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b"
+dependencies = [
+ "bitflags 2.6.0",
+ "core-foundation 0.9.4",
+ "system-configuration-sys",
+]
+
+[[package]]
+name = "system-configuration-sys"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
+dependencies = [
+ "core-foundation-sys 0.8.7",
+ "libc",
+]
+
[[package]]
name = "system-deps"
version = "6.2.2"
@@ -6058,6 +6325,27 @@ dependencies = [
"syn 2.0.75",
]
+[[package]]
+name = "tokio-native-tls"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"
+dependencies = [
+ "native-tls",
+ "tokio",
+]
+
+[[package]]
+name = "tokio-rustls"
+version = "0.26.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4"
+dependencies = [
+ "rustls",
+ "rustls-pki-types",
+ "tokio",
+]
+
[[package]]
name = "tokio-tungstenite"
version = "0.21.0"
@@ -6375,6 +6663,15 @@ dependencies = [
"unic-common",
]
+[[package]]
+name = "unicase"
+version = "2.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f7d2d4dafb69621809a81864c9c1b864479e1235c0dd4e199924b9742439ed89"
+dependencies = [
+ "version_check",
+]
+
[[package]]
name = "unicode-bidi"
version = "0.3.15"
@@ -6414,6 +6711,12 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "229730647fbc343e3a80e463c1db7f78f3855d3f3739bee0dda773c9a037c90a"
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
[[package]]
name = "url"
version = "2.5.2"
@@ -7507,6 +7810,12 @@ dependencies = [
"syn 2.0.75",
]
+[[package]]
+name = "zeroize"
+version = "1.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde"
+
[[package]]
name = "zune-core"
version = "0.4.12"
diff --git a/apps/desktop-solid/src-tauri/Cargo.toml b/apps/desktop-solid/src-tauri/Cargo.toml
index bd6c21369..eafee55f1 100644
--- a/apps/desktop-solid/src-tauri/Cargo.toml
+++ b/apps/desktop-solid/src-tauri/Cargo.toml
@@ -67,6 +67,8 @@ cap-utils = { path = "../../../crates/utils" }
cap-project = { path = "../../../crates/project" }
cap-rendering = { path = "../../../crates/rendering" }
cap-ffmpeg = { path = "../../../crates/ffmpeg" }
+reqwest = { version = "0.12.7", features = ["json", "stream", "multipart"] }
+dotenvy_macro = "0.15.7"
[target.'cfg(target_os = "macos")'.dependencies]
core-graphics = "0.24.0"
diff --git a/apps/desktop-solid/src-tauri/src/auth.rs b/apps/desktop-solid/src-tauri/src/auth.rs
new file mode 100644
index 000000000..fe67bd69a
--- /dev/null
+++ b/apps/desktop-solid/src-tauri/src/auth.rs
@@ -0,0 +1,26 @@
+use serde::{Deserialize, Serialize};
+use specta::Type;
+use tauri::{AppHandle, Manager, Wry};
+use tauri_plugin_store::{with_store, StoreCollection};
+
+#[derive(Serialize, Deserialize, Type)]
+pub struct AuthStore {
+ pub token: String,
+ pub expires: i32,
+}
+
+impl AuthStore {
+ pub fn get(app: &AppHandle) -> Result<Option<Self>, String> {
+ let stores = app
+ .try_state::<StoreCollection<Wry>>()
+ .ok_or("Store not found")?;
+ with_store(app.clone(), stores, "store", |store| {
+ let Some(store) = store.get("auth").cloned() else {
+ return Ok(None);
+ };
+
+ Ok(serde_json::from_value(store)?)
+ })
+ .map_err(|e| e.to_string())
+ }
+}
diff --git a/apps/desktop-solid/src-tauri/src/lib.rs b/apps/desktop-solid/src-tauri/src/lib.rs
index 7c5616638..dc49ac44d 100644
--- a/apps/desktop-solid/src-tauri/src/lib.rs
+++ b/apps/desktop-solid/src-tauri/src/lib.rs
@@ -1,4 +1,5 @@
mod audio;
+mod auth;
mod camera;
mod display;
mod editor;
@@ -9,7 +10,9 @@ mod playback;
mod project_recordings;
mod recording;
mod tray;
+mod upload;
+use auth::AuthStore;
use camera::{create_camera_window, list_cameras};
use cap_ffmpeg::FFmpeg;
use cap_project::ProjectConfiguration;
@@ -44,6 +47,7 @@ use tokio::{
sync::{Mutex, RwLock},
time::sleep,
};
+use upload::upload_video;
#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
@@ -132,7 +136,9 @@ impl App {
pub fn clear_current_recording(&mut self) -> Option<InProgressRecording> {
self.close_occluder_window();
- CurrentRecordingChanged(JsonValue::new(&None)).emit(&self.handle).ok();
+ CurrentRecordingChanged(JsonValue::new(&None))
+ .emit(&self.handle)
+ .ok();
self.current_recording.take()
}
@@ -653,7 +659,7 @@ async fn copy_rendered_video_to_clipboard(
video_id: String,
project: ProjectConfiguration,
) -> Result<(), String> {
- println!("copying");
+ println!("copying");
let output_path = match get_rendered_video(app.clone(), video_id.clone(), project).await {
Ok(path) => {
println!("Successfully retrieved rendered video path: {:?}", path);
@@ -862,7 +868,7 @@ fn show_previous_recordings_window(app: AppHandle) {
.accept_first_mouse(true)
.content_protected(true)
.inner_size(
- 800.0,
+ 800.0,
(monitor.size().height as f64) / monitor.scale_factor(),
)
.position(0.0, 0.0)
@@ -960,35 +966,6 @@ fn close_previous_recordings_window(app: AppHandle) {
}
}
-fn handle_ffmpeg_installation() -> Result<(), String> {
- if ffmpeg_is_installed() {
- println!("FFmpeg is already installed! πŸŽ‰");
- return Ok(());
- }
-
- println!("FFmpeg not found. Attempting to install...");
- match check_latest_version() {
- Ok(version) => println!("Latest available version: {}", version),
- Err(e) => println!("Skipping version check due to error: {e}"),
- }
-
- let download_url = ffmpeg_download_url().map_err(|e| e.to_string())?;
- let destination = sidecar_dir().map_err(|e| e.to_string())?;
-
- println!("Downloading from: {:?}", download_url);
- let archive_path =
- download_ffmpeg_package(download_url, &destination).map_err(|e| e.to_string())?;
- println!("Downloaded package: {:?}", archive_path);
-
- println!("Extracting...");
- unpack_ffmpeg(&archive_path, &destination).map_err(|e| e.to_string())?;
-
- let version = ffmpeg_version().map_err(|e| e.to_string())?;
-
- println!("Done! Installed FFmpeg version {} 🏁", version);
- Ok(())
-}
-
fn on_recording_options_change(app: &AppHandle, options: &RecordingOptions) {
match app.get_webview_window(camera::WINDOW_LABEL) {
Some(window) if options.camera_label.is_none() => {
@@ -1138,6 +1115,58 @@ fn open_main_window(app: AppHandle) {
window.set_traffic_lights_inset(14.0, 22.0).unwrap();
}
+#[tauri::command]
+#[specta::specta]
+async fn upload_rendered_video(
+ app: AppHandle,
+ video_id: String,
+ project: ProjectConfiguration,
+) -> Result<(), String> {
+ let Ok(Some(auth)) = AuthStore::get(&app) else {
+ println!("not authenticated!");
+ return Err("Not authenticated".to_string());
+ };
+
+ let output_path = match get_rendered_video(app.clone(), video_id.clone(), project).await {
+ Ok(path) => {
+ println!("Successfully retrieved rendered video path: {:?}", path);
+ path
+ }
+ Err(e) => {
+ println!("Failed to get rendered video: {}", e);
+ return Err(format!("Failed to get rendered video: {}", e));
+ }
+ };
+
+ let shareable_link = upload_video(video_id, auth.token, output_path).await.unwrap();
+
+ println!("Copying to clipboard: {:?}", shareable_link);
+
+ #[cfg(target_os = "macos")]
+ {
+ use cocoa::appkit::NSPasteboard;
+ use cocoa::base::{id, nil};
+ use cocoa::foundation::{NSArray, NSString, NSURL};
+ use objc::rc::autoreleasepool;
+
+ unsafe {
+ autoreleasepool(|| {
+ let pasteboard: id = NSPasteboard::generalPasteboard(nil);
+ NSPasteboard::clearContents(pasteboard);
+
+ let url =
+ NSURL::fileURLWithPath_(nil, NSString::alloc(nil).init_str(&shareable_link));
+
+ let objects: id = NSArray::arrayWithObject(nil, url);
+
+ NSPasteboard::writeObjects(pasteboard, objects);
+ });
+ }
+ }
+
+ Ok(())
+}
+
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let specta_builder = tauri_specta::Builder::new()
@@ -1170,7 +1199,8 @@ pub fn run() {
open_editor,
open_main_window,
permissions::open_permission_settings,
- permissions::do_permissions_check
+ permissions::do_permissions_check,
+ upload_rendered_video
])
.events(tauri_specta::collect_events![
RecordingOptionsChanged,
@@ -1180,7 +1210,8 @@ pub fn run() {
EditorStateChanged,
CurrentRecordingChanged
])
- .ty::<ProjectConfiguration>();
+ .ty::<ProjectConfiguration>()
+ .ty::<AuthStore>();
#[cfg(debug_assertions)] // <- Only export on non-release builds
specta_builder
@@ -1204,7 +1235,7 @@ pub fn run() {
let app_handle = app.handle();
- if let Err(_error) = handle_ffmpeg_installation() {
+ if let Err(_error) = FFmpeg::install_if_necessary() {
println!("Failed to install FFmpeg, which is required for Cap to function. Shutting down now");
// TODO: UI message instead
panic!("Failed to install FFmpeg, which is required for Cap to function. Shutting down now")
diff --git a/apps/desktop-solid/src-tauri/src/upload.rs b/apps/desktop-solid/src-tauri/src/upload.rs
new file mode 100644
index 000000000..514c6b72a
--- /dev/null
+++ b/apps/desktop-solid/src-tauri/src/upload.rs
@@ -0,0 +1,219 @@
+// credit @filleduchaos
+
+use mp4::Mp4Reader;
+use reqwest::{multipart::Form, Client, StatusCode};
+use std::fs::File;
+use std::io::{BufReader, Read, Write};
+use std::path::{Path, PathBuf};
+
+#[derive(serde::Deserialize)]
+struct S3UploadMeta {
+ id: String,
+ user_id: String,
+ aws_region: String,
+ aws_bucket: String,
+}
+
+#[derive(serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+struct S3UploadBody {
+ user_id: String,
+ file_key: String,
+ aws_bucket: String,
+ aws_region: String,
+}
+
+#[derive(serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+struct S3VideoUploadBody {
+ #[serde(flatten)]
+ base: S3UploadBody,
+ duration: String,
+ resolution: String,
+ framerate: String,
+ bandwidth: String,
+ video_codec: String,
+}
+
+pub async fn upload_video(
+ video_id: String,
+ auth_token: String,
+ file_path: PathBuf,
+) -> Result<String, String> {
+ println!("Uploading video {video_id}...");
+
+ 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 server_url_base: &'static str = dotenvy_macro::dotenv!("NEXT_PUBLIC_URL");
+ dbg!(server_url_base);
+ let s3_config = get_s3_config(&client, server_url_base, &auth_token).await?;
+
+ let file_key = format!("{}/{}/{}", s3_config.user_id, s3_config.id, file_name);
+
+ println!("File key: {file_key}");
+
+ let body = build_video_upload_body(
+ &file_path,
+ S3UploadBody {
+ user_id: s3_config.user_id,
+ file_key: file_key.clone(),
+ aws_bucket: s3_config.aws_bucket,
+ aws_region: s3_config.aws_region,
+ },
+ )?;
+
+ let (upload_url, mut form) =
+ presigned_s3_url(&client, server_url_base, body, &auth_token).await?;
+
+ 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("video/mp4")
+ .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!("File uploaded successfully");
+ return Ok(format!("{server_url_base}/s/{}", s3_config.id));
+ }
+
+ let status = response.status();
+ let error_body = response
+ .text()
+ .await
+ .unwrap_or_else(|_| "<no response body>".to_string());
+ tracing::error!(
+ "Failed to upload file. Status: {}. Body: {}",
+ status,
+ error_body
+ );
+ return Err(format!(
+ "Failed to upload file. Status: {}. Body: {}",
+ status, error_body
+ ));
+}
+
+async fn get_s3_config(
+ client: &Client,
+ server_url_base: &str,
+ auth_token: &str,
+) -> Result<S3UploadMeta, String> {
+ let config_url = format!(
+ "{}/api/desktop/video/create?origin={}",
+ server_url_base, server_url_base
+ );
+
+ let response = client
+ .get(config_url)
+ .header("Authorization", format!("Bearer {auth_token}"))
+ .send()
+ .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());
+ }
+
+ let config = response.json::<S3UploadMeta>().await.map_err(|e| {
+ format!(
+ "Failed to read and deserialize response from Next.js handler: {}",
+ e
+ )
+ })?;
+
+ Ok(config)
+}
+
+async fn presigned_s3_url(
+ client: &Client,
+ server_url_base: &str,
+ body: S3VideoUploadBody,
+ auth_token: &str,
+) -> Result<(String, Form), String> {
+ let presigned_upload_url = format!("{}/api/upload/signed", server_url_base);
+
+ let response = client
+ .post(presigned_upload_url)
+ .json(&serde_json::json!(body))
+ .header("Authorization", format!("Bearer {auth_token}"))
+ .send()
+ .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());
+ }
+
+ 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());
+ }
+
+ Ok((post_url, form))
+}
+
+fn build_video_upload_body(
+ path: &PathBuf,
+ base: S3UploadBody,
+) -> Result<S3VideoUploadBody, String> {
+ let input =
+ ffmpeg_next::format::input(path).map_err(|e| format!("Failed to read input file: {e}"))?;
+ let stream = input
+ .streams()
+ .best(ffmpeg_next::media::Type::Video)
+ .ok_or_else(|| format!("Failed to find appropriate video stream in file"))?;
+
+ let duration_millis = input.duration() as f64 / 1000.;
+
+ let codec = ffmpeg_next::codec::context::Context::from_parameters(stream.parameters())
+ .map_err(|e| format!("Unable to read video codec information: {e}"))?;
+ let codec_name = codec.id();
+ let video = codec.decoder().video().unwrap();
+ let width = video.width();
+ let height = video.height();
+ let frame_rate = video
+ .frame_rate()
+ .map(|fps| fps.to_string())
+ .unwrap_or("-".into());
+ let bit_rate = video.bit_rate();
+
+ Ok(S3VideoUploadBody {
+ base,
+ duration: duration_millis.to_string(),
+ resolution: format!("{}x{}", width, height),
+ framerate: frame_rate,
+ bandwidth: bit_rate.to_string(),
+ video_codec: format!("{codec_name:?}").replace("Id::", "").to_lowercase(),
+ })
+}
diff --git a/apps/desktop-solid/src/routes/createPresets.ts b/apps/desktop-solid/src/routes/createPresets.ts
index 929b85661..34163cb62 100644
--- a/apps/desktop-solid/src/routes/createPresets.ts
+++ b/apps/desktop-solid/src/routes/createPresets.ts
@@ -56,7 +56,7 @@ export function createPresets() {
const p = query();
if (!p) return;
- return p.presets[p.default ?? 0].config;
+ return p.presets[p.default ?? 0]?.config;
},
setDefault: (index: number) =>
updatePresets((prev) => ({
diff --git a/apps/desktop-solid/src/routes/prev-recordings.tsx b/apps/desktop-solid/src/routes/prev-recordings.tsx
index 6790b90a8..2136d07b9 100644
--- a/apps/desktop-solid/src/routes/prev-recordings.tsx
+++ b/apps/desktop-solid/src/routes/prev-recordings.tsx
@@ -11,18 +11,16 @@ import {
createEffect,
createResource,
createSignal,
- on,
onCleanup,
} from "solid-js";
-import createPresence from "solid-presence";
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";
+
import { commands, events } from "../utils/tauri";
import { DEFAULT_PROJECT_CONFIG } from "./editor/projectConfig";
import { createPresets } from "./createPresets";
@@ -84,10 +82,11 @@ export default function () {
const copyVideo = createMutation(() => ({
mutationFn: async () => {
- await commands.copyRenderedVideoToClipboard(
+ const res = await commands.copyRenderedVideoToClipboard(
videoId,
presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
);
+ if (res.status !== "ok") throw new Error(res.error);
},
}));
@@ -113,6 +112,17 @@ export default function () {
},
}));
+ const uploadVideo = createMutation(() => ({
+ mutationFn: async () => {
+ console.log("bruh");
+ const res = await commands.uploadRenderedVideo(
+ videoId,
+ presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
+ );
+ if (res.status !== "ok") throw new Error(res.error);
+ },
+ }));
+
const [metadata] = createResource(async () => {
const result = await commands.getVideoMetadata(
recording.path,
@@ -247,14 +257,36 @@ export default function () {
</Switch>
</TooltipIconButton>
<TooltipIconButton
- class="absolute right-3 bottom-3"
- tooltipText="Create Shareable Link"
+ class="absolute right-3 bottom-3 z-20"
+ tooltipText={
+ uploadVideo.isPending
+ ? "Uploading Cap"
+ : "Create Shareable Link"
+ }
+ forceOpen={uploadVideo.isPending}
tooltipPlacement="left"
- onClick={async () => {
- // Implement shareable link functionality here
- }}
+ onClick={() => uploadVideo.mutate()}
+ disabled={uploadVideo.isPending}
>
- <IconCapUpload class="size-[1rem]" />
+ <Switch
+ fallback={<IconCapUpload class="size-[1rem]" />}
+ >
+ <Match when={uploadVideo.isPending}>
+ <IconLucideLoaderCircle class="size-[1rem] animate-spin" />
+ </Match>
+ <Match when={uploadVideo.isSuccess}>
+ {(_) => {
+ setTimeout(() => {
+ if (!uploadVideo.isPending)
+ uploadVideo.reset();
+ }, 2000);
+
+ return (
+ <IconLucideCheck class="size-[1rem]" />
+ );
+ }}
+ </Match>
+ </Switch>
</TooltipIconButton>
<div class="absolute inset-0 flex items-center justify-center">
<Button
diff --git a/apps/desktop-solid/src/store.ts b/apps/desktop-solid/src/store.ts
index e82db4a1e..514438f57 100644
--- a/apps/desktop-solid/src/store.ts
+++ b/apps/desktop-solid/src/store.ts
@@ -1,6 +1,6 @@
import { Store } from "@tauri-apps/plugin-store";
-import type { ProjectConfiguration } from "./utils/tauri";
+import type { AuthStore, ProjectConfiguration } from "./utils/tauri";
const store = new Store("store");
@@ -22,11 +22,6 @@ export const presetsStore = {
store.onKeyChange<PresetsStore>("presets", fn),
};
-export type AuthStore = {
- token: string;
- expires: number;
-};
-
export const authStore = {
get: () => store.get<AuthStore>("auth"),
set: async (value: AuthStore | null) => {
diff --git a/apps/desktop-solid/src/utils/tauri.ts b/apps/desktop-solid/src/utils/tauri.ts
index 14b52a871..92294d296 100644
--- a/apps/desktop-solid/src/utils/tauri.ts
+++ b/apps/desktop-solid/src/utils/tauri.ts
@@ -156,6 +156,14 @@ async openPermissionSettings(settings: OSPermissionSettings) : Promise<void> {
},
async doPermissionsCheck() : Promise<OSPermissionsCheck> {
return await TAURI_INVOKE("do_permissions_check");
+},
+async uploadRenderedVideo(videoId: string, project: ProjectConfiguration) : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("upload_rendered_video", { videoId, project }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
}
}
@@ -187,6 +195,7 @@ showCapturesPanel: "show-captures-panel"
export type AspectRatio = "wide" | "vertical" | "square" | "classic" | "tall"
export type Audio = { duration: number; sample_rate: number; channels: number }
export type AudioConfiguration = { mute: boolean; improve: boolean }
+export type AuthStore = { token: string; expires: number }
export type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; inset: number; crop: Crop | null }
export type BackgroundSource = { type: "wallpaper"; id: number } | { type: "image"; path: string | null } | { type: "color"; value: [number, number, number] } | { type: "gradient"; from: [number, number, number]; to: [number, number, number] }
export type Bounds = { x: number; y: number; width: number; height: number }
diff --git a/crates/ffmpeg/src/lib.rs b/crates/ffmpeg/src/lib.rs
index e716ee8c3..d1abe8e51 100644
--- a/crates/ffmpeg/src/lib.rs
+++ b/crates/ffmpeg/src/lib.rs
@@ -309,29 +309,29 @@ impl FFmpeg {
pub fn start(self) -> FFmpegProcess {
FFmpegProcess::spawn(self.command)
}
-}
-pub fn handle_ffmpeg_installation() -> Result<(), String> {
- if ffmpeg_is_installed() {
- return Ok(());
- }
+ pub fn install_if_necessary() -> Result<(), String> {
+ if ffmpeg_is_installed() {
+ return Ok(());
+ }
- match check_latest_version() {
- Ok(version) => println!("Latest available version: {}", version),
- Err(e) => println!("Skipping version check due to error: {e}"),
- }
+ match check_latest_version() {
+ Ok(version) => println!("Latest available version: {}", version),
+ Err(e) => println!("Skipping version check due to error: {e}"),
+ }
- let download_url = ffmpeg_download_url().map_err(|e| e.to_string())?;
- let destination = sidecar_dir().map_err(|e| e.to_string())?;
+ let download_url = ffmpeg_download_url().map_err(|e| e.to_string())?;
+ let destination = sidecar_dir().map_err(|e| e.to_string())?;
- let archive_path =
- download_ffmpeg_package(download_url, &destination).map_err(|e| e.to_string())?;
+ let archive_path =
+ download_ffmpeg_package(download_url, &destination).map_err(|e| e.to_string())?;
- unpack_ffmpeg(&archive_path, &destination).map_err(|e| e.to_string())?;
+ unpack_ffmpeg(&archive_path, &destination).map_err(|e| e.to_string())?;
- let version = ffmpeg_version().map_err(|e| e.to_string())?;
+ let version = ffmpeg_version().map_err(|e| e.to_string())?;
- println!("Done! Installed FFmpeg version {} 🏁", version);
+ println!("Done! Installed FFmpeg version {} 🏁", version);
- Ok(())
+ Ok(())
+ }
}