Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

allow reuploading instant mode recordings (#372)

Brendan Allan7044a9014aa2
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index b8f593823..dd4f0dffa 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -76,6 +76,7 @@ use tauri_plugin_notification::{NotificationExt, PermissionState};
use tauri_plugin_shell::ShellExt;
use tauri_specta::Event;
use tokio::sync::{Mutex, RwLock};
+use tracing::info;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::Layer;
@@ -1883,6 +1884,56 @@ fn set_fail(name: String, value: bool) {
cap_fail::set_fail(&name, value)
}
+#[tauri::command(async)]
+#[specta::specta]
+async fn reupload_instant_video(app: AppHandle, video_id: String) -> Result<(), String> {
+ let recording_dir = app
+ .path()
+ .app_data_dir()
+ .unwrap()
+ .join("recordings")
+ .join(format!("{video_id}.cap"));
+
+ let meta = RecordingMeta::load_for_project(&recording_dir)?;
+
+ let Some(share_id) = meta.sharing.map(|s| s.id) else {
+ return Err("Video share data not found".to_string());
+ };
+
+ let config = match AuthStore::get(&app).ok().flatten() {
+ Some(_) => match get_s3_config(&app, false, Some(share_id)).await {
+ Ok(s3_config) => {
+ let link = web_api::make_url(format!("/s/{}", s3_config.id()));
+ info!("Created shareable link: {}", link);
+
+ VideoUploadInfo {
+ id: s3_config.id().to_string(),
+ link: link.clone(),
+ config: s3_config,
+ }
+ }
+ Err(e) => return Err(format!("Failed to get upload config: {e}")),
+ },
+ // Allow the recording to proceed without error for any signed-in user
+ _ => {
+ // User is not signed in
+ ShowCapWindow::SignIn.show(&app).ok();
+ return Err("Please sign in to use instant recording".to_string());
+ }
+ };
+
+ upload::InstantMultipartUpload::run(
+ app,
+ video_id,
+ recording_dir.join("content/output.mp4"),
+ config,
+ false,
+ )
+ .await;
+
+ Ok(())
+}
+
async fn check_notification_permissions(app: AppHandle) {
// Check if we've already requested permissions
let Ok(Some(settings)) = GeneralSettingsStore::get(&app) else {
@@ -2038,7 +2089,8 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
get_wallpaper_path,
list_fails,
set_fail,
- update_auth_plan
+ update_auth_plan,
+ reupload_instant_video
])
.events(tauri_specta::collect_events![
RecordingOptionsChanged,
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index fd7b2df30..0a6df70e0 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -7,7 +7,7 @@ use crate::{
general_settings::GeneralSettingsStore,
open_editor, open_external_link,
presets::PresetsStore,
- upload::{get_s3_config, prepare_screenshot_upload, upload_video, ProgressiveUploadTask},
+ upload::{get_s3_config, prepare_screenshot_upload, upload_video, InstantMultipartUpload},
web_api,
windows::{CapWindowId, ShowCapWindow},
App, CurrentRecordingChanged, DynLoggingLayer, MutableState, NewStudioRecordingAdded,
@@ -20,7 +20,7 @@ use cap_media::{
sources::{CaptureScreen, CaptureWindow},
};
use cap_project::{
- ProjectConfiguration, RecordingMeta, RecordingMetaInner, StudioRecordingMeta,
+ ProjectConfiguration, RecordingMeta, RecordingMetaInner, SharingMeta, StudioRecordingMeta,
TimelineConfiguration, TimelineSegment, ZoomSegment,
};
use cap_recording::{
@@ -38,7 +38,7 @@ use tracing_subscriber::Layer;
pub enum InProgressRecording {
Instant {
handle: InstantRecordingHandle,
- progressive_upload: Option<ProgressiveUploadTask>,
+ progressive_upload: Option<InstantMultipartUpload>,
video_upload_info: VideoUploadInfo,
},
Studio {
@@ -94,7 +94,7 @@ impl InProgressRecording {
pub enum CompletedRecording {
Instant {
recording: CompletedInstantRecording,
- progressive_upload: Option<ProgressiveUploadTask>,
+ progressive_upload: Option<InstantMultipartUpload>,
video_upload_info: VideoUploadInfo,
},
Studio(CompletedStudioRecording),
@@ -221,7 +221,7 @@ pub async fn start_recording(
.as_ref()
.filter(|_| matches!(recording_options.mode, RecordingMode::Instant))
.map(|video_upload_info| {
- ProgressiveUploadTask::spawn(
+ InstantMultipartUpload::spawn(
app.clone(),
id.clone(),
recording_dir.join("content/output.mp4"),
@@ -436,7 +436,7 @@ async fn handle_recording_finish(
let mut shareable_link = None;
- let meta_inner = match completed_recording {
+ let (meta_inner, sharing) = match completed_recording {
CompletedRecording::Studio(recording) => {
let recordings = ProjectRecordings::new(&recording_dir, &recording.meta);
@@ -461,7 +461,7 @@ async fn handle_recording_finish(
}
.emit(app);
- RecordingMetaInner::Studio(recording.meta)
+ (RecordingMetaInner::Studio(recording.meta), None)
}
CompletedRecording::Instant {
recording,
@@ -472,77 +472,88 @@ async fn handle_recording_finish(
let app = app.clone();
let output_path = recording_dir.join("content/output.mp4");
- spawn_actor(async move {
- if let Some(progressive_upload) = progressive_upload {
- let video_upload_succeeded = match progressive_upload
- .handle
- .await
- .map_err(|e| e.to_string())
- .and_then(|r| r)
- {
- Ok(()) => {
- info!("Not attempting instant recording upload as progressive upload succeeded");
- true
- }
- Err(e) => {
- error!("Progressive upload failed: {}", e);
- false
- }
- };
-
- if video_upload_succeeded {
- let (screenshot_url, screenshot_form) = match prepare_screenshot_upload(
- &app,
- &video_upload_info.config.clone(),
- display_screenshot,
- )
- .await
+ {
+ let video_upload_info = video_upload_info.clone();
+ spawn_actor(async move {
+ if let Some(progressive_upload) = progressive_upload {
+ let video_upload_succeeded = match progressive_upload
+ .handle
+ .await
+ .map_err(|e| e.to_string())
+ .and_then(|r| r)
{
- Ok(v) => v,
+ Ok(()) => {
+ info!("Not attempting instant recording upload as progressive upload succeeded");
+ true
+ }
Err(e) => {
- error!("Failed to prepare screenshot upload: {e}");
- return;
+ error!("Progressive upload failed: {}", e);
+ false
}
};
- let resp = reqwest::Client::new()
- .post(screenshot_url)
- .multipart(screenshot_form)
- .send()
- .await;
-
- match resp {
- Ok(r) if r.status() == 200 => {
- info!("Screenshot uploaded successfully");
- }
- Ok(r) => {
- error!("Failed to upload screenshot: {}", r.status());
+ if video_upload_succeeded {
+ let (screenshot_url, screenshot_form) = match prepare_screenshot_upload(
+ &app,
+ &video_upload_info.config.clone(),
+ display_screenshot,
+ )
+ .await
+ {
+ Ok(v) => v,
+ Err(e) => {
+ error!("Failed to prepare screenshot upload: {e}");
+ return;
+ }
+ };
+
+ let resp = reqwest::Client::new()
+ .post(screenshot_url)
+ .multipart(screenshot_form)
+ .send()
+ .await;
+
+ match resp {
+ Ok(r) if r.status() == 200 => {
+ info!("Screenshot uploaded successfully");
+ }
+ Ok(r) => {
+ error!("Failed to upload screenshot: {}", r.status());
+ }
+ Err(e) => {
+ error!("Failed to upload screenshot: {e}");
+ }
}
- Err(e) => {
- error!("Failed to upload screenshot: {e}");
- }
- }
- } else {
- // The upload_video function handles screenshot upload, so we can pass it along
- match upload_video(
- &app,
- video_upload_info.id.clone(),
- output_path,
- Some(video_upload_info.config.clone()),
- Some(display_screenshot.clone()),
- )
- .await
- {
- Ok(_) => {
- info!("Final video upload with screenshot completed successfully")
+ } else {
+ // The upload_video function handles screenshot upload, so we can pass it along
+ match upload_video(
+ &app,
+ video_upload_info.id.clone(),
+ output_path,
+ Some(video_upload_info.config.clone()),
+ Some(display_screenshot.clone()),
+ )
+ .await
+ {
+ Ok(_) => {
+ info!(
+ "Final video upload with screenshot completed successfully"
+ )
+ }
+ Err(e) => error!("Error in final upload with screenshot: {}", e),
}
- Err(e) => error!("Error in final upload with screenshot: {}", e),
}
}
- }
- });
+ });
+ }
- RecordingMetaInner::Instant(recording.meta)
+ (
+ RecordingMetaInner::Instant(recording.meta),
+ Some(SharingMeta {
+ link: video_upload_info.link,
+ id: video_upload_info.id,
+ }),
+ )
}
};
@@ -553,7 +564,7 @@ async fn handle_recording_finish(
let meta = RecordingMeta {
project_path: recording_dir,
- sharing: None,
+ sharing,
pretty_name: format!(
"Cap {}",
chrono::Local::now().format("%Y-%m-%d at %H.%M.%S")
diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rs
index 2c9cae75e..b4736c493 100644
--- a/apps/desktop/src-tauri/src/upload.rs
+++ b/apps/desktop/src-tauri/src/upload.rs
@@ -803,11 +803,11 @@ async fn compress_image(path: PathBuf) -> Result<Vec<u8>, String> {
const CHUNK_SIZE: u64 = 5 * 1024 * 1024; // 5MB
const MIN_PART_SIZE: u64 = 5 * 1024 * 1024; // For non-final parts
-pub struct ProgressiveUploadTask {
+pub struct InstantMultipartUpload {
pub handle: tokio::task::JoinHandle<Result<(), String>>,
}
-impl ProgressiveUploadTask {
+impl InstantMultipartUpload {
/// starts a progressive (multipart) upload that runs until recording stops
/// and the file has stabilized (no additional data is being written).
pub fn spawn(
@@ -817,371 +817,378 @@ impl ProgressiveUploadTask {
pre_created_video: VideoUploadInfo,
) -> Self {
Self {
- handle: spawn_actor(async move {
- use std::time::Duration;
- use tokio::sync::mpsc;
- use tokio::time::sleep;
-
- // --------------------------------------------
- // listen for a "RecordingStopped" signal. We'll
- // finalize only after we know there's no more
- // incoming data from the pipeline (plus we do
- // an extra stabilization check).
- // --------------------------------------------
- let (recording_end_tx, mut recording_end_rx) = mpsc::channel::<()>(1);
-
- RecordingStopped::listen_any(&app.clone(), {
- let app = app.clone();
- move |_| {
- let tx = recording_end_tx.clone();
- let app = app.clone();
-
- tokio::spawn(async move {
- let state = app.state::<Arc<RwLock<App>>>();
- let app_state = state.read().await;
- if app_state.current_recording.is_none() {
- // Recording truly ended
- let _ = tx.send(()).await;
- }
- });
+ handle: spawn_actor(Self::run(app, video_id, file_path, pre_created_video, true)),
+ }
+ }
+
+ pub async fn run(
+ app: AppHandle,
+ video_id: String,
+ file_path: PathBuf,
+ pre_created_video: VideoUploadInfo,
+ // whether the video is being created at the same time as uploaded
+ realtime_uploading: bool,
+ ) -> Result<(), String> {
+ dbg!(&video_id, &file_path);
+ use std::time::Duration;
+ use tokio::sync::mpsc;
+ use tokio::time::sleep;
+
+ // --------------------------------------------
+ // listen for a "RecordingStopped" signal. We'll
+ // finalize only after we know there's no more
+ // incoming data from the pipeline (plus we do
+ // an extra stabilization check).
+ // --------------------------------------------
+ let (recording_end_tx, mut recording_end_rx) = mpsc::channel::<()>(1);
+
+ RecordingStopped::listen_any(&app.clone(), {
+ let app = app.clone();
+ move |_| {
+ let tx = recording_end_tx.clone();
+ let app = app.clone();
+
+ tokio::spawn(async move {
+ let state = app.state::<Arc<RwLock<App>>>();
+ let app_state = state.read().await;
+ if app_state.current_recording.is_none() {
+ // Recording truly ended
+ let _ = tx.send(()).await;
}
});
+ }
+ });
- // --------------------------------------------
- // basic constants and info for chunk approach
- // --------------------------------------------
- let file_name = "result.mp4";
- let client = reqwest::Client::new();
- let s3_config = pre_created_video.config;
- let file_key = format!("{}/{}/{}", s3_config.user_id(), s3_config.id(), file_name);
-
- let mut uploaded_parts = Vec::new();
- let mut part_number = 1;
- let mut last_uploaded_position: u64 = 0;
-
- let mut upload_complete = false;
- let mut recording_stopped = false;
-
- println!("Starting multipart upload for {video_id}...");
-
- // --------------------------------------------
- // wait until the file hits 5MB or more
- // before initiating the multipart upload.
- // --------------------------------------------
- loop {
- if !file_path.exists() {
- println!("File does not exist yet, waiting...");
+ // --------------------------------------------
+ // basic constants and info for chunk approach
+ // --------------------------------------------
+ let file_name = "result.mp4";
+ let client = reqwest::Client::new();
+ let s3_config = pre_created_video.config;
+ let file_key = format!("{}/{}/{}", s3_config.user_id(), s3_config.id(), file_name);
+
+ let mut uploaded_parts = Vec::new();
+ let mut part_number = 1;
+ let mut last_uploaded_position: u64 = 0;
+
+ let mut upload_complete = false;
+ let mut recording_stopped = false;
+
+ println!("Starting multipart upload for {video_id}...");
+
+ // --------------------------------------------
+ // wait until the file hits 5MB or more
+ // before initiating the multipart upload.
+ // --------------------------------------------
+ loop {
+ if !file_path.exists() {
+ println!("File does not exist yet, waiting...");
+ sleep(Duration::from_millis(500)).await;
+ continue;
+ }
+ match tokio::fs::metadata(&file_path).await {
+ Ok(metadata) => {
+ if metadata.len() < MIN_PART_SIZE {
sleep(Duration::from_millis(500)).await;
continue;
- }
- match tokio::fs::metadata(&file_path).await {
- Ok(metadata) => {
- if metadata.len() < MIN_PART_SIZE {
- sleep(Duration::from_millis(500)).await;
- continue;
- } else {
- break;
- }
- }
- Err(e) => {
- println!("Failed to get file metadata: {}", e);
- sleep(Duration::from_millis(500)).await;
- }
+ } else {
+ break;
}
}
+ Err(e) => {
+ println!("Failed to get file metadata: {}", e);
+ sleep(Duration::from_millis(500)).await;
+ }
+ }
+ }
- // Copy link to clipboard early
- let _ = app.clipboard().write_text(pre_created_video.link.clone());
+ // Copy link to clipboard early
+ let _ = app.clipboard().write_text(pre_created_video.link.clone());
- notifications::send_notification(
- &app,
- notifications::NotificationType::ShareableLinkCopied,
- );
+ // --------------------------------------------
+ // initiate the multipart upload
+ // --------------------------------------------
+ println!("Initiating multipart upload for {video_id}...");
+ let initiate_response = match app
+ .authed_api_request(|c| {
+ c.post(web_api::make_url("/api/upload/multipart/initiate"))
+ .header("Content-Type", "application/json")
+ .json(&serde_json::json!({
+ "fileKey": file_key,
+ "contentType": "video/mp4"
+ }))
+ })
+ .await
+ {
+ Ok(r) => r,
+ Err(e) => {
+ return Err(format!("Failed to initiate multipart upload: {}", e));
+ }
+ };
- // --------------------------------------------
- // initiate the multipart upload
- // --------------------------------------------
- println!("Initiating multipart upload for {video_id}...");
- let initiate_response = match app
- .authed_api_request(|c| {
- c.post(web_api::make_url("/api/upload/multipart/initiate"))
- .header("Content-Type", "application/json")
- .json(&serde_json::json!({
- "fileKey": file_key,
- "contentType": "video/mp4"
- }))
- })
- .await
- {
- Ok(r) => r,
- Err(e) => {
- return Err(format!("Failed to initiate multipart upload: {}", e));
- }
- };
-
- if !initiate_response.status().is_success() {
- let status = initiate_response.status();
- let error_body = initiate_response
- .text()
- .await
- .unwrap_or_else(|_| "<no response body>".to_string());
- return Err(format!(
- "Failed to initiate multipart upload. Status: {}. Body: {}",
- status, error_body
- ));
+ if !initiate_response.status().is_success() {
+ let status = initiate_response.status();
+ let error_body = initiate_response
+ .text()
+ .await
+ .unwrap_or_else(|_| "<no response body>".to_string());
+ return Err(format!(
+ "Failed to initiate multipart upload. Status: {}. Body: {}",
+ status, error_body
+ ));
+ }
+
+ let initiate_data = match initiate_response.json::<serde_json::Value>().await {
+ Ok(d) => d,
+ Err(e) => {
+ return Err(format!("Failed to parse initiate response: {}", e));
+ }
+ };
+
+ let upload_id = match initiate_data.get("uploadId") {
+ Some(val) => val.as_str().unwrap_or("").to_string(),
+ None => {
+ return Err("No uploadId returned from initiate endpoint".to_string());
+ }
+ };
+ if upload_id.is_empty() {
+ return Err("Empty uploadId returned from initiate endpoint".to_string());
+ }
+
+ println!("Multipart upload initiated with ID: {}", upload_id);
+
+ // --------------------------------------------
+ // Main loop while upload not complete:
+ // - If we have >= CHUNK_SIZE new data, upload.
+ // - If recording hasn't stopped, keep waiting.
+ // - If recording stopped, do leftover final(s).
+ // --------------------------------------------
+ while !upload_complete {
+ if !recording_stopped {
+ // Check if the recording pipeline is done
+ if let Ok(_) = recording_end_rx.try_recv() {
+ println!("Recording end detected, will finalize soon.");
+ recording_stopped = true;
}
+ }
- let initiate_data = match initiate_response.json::<serde_json::Value>().await {
- Ok(d) => d,
- Err(e) => {
- return Err(format!("Failed to parse initiate response: {}", e));
- }
- };
+ // Check the file's current size
+ if !file_path.exists() {
+ println!("File no longer exists, aborting upload");
+ return Err("File no longer exists".to_string());
+ }
- let upload_id = match initiate_data.get("uploadId") {
- Some(val) => val.as_str().unwrap_or("").to_string(),
- None => {
- return Err("No uploadId returned from initiate endpoint".to_string());
- }
- };
- if upload_id.is_empty() {
- return Err("Empty uploadId returned from initiate endpoint".to_string());
+ let file_size = match tokio::fs::metadata(&file_path).await {
+ Ok(md) => md.len(),
+ Err(e) => {
+ println!("Failed to get file metadata: {}", e);
+ sleep(Duration::from_millis(500)).await;
+ continue;
}
+ };
- println!("Multipart upload initiated with ID: {}", upload_id);
+ let new_data_size = file_size.saturating_sub(last_uploaded_position);
- // --------------------------------------------
- // Main loop while upload not complete:
- // - If we have >= CHUNK_SIZE new data, upload.
- // - If recording hasn't stopped, keep waiting.
- // - If recording stopped, do leftover final(s).
- // --------------------------------------------
- while !upload_complete {
- if !recording_stopped {
- // Check if the recording pipeline is done
- if let Ok(_) = recording_end_rx.try_recv() {
- println!("Recording end detected, will finalize soon.");
- recording_stopped = true;
- }
+ if new_data_size >= CHUNK_SIZE {
+ // We have a full chunk to send
+ match Self::upload_chunk(
+ &app,
+ &client,
+ &file_path,
+ &file_key,
+ &upload_id,
+ &mut part_number,
+ &mut last_uploaded_position,
+ CHUNK_SIZE,
+ )
+ .await
+ {
+ Ok(part) => {
+ uploaded_parts.push(part);
}
-
- // Check the file's current size
- if !file_path.exists() {
- println!("File no longer exists, aborting upload");
- return Err("File no longer exists".to_string());
+ Err(e) => {
+ println!(
+ "Error uploading chunk (part {}): {}. Retrying in 1s...",
+ part_number, e
+ );
+ sleep(Duration::from_secs(1)).await;
+ }
+ }
+ } else {
+ if realtime_uploading {
+ // If recording is not done, keep waiting a bit
+ if !recording_stopped {
+ sleep(Duration::from_millis(500)).await;
+ continue;
}
- let file_size = match tokio::fs::metadata(&file_path).await {
- Ok(md) => md.len(),
- Err(e) => {
- println!("Failed to get file metadata: {}", e);
- sleep(Duration::from_millis(500)).await;
- continue;
- }
- };
-
- let new_data_size = file_size.saturating_sub(last_uploaded_position);
-
- if new_data_size >= CHUNK_SIZE {
- // We have a full chunk to send
- match Self::upload_chunk(
- &app,
- &client,
- &file_path,
- &file_key,
- &upload_id,
- &mut part_number,
- &mut last_uploaded_position,
- CHUNK_SIZE,
- )
- .await
- {
- Ok(part) => {
- uploaded_parts.push(part);
- }
- Err(e) => {
- println!(
- "Error uploading chunk (part {}): {}. Retrying in 1s...",
- part_number, e
- );
- sleep(Duration::from_secs(1)).await;
+ // --------------------------------------------
+ // Recording has stopped. We do repeated
+ // checks to ensure the file is stable (not
+ // still growing). Then we keep uploading
+ // leftover chunks until no more data arrives.
+ // --------------------------------------------
+ let max_stabilize_attempts = 8;
+ let mut attempts = 0;
+
+ // We'll loop to catch any last bits that appear
+ // after we do a leftover chunk upload.
+ loop {
+ // Wait for the file to stabilize
+ println!("Waiting for file to stabilize...");
+ let mut stable_count = 0;
+ let stable_required = 3; // e.g. 3 consecutive stable checks
+
+ // Keep track of last known size
+ let mut prev_size = tokio::fs::metadata(&file_path)
+ .await
+ .map(|md| md.len())
+ .unwrap_or(0);
+
+ while stable_count < stable_required {
+ sleep(Duration::from_secs(1)).await;
+ let size_now = match tokio::fs::metadata(&file_path).await {
+ Ok(md) => md.len(),
+ Err(_) => 0,
+ };
+ if size_now == prev_size {
+ stable_count += 1;
+ } else {
+ stable_count = 0;
+ prev_size = size_now;
}
}
- } else {
- // If recording is not done, keep waiting a bit
- if !recording_stopped {
- sleep(Duration::from_millis(500)).await;
- continue;
- }
-
- // --------------------------------------------
- // Recording has stopped. We do repeated
- // checks to ensure the file is stable (not
- // still growing). Then we keep uploading
- // leftover chunks until no more data arrives.
- // --------------------------------------------
- let max_stabilize_attempts = 8;
- let mut attempts = 0;
-
- // We'll loop to catch any last bits that appear
- // after we do a leftover chunk upload.
- loop {
- // Wait for the file to stabilize
- println!("Waiting for file to stabilize...");
- let mut stable_count = 0;
- let stable_required = 3; // e.g. 3 consecutive stable checks
-
- // Keep track of last known size
- let mut prev_size = tokio::fs::metadata(&file_path)
- .await
- .map(|md| md.len())
- .unwrap_or(0);
-
- while stable_count < stable_required {
- sleep(Duration::from_secs(1)).await;
- let size_now = match tokio::fs::metadata(&file_path).await {
- Ok(md) => md.len(),
- Err(_) => 0,
- };
- if size_now == prev_size {
- stable_count += 1;
- } else {
- stable_count = 0;
- prev_size = size_now;
- }
- }
- // At this point, the file has stayed the same size
- // for ~ stable_required seconds.
- let final_size = prev_size;
- let leftover_size = final_size.saturating_sub(last_uploaded_position);
+ // At this point, the file has stayed the same size
+ // for ~ stable_required seconds.
+ let final_size = prev_size;
+ let leftover_size = final_size.saturating_sub(last_uploaded_position);
- // Double-check moov if you want
- // let moov_found = found_moov_atom(&file_path).await;
+ // Double-check moov if you want
+ // let moov_found = found_moov_atom(&file_path).await;
- if leftover_size > 0 {
- if leftover_size >= MIN_PART_SIZE {
- // We still have at least 5MB leftover, treat it like a normal part:
- println!(
+ if leftover_size > 0 {
+ if leftover_size >= MIN_PART_SIZE {
+ // We still have at least 5MB leftover, treat it like a normal part:
+ println!(
"File stabilized, but leftover >= 5MB. Uploading leftover chunk of {} bytes.",
leftover_size
);
- match Self::upload_chunk(
- &app,
- &client,
- &file_path,
- &file_key,
- &upload_id,
- &mut part_number,
- &mut last_uploaded_position,
- leftover_size, // read leftover
- )
- .await
- {
- Ok(part) => {
- uploaded_parts.push(part);
- }
- Err(e) => {
- return Err(format!(
- "Failed uploading leftover chunk: {}",
- e
- ));
- }
+ match Self::upload_chunk(
+ &app,
+ &client,
+ &file_path,
+ &file_key,
+ &upload_id,
+ &mut part_number,
+ &mut last_uploaded_position,
+ leftover_size, // read leftover
+ )
+ .await
+ {
+ Ok(part) => {
+ uploaded_parts.push(part);
}
- } else {
- // Less than 5 MB leftover -> final chunk
- println!(
+ Err(e) => {
+ return Err(format!(
+ "Failed uploading leftover chunk: {}",
+ e
+ ));
+ }
+ }
+ } else {
+ // Less than 5 MB leftover -> final chunk
+ println!(
"Uploading final leftover chunk of {} bytes before completion",
leftover_size
);
- match Self::upload_chunk(
- &app,
- &client,
- &file_path,
- &file_key,
- &upload_id,
- &mut part_number,
- &mut last_uploaded_position,
- leftover_size,
- )
- .await
- {
- Ok(part) => {
- uploaded_parts.push(part);
- println!(
- "Successfully uploaded leftover chunk, part {}",
- part_number - 1
- );
- }
- Err(e) => {
- return Err(format!(
- "Failed to upload leftover chunk: {}",
- e
- ));
- }
+ match Self::upload_chunk(
+ &app,
+ &client,
+ &file_path,
+ &file_key,
+ &upload_id,
+ &mut part_number,
+ &mut last_uploaded_position,
+ leftover_size,
+ )
+ .await
+ {
+ Ok(part) => {
+ uploaded_parts.push(part);
+ println!(
+ "Successfully uploaded leftover chunk, part {}",
+ part_number - 1
+ );
+ }
+ Err(e) => {
+ return Err(format!(
+ "Failed to upload leftover chunk: {}",
+ e
+ ));
}
}
+ }
- // We just uploaded a leftover chunk, but let's see
- // if more data arrives. We'll try again. If no more
- // new data arrives, we can finalize.
- attempts += 1;
- if attempts > max_stabilize_attempts {
- println!(
+ // We just uploaded a leftover chunk, but let's see
+ // if more data arrives. We'll try again. If no more
+ // new data arrives, we can finalize.
+ attempts += 1;
+ if attempts > max_stabilize_attempts {
+ println!(
"Reached maximum leftover attempts, proceeding to finalize."
);
- break;
- }
- } else {
- // No leftover. We have stabilized with no new data.
- println!("File is stable with no leftover data, finalizing...");
break;
}
+ } else {
+ // No leftover. We have stabilized with no new data.
+ println!("File is stable with no leftover data, finalizing...");
+ break;
}
+ }
- match Self::upload_chunk(
- &app,
- &client,
- &file_path,
- &file_key,
- &upload_id,
- &mut 1,
- &mut 0,
- uploaded_parts[0].size as u64,
- )
- .await
- {
- Ok(part) => {
- uploaded_parts[0] = part;
- println!("Successfully re-uploaded first chunk",);
- }
- Err(e) => {
- return Err(format!("Failed to re-upload first chunk"));
- }
+ match Self::upload_chunk(
+ &app,
+ &client,
+ &file_path,
+ &file_key,
+ &upload_id,
+ &mut 1,
+ &mut 0,
+ uploaded_parts[0].size as u64,
+ )
+ .await
+ {
+ Ok(part) => {
+ uploaded_parts[0] = part;
+ println!("Successfully re-uploaded first chunk",);
+ }
+ Err(e) => {
+ return Err(format!("Failed to re-upload first chunk"));
}
-
- // All leftover chunks are now uploaded. We finalize.
- println!(
- "Completing multipart upload with {} parts",
- uploaded_parts.len()
- );
- Self::finalize_upload(
- &app,
- &file_path,
- &file_key,
- &upload_id,
- &uploaded_parts,
- &video_id,
- )
- .await?;
-
- upload_complete = true;
}
}
- Ok(())
- }),
+ // All leftover chunks are now uploaded. We finalize.
+ println!(
+ "Completing multipart upload with {} parts",
+ uploaded_parts.len()
+ );
+ Self::finalize_upload(
+ &app,
+ &file_path,
+ &file_key,
+ &upload_id,
+ &uploaded_parts,
+ &video_id,
+ )
+ .await?;
+
+ upload_complete = true;
+ }
}
+
+ Ok(())
}
/// Upload a single chunk from the file at `last_uploaded_position` for `chunk_size` bytes.
@@ -1503,6 +1510,7 @@ impl ProgressiveUploadTask {
}
};
+ dbg!(&complete_data);
if let Some(location) = complete_data.get("location") {
println!("Multipart upload complete. Final S3 location: {location}");
} else {
diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsx
index 71e0fbed1..f3908063f 100644
--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx
+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx
@@ -234,16 +234,17 @@ export default function () {
await commands.showWindow("Upgrade");
}
}}
- class={`text-[0.6rem] ${license.data?.type === "pro"
+ class={`text-[0.6rem] ${
+ license.data?.type === "pro"
? "bg-[--blue-400] text-gray-50 dark:text-gray-500"
: "bg-gray-200 cursor-pointer hover:bg-gray-300"
- } rounded-lg px-1.5 py-0.5`}
+ } rounded-lg px-1.5 py-0.5`}
>
{license.data?.type === "commercial"
? "Commercial"
: license.data?.type === "pro"
- ? "Pro"
- : "Personal"}
+ ? "Pro"
+ : "Personal"}
</span>
</Suspense>
</ErrorBoundary>
@@ -461,6 +462,11 @@ function TargetSelects(props: {
return value;
};
+ createEffect(() => {
+ screenValue();
+ windowValue();
+ });
+
const windowValue = () => {
const captureTarget = props.options?.captureTarget;
if (captureTarget?.variant !== "window") return null;
@@ -555,10 +561,11 @@ function TargetSelects(props: {
)}
>
<IconCapCrop
- class={`w-[1rem] h-[1rem] ${areaSelection.pending
+ class={`w-[1rem] h-[1rem] ${
+ areaSelection.pending
? "animate-gentle-bounce duration-1000 text-gray-500 mt-1"
: ""
- }`}
+ }`}
/>
</button>
)}
@@ -570,16 +577,17 @@ function TargetSelects(props: {
{isTargetCaptureArea()
? "Remove selection"
: areaSelection.pending
- ? "Selecting area..."
- : "Select area"}
+ ? "Selecting area..."
+ : "Select area"}
<Tooltip.Arrow class="fill-gray-500" />
</Tooltip.Content>
</Tooltip.Portal>
</Tooltip.Root>
<div
- class={`flex flex-row items-center rounded-[0.5rem] relative border h-8 transition-all duration-500 ${isTargetScreenOrArea() ? "ml-[2.4rem]" : ""
- }`}
+ class={`flex flex-row items-center rounded-[0.5rem] relative border h-8 transition-all duration-500 ${
+ isTargetScreenOrArea() ? "ml-[2.4rem]" : ""
+ }`}
style={{
"transition-timing-function":
"cubic-bezier(0.785, 0.135, 0.15, 0.86)",
@@ -640,7 +648,11 @@ function TargetSelects(props: {
placeholder="Window"
optionsEmptyText="No windows found"
selected={props.options?.captureTarget.variant === "window"}
- getName={(value) => platform() === "windows" ? value.name : `${value.owner_name} | ${value.name}`}
+ getName={(value) =>
+ platform() === "windows"
+ ? value.name
+ : `${value.owner_name} | ${value.name}`
+ }
/>
</div>
</div>
@@ -985,8 +997,8 @@ function TargetSelectInfoPill<T>(props: {
{!props.permissionGranted
? "Request Permission"
: props.value !== null
- ? "On"
- : "Off"}
+ ? "On"
+ : "Off"}
</InfoPill>
);
}
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx
index 130b1145e..4e62a3621 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx
@@ -1,4 +1,4 @@
-import { createQuery } from "@tanstack/solid-query";
+import { createMutation, createQuery } from "@tanstack/solid-query";
import { For, ParentProps, Show, Suspense, createSignal } from "solid-js";
import { convertFileSrc } from "@tauri-apps/api/core";
@@ -99,6 +99,12 @@ function RecordingItem(props: {
}) {
const [imageExists, setImageExists] = createSignal(true);
+ const reupload = createMutation(() => ({
+ mutationFn: () => {
+ return commands.reuploadInstantVideo(props.recording.id);
+ },
+ }));
+
return (
<li class="w-full flex flex-row justify-between items-center p-2 hover:bg-gray-100 rounded">
<div class="flex items-center">
@@ -118,6 +124,17 @@ function RecordingItem(props: {
<span>{props.recording.prettyName}</span>
</div>
<div class="flex items-center">
+ {import.meta.env.DEV &&
+ props.recording.meta.type === "instant" &&
+ props.recording.meta.sharing?.id && (
+ <button
+ onClick={() => {
+ reupload.mutate();
+ }}
+ >
+ Reupload
+ </button>
+ )}
<TooltipIconButton
tooltipText="Open project files"
onClick={() => props.onOpenFolder()}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index c0246b12c..0020907d2 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -169,6 +169,9 @@ async setFail(name: string, value: boolean) : Promise<void> {
},
async updateAuthPlan() : Promise<void> {
await TAURI_INVOKE("update_auth_plan");
+},
+async reuploadInstantVideo(videoId: string) : Promise<null> {
+ return await TAURI_INVOKE("reupload_instant_video", { videoId });
}
}