Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: New auto create shareable link setting
Richie McIlroyeaf957b693ba
diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rsindex 8a1b58e1a..e3cce3758 100644--- a/apps/desktop/src-tauri/src/general_settings.rs+++ b/apps/desktop/src-tauri/src/general_settings.rs@@ -11,6 +11,8 @@ pub struct GeneralSettingsStore {pub open_editor_after_recording: bool,#[serde(default)]pub hide_dock_icon: bool,+ #[serde(default)]+ pub auto_create_shareable_link: bool,}impl GeneralSettingsStore {diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 8381fe548..795815748 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -59,7 +59,7 @@ use tokio::{sync::{Mutex, RwLock},time::sleep,};-use upload::{upload_image, upload_individual_file, upload_video};+use upload::{get_s3_config, upload_image, upload_individual_file, upload_video, S3UploadMeta};use windows::CapWindow;#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]@@ -93,6 +93,8 @@ pub struct App {handle: AppHandle,#[serde(skip)]current_recording: Option<InProgressRecording>,+ #[serde(skip)]+ pre_created_video: Option<PreCreatedVideo>,}#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]@@ -110,6 +112,13 @@ enum UploadResult {UpgradeRequired,}+#[derive(Clone, Serialize, Deserialize, specta::Type)]+struct PreCreatedVideo {+ id: String,+ link: String,+ config: S3UploadMeta,+}+impl App {pub fn set_current_recording(&mut self, new_value: InProgressRecording) {let option = Some(new_value);@@ -295,6 +304,30 @@ async fn start_recording(app: AppHandle, state: MutableState<'_, App>) -> Result.join("recordings").join(format!("{id}.cap"));+ // Check if auto_create_shareable_link is true and user is upgraded+ let general_settings = GeneralSettingsStore::get(&app)?;+ let auto_create_shareable_link = general_settings+ .map(|settings| settings.auto_create_shareable_link)+ .unwrap_or(false);++ if auto_create_shareable_link {+ if let Ok(Some(auth)) = AuthStore::get(&app) {+ if auth.is_upgraded() {+ // Pre-create the video and get the shareable link+ let s3_config = get_s3_config(&app, false).await?;+ let link = web_api::make_url(format!("/s/{}", s3_config.id()));++ state.pre_created_video = Some(PreCreatedVideo {+ id: s3_config.id().to_string(),+ link: link.clone(),+ config: s3_config,+ });++ println!("Pre-created shareable link: {}", link);+ }+ }+ }+match recording::start(recording_dir,&state.start_recording_options,@@ -362,7 +395,8 @@ async fn resume_recording(state: MutableState<'_, App>) -> Result<(), String> {#[tauri::command]#[specta::specta]async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {- let Some(mut current_recording) = state.write().await.clear_current_recording() else {+ let mut state = state.write().await;+ let Some(mut current_recording) = state.clear_current_recording() else {return Err("Recording not in progress".to_string());};@@ -446,16 +480,74 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<AppSounds::StopRecording.play();if let Ok(Some(settings)) = GeneralSettingsStore::get(&app) {- if settings.open_editor_after_recording {- let recording_id = current_recording- .recording_dir- .file_name()- .unwrap_or_default()- .to_string_lossy()- .to_string()- .trim_end_matches(".cap")- .to_string();- open_editor(app.clone(), recording_id);+ if let Ok(Some(auth)) = AuthStore::get(&app) {+ if auth.is_upgraded() && settings.auto_create_shareable_link {+ if let Some(pre_created_video) = state.pre_created_video.take() {+ // Open the pre-created shareable link+ open_external_link(app.clone(), pre_created_video.link.clone()).ok();++ // Start the upload process in the background with retry mechanism+ let app_clone = app.clone();+ let recording_id = current_recording+ .recording_dir+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .to_string()+ .trim_end_matches(".cap")+ .to_string();++ tauri::async_runtime::spawn(async move {+ let max_retries = 3;+ let mut retry_count = 0;++ while retry_count < max_retries {+ match upload_rendered_video(+ app_clone.clone(),+ recording_id.clone(),+ ProjectConfiguration::default(),+ Some(pre_created_video.clone()),+ )+ .await+ {+ Ok(_) => {+ println!("Video uploaded successfully");+ break;+ }+ Err(e) => {+ retry_count += 1;+ println!(+ "Error during auto-upload (attempt {}/{}): {}",+ retry_count, max_retries, e+ );++ if retry_count < max_retries {+ // Wait for a short time before retrying+ tokio::time::sleep(std::time::Duration::from_secs(5)).await;+ } else {+ println!("Max retries reached. Upload failed.");+ // Optionally, you can notify the user about the failure+ notifications::send_notification(+ &app_clone,+ notifications::NotificationType::UploadFailed,+ );+ }+ }+ }+ }+ });+ }+ } else if settings.open_editor_after_recording {+ let recording_id = current_recording+ .recording_dir+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .to_string()+ .trim_end_matches(".cap")+ .to_string();+ open_editor(app.clone(), recording_id);+ }}}@@ -1499,6 +1591,7 @@ async fn upload_rendered_video(app: AppHandle,video_id: String,project: ProjectConfiguration,+ pre_created_video: Option<PreCreatedVideo>,) -> Result<UploadResult, String> {let Ok(Some(mut auth)) = AuthStore::get(&app) else {println!("not authenticated!");@@ -1532,6 +1625,30 @@ async fn upload_rendered_video(let share_link = if let Some(sharing) = meta.sharing {sharing.link+ } else if let Some(pre_created) = pre_created_video {+ // Use the pre-created video information+ let output_path = match get_rendered_video_impl(editor_instance.clone(), project).await {+ Ok(path) => path,+ Err(e) => return Err(format!("Failed to get rendered video: {}", e)),+ };++ upload_video(+ &app,+ video_id.clone(),+ output_path,+ false,+ Some(pre_created.config),+ )+ .await?;++ meta.sharing = Some(SharingMeta {+ link: pre_created.link.clone(),+ id: pre_created.id.clone(),+ });+ meta.save_for_project();+ RecordingMetaChanged { id: video_id }.emit(&app).ok();++ pre_created.link} else {let output_path = match get_rendered_video_impl(editor_instance.clone(), project).await {Ok(path) => {@@ -1544,7 +1661,7 @@ async fn upload_rendered_video(}};- let uploaded_video = upload_video(&app, video_id.clone(), output_path, false).await?;+ let uploaded_video = upload_video(&app, video_id.clone(), output_path, false, None).await?;let general_settings = GeneralSettingsStore::get(&app)?;if let Some(settings) = general_settings {@@ -2253,6 +2370,7 @@ pub async fn run() {audio_input_name: None,},current_recording: None,+ pre_created_video: None,})));app.manage(FakeWindowBounds(Arc::new(RwLock::new(HashMap::new()))));diff --git a/apps/desktop/src-tauri/src/notifications.rs b/apps/desktop/src-tauri/src/notifications.rsindex 58554f482..e51ab86de 100644--- a/apps/desktop/src-tauri/src/notifications.rs+++ b/apps/desktop/src-tauri/src/notifications.rs@@ -4,6 +4,7 @@ pub enum NotificationType {VideoSaved,VideoCopiedToClipboard,ShareableLinkCopied,+ UploadFailed,}impl NotificationType {@@ -20,6 +21,26 @@ impl NotificationType {"Link Copied","Shareable link has been copied to the clipboard.",),+ NotificationType::UploadFailed => (+ "Upload Failed",+ "Failed to upload your video after multiple attempts. Please try again later.",+ ),+ }+ }++ pub fn message(&self) -> &'static str {+ match self {+ NotificationType::UploadFailed => {+ "Failed to upload your video after multiple attempts. Please try again later."+ }+ _ => "",+ }+ }++ pub fn title(&self) -> &'static str {+ match self {+ NotificationType::UploadFailed => "Upload Failed",+ _ => "",}}}diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex e47f42080..15fdc208e 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -12,7 +12,10 @@ use crate::{web_api::{self, ManagerExt},};-#[derive(serde::Deserialize, Clone)]+use serde::{Deserialize, Serialize};+use specta::Type;++#[derive(Deserialize, Serialize, Clone, Type)]pub struct S3UploadMeta {id: String,user_id: String,@@ -20,6 +23,24 @@ pub struct S3UploadMeta {aws_bucket: String,}+impl S3UploadMeta {+ pub fn id(&self) -> &str {+ &self.id+ }++ pub fn user_id(&self) -> &str {+ &self.user_id+ }++ pub fn aws_region(&self) -> &str {+ &self.aws_region+ }++ pub fn aws_bucket(&self) -> &str {+ &self.aws_bucket+ }+}+#[derive(serde::Serialize)]#[serde(rename_all = "camelCase")]struct S3UploadBody {@@ -80,6 +101,7 @@ pub async fn upload_video(video_id: String,file_path: PathBuf,is_individual: bool,+ existing_config: Option<S3UploadMeta>,) -> Result<UploadedVideo, String> {println!("Uploading video {video_id}...");@@ -90,24 +112,29 @@ pub async fn upload_video(.to_string();let client = reqwest::Client::new();- let s3_config = get_s3_config(&app, false).await?;+ let s3_config = match existing_config {+ Some(config) => config,+ None => get_s3_config(app, false).await?,+ };let file_key = if is_individual {format!("{}/{}/individual/{}",- s3_config.user_id, s3_config.id, file_name+ s3_config.user_id(),+ s3_config.id(),+ file_name)} else {- format!("{}/{}/{}", s3_config.user_id, s3_config.id, file_name)+ format!("{}/{}/{}", s3_config.user_id(), s3_config.id(), file_name)};let body = build_video_upload_body(&file_path,S3UploadBody {- user_id: s3_config.user_id.clone(),+ user_id: s3_config.user_id().to_string(),file_key: file_key.clone(),- aws_bucket: s3_config.aws_bucket.clone(),- aws_region: s3_config.aws_region.clone(),+ aws_bucket: s3_config.aws_bucket().to_string(),+ aws_region: s3_config.aws_region().to_string(),},)?;@@ -336,7 +363,7 @@ pub async fn upload_audio(app: &AppHandle, file_path: PathBuf) -> Result<Uploade))}-async fn get_s3_config(app: &AppHandle, is_screenshot: bool) -> Result<S3UploadMeta, String> {+pub async fn get_s3_config(app: &AppHandle, is_screenshot: bool) -> Result<S3UploadMeta, String> {let origin = "http://tauri.localhost";let config_url = web_api::make_url(if is_screenshot {format!(diff --git a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx b/apps/desktop/src/routes/(window-chrome)/settings/general.tsxindex 2a08867f9..1d2612af8 100644--- a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx+++ b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx@@ -22,6 +22,12 @@ const settingsList = [description:"The dock icon will be hidden when there are no windows available to close.",},+ {+ key: "auto_create_shareable_link",+ label: "Cap Pro: Automatically create shareable link after recording",+ description:+ "When enabled, a shareable link will be created automatically after stopping the recording. You'll be redirected to the URL while the upload continues in the background.",+ },];export default function GeneralSettings() {@@ -57,61 +63,63 @@ function Inner(props: { store: GeneralSettingsStore | null }) {};return (- <div class="flex flex-col w-full h-full divide-y divide-gray-200 pb-12">- <div class="flex-1 p-4 space-y-2 divide-y divide-gray-200">- <For each={settingsList}>- {(setting) => (- <div class="space-y-2 py-3">- <div class="flex items-center justify-between">- <p>{setting.label}</p>- <button- type="button"- role="switch"- aria-checked={- settings[setting.key as keyof GeneralSettingsStore]- }- data-state={- settings[setting.key as keyof GeneralSettingsStore]- ? "checked"- : "unchecked"- }- value={- settings[setting.key as keyof GeneralSettingsStore]- ? "on"- : "off"- }- class={`peer inline-flex h-4 w-8 shrink-0 cursor-pointer items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 ${- settings[setting.key as keyof GeneralSettingsStore]- ? "bg-blue-400 border-blue-400"- : "bg-gray-300 border-gray-300"- }`}- onClick={() =>- handleChange(- setting.key,- !settings[setting.key as keyof GeneralSettingsStore]- )- }- >- <span+ <div class="flex flex-col w-full h-full">+ <div class="flex-1 overflow-y-auto">+ <div class="p-4 space-y-2 divide-y divide-gray-200">+ <For each={settingsList}>+ {(setting) => (+ <div class="space-y-2 py-3">+ <div class="flex items-center justify-between">+ <p>{setting.label}</p>+ <button+ type="button"+ role="switch"+ aria-checked={+ settings[setting.key as keyof GeneralSettingsStore]+ }data-state={settings[setting.key as keyof GeneralSettingsStore]? "checked": "unchecked"}- class={`pointer-events-none block h-4 w-4 rounded-full bg-gray-50 shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0 border-2 ${+ value={+ settings[setting.key as keyof GeneralSettingsStore]+ ? "on"+ : "off"+ }+ class={`peer inline-flex h-4 w-8 shrink-0 cursor-pointer items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 ${settings[setting.key as keyof GeneralSettingsStore]- ? "border-blue-400"- : "border-gray-300"+ ? "bg-blue-400 border-blue-400"+ : "bg-gray-300 border-gray-300"}`}- />- </button>+ onClick={() =>+ handleChange(+ setting.key,+ !settings[setting.key as keyof GeneralSettingsStore]+ )+ }+ >+ <span+ data-state={+ settings[setting.key as keyof GeneralSettingsStore]+ ? "checked"+ : "unchecked"+ }+ class={`pointer-events-none block h-4 w-4 rounded-full bg-gray-50 shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0 border-2 ${+ settings[setting.key as keyof GeneralSettingsStore]+ ? "border-blue-400"+ : "border-gray-300"+ }`}+ />+ </button>+ </div>+ {setting.description && (+ <p class="text-xs text-gray-400">{setting.description}</p>+ )}</div>- {setting.description && (- <p class="text-xs text-gray-400">{setting.description}</p>- )}- </div>- )}- </For>+ )}+ </For>+ </div></div></div>);diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex d8a8f2d9d..49b0fab32 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -197,9 +197,9 @@ async doPermissionsCheck(initialCheck: boolean) : Promise<OSPermissionsCheck> {async requestPermission(permission: OSPermission) : Promise<void> {await TAURI_INVOKE("request_permission", { permission });},-async uploadRenderedVideo(videoId: string, project: ProjectConfiguration) : Promise<Result<UploadResult, string>> {+async uploadRenderedVideo(videoId: string, project: ProjectConfiguration, preCreatedVideo: PreCreatedVideo | null) : Promise<Result<UploadResult, string>> {try {- return { status: "ok", data: await TAURI_INVOKE("upload_rendered_video", { videoId, project }) };+ return { status: "ok", data: await TAURI_INVOKE("upload_rendered_video", { videoId, project, preCreatedVideo }) };} catch (e) {if(e instanceof Error) throw e;else return { status: "error", error: e as any };@@ -373,7 +373,7 @@ export type CursorConfiguration = { hideWhenIdle: boolean; size: number; type: Cexport type CursorType = "pointer" | "circle"export type Display = { path: string }export type EditorStateChanged = { playhead_position: number }-export type GeneralSettingsStore = { upload_individual_files: boolean; open_editor_after_recording: boolean; hide_dock_icon?: boolean }+export type GeneralSettingsStore = { upload_individual_files: boolean; open_editor_after_recording: boolean; hide_dock_icon?: boolean; auto_create_shareable_link?: boolean }export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean; shift: boolean }export type HotkeyAction = "startRecording" | "stopRecording" | "restartRecording" | "takeScreenshot"export type HotkeysConfiguration = { show: boolean }@@ -386,6 +386,7 @@ export type OSPermission = "screenRecording" | "camera" | "microphone" | "accessexport type OSPermissionStatus = "notNeeded" | "empty" | "granted" | "denied"export type OSPermissionsCheck = { screenRecording: OSPermissionStatus; microphone: OSPermissionStatus; camera: OSPermissionStatus; accessibility: OSPermissionStatus }export type Plan = { upgraded: boolean; last_checked: number }+export type PreCreatedVideo = { id: string; link: string; config: S3UploadMeta }export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: CameraConfiguration; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null }export type ProjectRecordings = { display: Video; camera: Video | null; audio: Audio | null }export type RecordingMeta = { pretty_name: string; sharing?: SharingMeta | null; display: Display; camera?: CameraMeta | null; audio?: AudioMeta | null; segments?: RecordingSegment[] }@@ -402,6 +403,7 @@ export type RequestOpenSettings = { page: string }export type RequestRestartRecording = nullexport type RequestStartRecording = nullexport type RequestStopRecording = null+export type S3UploadMeta = { id: string; user_id: string; aws_region: string; aws_bucket: string }export type ScreenCaptureTarget = ({ variant: "window" } & CaptureWindow) | { variant: "screen" }export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordings; path: string; prettyName: string }export type SharingMeta = { id: string; link: string }diff --git a/apps/embed/app/view/[videoId]/_components/ShareVideo.tsx b/apps/embed/app/view/[videoId]/_components/ShareVideo.tsxindex e7a1ba088..56c46e93e 100644--- a/apps/embed/app/view/[videoId]/_components/ShareVideo.tsx+++ b/apps/embed/app/view/[videoId]/_components/ShareVideo.tsx@@ -289,7 +289,15 @@ export const ShareVideo = ({if (data.transcriptionStatus === "COMPLETE") {fetchSubtitles();} else {+ const startTime = Date.now();+ const maxDuration = 2 * 60 * 1000; // 2 minutes in milliseconds+const intervalId = setInterval(() => {+ if (Date.now() - startTime > maxDuration) {+ clearInterval(intervalId);+ return;+ }+fetch(`/api/video/transcribe/status?videoId=${data.id}`).then((response) => response.json()).then(({ transcriptionStatus }) => {diff --git a/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsxindex e0d24a871..f078d6440 100644--- a/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx+++ b/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx@@ -1,4 +1,10 @@-import { memo, forwardRef, useRef, useImperativeHandle } from "react";+import {+ memo,+ forwardRef,+ useRef,+ useImperativeHandle,+ useEffect,+} from "react";interface MP4VideoPlayerProps {videoSrc: string;@@ -10,6 +16,31 @@ export const MP4VideoPlayer = memo(useImperativeHandle(ref, () => videoRef.current as HTMLVideoElement);+ useEffect(() => {+ const video = videoRef.current;+ if (!video) return;++ const startTime = Date.now();+ const maxDuration = 2 * 60 * 1000;++ const checkAndReload = () => {+ if (video.readyState === 0) {+ // HAVE_NOTHING+ video.load();+ }++ if (Date.now() - startTime < maxDuration) {+ setTimeout(checkAndReload, 3000);+ }+ };++ checkAndReload();++ return () => {+ clearTimeout(checkAndReload as unknown as number);+ };+ }, [videoSrc]);+return (<videoid="video-player"diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsxindex 3ec9adf7d..0f3e9c07f 100644--- a/apps/web/app/s/[videoId]/page.tsx+++ b/apps/web/app/s/[videoId]/page.tsx@@ -96,21 +96,6 @@ export default async function ShareVideoPage(props: Props) {);}- if (- video.jobStatus !== "COMPLETE" &&- video.skipProcessing === false &&- video.source.type === "MediaConvert"- ) {- fetch(- `${process.env.NEXT_PUBLIC_URL}/api/upload/mux/status?videoId=${videoId}&userId=${video.ownerId}`,- {- method: "GET",- credentials: "include",- cache: "no-store",- }- );- }-if (video.public === false && userId !== video.ownerId) {return <p>This video is private</p>;}