Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: 0.3.0-beta.2 release

Richie McIlroyf8b180e76f58
diff --git a/Cargo.lock b/Cargo.lock
index b8be39bc0..f09b71bd3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1425,7 +1425,7 @@ dependencies = [
[[package]]
name = "desktop"
-version = "0.3.0-alpha.27"
+version = "0.3.0-beta.2"
dependencies = [
"anyhow",
"axum",
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 90420d846..9a85b4a69 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "desktop"
-version = "0.3.0-alpha.27"
+version = "0.3.0-beta.2"
description = "Beautiful, shareable screen recordings."
authors = ["you"]
edition = "2021"
diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json
index b3541c013..c478ad301 100644
--- a/apps/desktop/src-tauri/capabilities/default.json
+++ b/apps/desktop/src-tauri/capabilities/default.json
@@ -21,6 +21,7 @@
"core:app:allow-version",
"shell:default",
"fs:default",
+ "fs:read-files",
"dialog:default",
"store:default",
"process:default",
diff --git a/apps/desktop/src-tauri/src/auth.rs b/apps/desktop/src-tauri/src/auth.rs
index fe67bd69a..6afdf16af 100644
--- a/apps/desktop/src-tauri/src/auth.rs
+++ b/apps/desktop/src-tauri/src/auth.rs
@@ -7,6 +7,13 @@ use tauri_plugin_store::{with_store, StoreCollection};
pub struct AuthStore {
pub token: String,
pub expires: i32,
+ pub plan: Plan,
+}
+
+#[derive(Serialize, Deserialize, Type)]
+pub struct Plan {
+ pub upgraded: bool,
+ pub last_checked: i32,
}
impl AuthStore {
@@ -15,11 +22,78 @@ impl AuthStore {
.try_state::<StoreCollection<Wry>>()
.ok_or("Store not found")?;
with_store(app.clone(), stores, "store", |store| {
- let Some(store) = store.get("auth").cloned() else {
+ let Some(store_value) = store.get("auth").cloned() else {
return Ok(None);
};
- Ok(serde_json::from_value(store)?)
+ // Try to deserialize into the new structure
+ match serde_json::from_value::<Self>(store_value.clone()) {
+ Ok(auth_store) => Ok(Some(auth_store)),
+ Err(_) => {
+ // If deserialization fails, it might be due to the old structure
+ // Try to deserialize into a temporary struct without the plan field
+ #[derive(Deserialize)]
+ struct OldAuthStore {
+ token: String,
+ expires: i32,
+ }
+
+ let old_auth: OldAuthStore = serde_json::from_value(store_value)?;
+
+ // Create a new AuthStore with default Plan values
+ Ok(Some(Self {
+ token: old_auth.token,
+ expires: old_auth.expires,
+ plan: Plan {
+ upgraded: false,
+ last_checked: 0,
+ },
+ }))
+ }
+ }
+ })
+ .map_err(|e| e.to_string())
+ }
+
+ pub async fn fetch_and_update_plan(app: &AppHandle) -> Result<(), String> {
+ let auth = Self::get(app)?;
+ let Some(mut auth) = auth else {
+ return Err("User not authenticated".to_string());
+ };
+
+ let client = reqwest::Client::new();
+ let server_url_base: &'static str = dotenvy_macro::dotenv!("NEXT_PUBLIC_URL");
+ let url = format!("{}/api/desktop/plan", server_url_base);
+
+ let response = client
+ .get(&url)
+ .header("Authorization", format!("Bearer {}", auth.token))
+ .send()
+ .await
+ .map_err(|e| e.to_string())?;
+
+ if !response.status().is_success() {
+ let error_msg = format!("Failed to fetch plan: {}", response.status());
+ return Err(error_msg);
+ }
+
+ let plan_response: serde_json::Value = response.json().await.map_err(|e| e.to_string())?;
+
+ auth.plan.upgraded = plan_response["upgraded"].as_bool().unwrap_or(false);
+ auth.plan.last_checked = chrono::Utc::now().timestamp() as i32;
+
+ let _ = Self::set(app, Some(auth))?;
+
+ Ok(())
+ }
+
+ pub fn set(app: &AppHandle, value: Option<Self>) -> Result<(), String> {
+ let stores = app
+ .try_state::<StoreCollection<Wry>>()
+ .ok_or("Store not found")?;
+ with_store(app.clone(), stores, "store", |store| {
+ let _ = store.insert("auth".to_string(), serde_json::to_value(value)?);
+ store.save()
})
.map_err(|e| e.to_string())
}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 6d9ff5673..f67673441 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -50,6 +50,7 @@ use std::{
use tauri::{AppHandle, Manager, State, WebviewUrl, WebviewWindow, WindowEvent};
use tauri_nspanel::{cocoa::appkit::NSMainMenuWindowLevel, ManagerExt};
use tauri_plugin_decorum::WebviewWindowExt;
+use tauri_plugin_shell::ShellExt;
use tauri_specta::Event;
use tokio::io::AsyncWriteExt;
use tokio::sync::mpsc;
@@ -95,6 +96,14 @@ pub enum VideoType {
Output,
}
+#[derive(Serialize, Deserialize, specta::Type)]
+enum UploadResult {
+ Success(String),
+ NotAuthenticated,
+ PlanCheckFailed,
+ UpgradeRequired,
+}
+
const WINDOW_CAPTURE_OCCLUDER_LABEL: &str = "window-capture-occluder";
const IN_PROGRESS_RECORDINGS_LABEL: &str = "in-progress-recordings";
@@ -221,6 +230,11 @@ pub struct RequestNewScreenshot;
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RequestStopRecording;
+#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
+pub struct RequestOpenSettings {
+ page: String,
+}
+
type MutableState<'a, T> = State<'a, Arc<RwLock<T>>>;
#[tauri::command]
@@ -345,7 +359,7 @@ async fn resume_recording(state: MutableState<'_, App>) -> Result<(), String> {
fn create_in_progress_recording_window(app: &AppHandle) {
let monitor = app.primary_monitor().unwrap().unwrap();
- let width = 120.0;
+ let width = 160.0;
let height = 40.0;
WebviewWindow::builder(
@@ -377,7 +391,6 @@ fn create_in_progress_recording_window(app: &AppHandle) {
#[tauri::command]
#[specta::specta]
async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
- // dropping the mutex lock is important to ensure that the getCurrentRecording query isn't blocked
let Some(mut current_recording) = state.write().await.clear_current_recording() else {
return Err("Recording not in progress".to_string());
};
@@ -390,6 +403,7 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<
);
current_recording.stop();
+ println!("Recording stopped");
let window = app
.get_webview_window(IN_PROGRESS_RECORDINGS_LABEL)
@@ -401,7 +415,6 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<
}
std::fs::create_dir_all(current_recording.recording_dir.join("screenshots")).ok();
- dbg!(&current_recording.display.output_path);
FFmpeg::new()
.command
@@ -447,14 +460,11 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<
let config = {
let mut segments = vec![];
-
let mut passed_duration = 0.0;
for i in (0..current_recording.segments.len()).step_by(2) {
let start = passed_duration;
-
passed_duration += current_recording.segments[i + 1] - current_recording.segments[i];
-
segments.push(TimelineSegment {
start,
end: passed_duration,
@@ -578,34 +588,36 @@ async fn copy_screenshot_to_clipboard(app: AppHandle, path: PathBuf) -> Result<(
#[tauri::command]
#[specta::specta]
async fn open_file_path(app: AppHandle, path: PathBuf) -> Result<(), String> {
- #[cfg(target_os = "macos")]
+ let path_str = path.to_str().ok_or("Invalid path")?;
+
+ #[cfg(target_os = "windows")]
{
- use std::process::Command;
- Command::new("open")
- .arg(&path)
- .output()
- .map_err(|e| format!("Failed to open file: {}", e))?;
+ Command::new("explorer")
+ .args(["/select,", path_str])
+ .spawn()
+ .map_err(|e| format!("Failed to open folder: {}", e))?;
}
- #[cfg(target_os = "windows")]
+ #[cfg(target_os = "macos")]
{
- use std::os::windows::process::CommandExt;
- use std::process::Command;
- Command::new("cmd")
- .args(&["/C", "start", ""])
- .arg(&path)
- .creation_flags(0x08000000) // CREATE_NO_WINDOW
- .output()
- .map_err(|e| format!("Failed to open file: {}", e))?;
+ Command::new("open")
+ .arg("-R")
+ .arg(path_str)
+ .spawn()
+ .map_err(|e| format!("Failed to open folder: {}", e))?;
}
#[cfg(target_os = "linux")]
{
- use std::process::Command;
Command::new("xdg-open")
- .arg(&path)
- .output()
- .map_err(|e| format!("Failed to open file: {}", e))?;
+ .arg(
+ path.parent()
+ .ok_or("Invalid path")?
+ .to_str()
+ .ok_or("Invalid path")?,
+ )
+ .spawn()
+ .map_err(|e| format!("Failed to open folder: {}", e))?;
}
Ok(())
@@ -1446,6 +1458,32 @@ async fn open_feedback_window(app: AppHandle) {
window.set_traffic_lights_inset(14.0, 22.0).unwrap();
}
+#[tauri::command]
+#[specta::specta]
+async fn open_upgrade_window(app: AppHandle) {
+ if let Some(window) = app.get_webview_window("upgrade") {
+ window.set_focus().ok();
+ return;
+ }
+
+ let window = WebviewWindow::builder(&app, "upgrade", tauri::WebviewUrl::App("/upgrade".into()))
+ .title("Cap Upgrade")
+ .inner_size(800.0, 850.0)
+ .resizable(false)
+ .maximized(false)
+ .shadow(true)
+ .accept_first_mouse(true)
+ .transparent(true)
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay)
+ .build()
+ .unwrap();
+
+ window.create_overlay_titlebar().unwrap();
+ #[cfg(target_os = "macos")]
+ window.set_traffic_lights_inset(14.0, 22.0).unwrap();
+}
+
#[tauri::command]
#[specta::specta]
async fn open_changelog_window(app: AppHandle) {
@@ -1473,20 +1511,23 @@ async fn open_changelog_window(app: AppHandle) {
#[tauri::command]
#[specta::specta]
-async fn open_settings_window(app: AppHandle) {
- let window =
- WebviewWindow::builder(&app, "settings", tauri::WebviewUrl::App("/settings".into()))
- .title("Cap Settings")
- .inner_size(600.0, 450.0)
- .resizable(true)
- .maximized(false)
- .shadow(true)
- .accept_first_mouse(true)
- .transparent(true)
- .hidden_title(true)
- .title_bar_style(tauri::TitleBarStyle::Overlay)
- .build()
- .unwrap();
+async fn open_settings_window(app: AppHandle, page: String) {
+ let window = WebviewWindow::builder(
+ &app,
+ "settings",
+ tauri::WebviewUrl::App(format!("/settings?page={page}").into()),
+ )
+ .title("Cap Settings")
+ .inner_size(600.0, 450.0)
+ .resizable(true)
+ .maximized(false)
+ .shadow(true)
+ .accept_first_mouse(true)
+ .transparent(true)
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay)
+ .build()
+ .unwrap();
window.create_overlay_titlebar().unwrap();
#[cfg(target_os = "macos")]
@@ -1499,12 +1540,33 @@ async fn upload_rendered_video(
app: AppHandle,
video_id: String,
project: ProjectConfiguration,
-) -> Result<(), String> {
- let Ok(Some(auth)) = AuthStore::get(&app) else {
+) -> Result<UploadResult, String> {
+ let Ok(Some(mut auth)) = AuthStore::get(&app) else {
println!("not authenticated!");
- return Err("Not authenticated".to_string());
+ return Ok(UploadResult::NotAuthenticated);
};
+ // Check if user has an upgraded plan
+ if !auth.plan.upgraded {
+ // Fetch and update plan information
+ if let Err(e) = AuthStore::fetch_and_update_plan(&app).await {
+ println!("Failed to update plan information: {}", e);
+ return Ok(UploadResult::PlanCheckFailed);
+ }
+
+ // Refresh auth information after update
+ auth = AuthStore::get(&app).unwrap().unwrap();
+
+ // Re-check upgraded status after refresh
+ if !auth.plan.upgraded {
+ // Open upgrade window instead of returning an error
+ open_upgrade_window(app).await;
+ return Ok(UploadResult::UpgradeRequired);
+ }
+ }
+
+ println!("Uploading rendered video: {:?}", video_id);
+
let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;
let mut meta = editor_instance.meta();
@@ -1560,17 +1622,56 @@ async fn upload_rendered_video(
}
}
- Ok(())
+ Ok(UploadResult::Success(share_link))
}
#[tauri::command]
#[specta::specta]
-async fn upload_screenshot(app: AppHandle, screenshot_path: PathBuf) -> Result<String, String> {
- let Ok(Some(auth)) = AuthStore::get(&app) else {
+async fn upload_screenshot(
+ app: AppHandle,
+ screenshot_path: PathBuf,
+) -> Result<UploadResult, String> {
+ let Ok(Some(mut auth)) = AuthStore::get(&app) else {
println!("not authenticated!");
- return Err("Not authenticated".to_string());
+ return Ok(UploadResult::NotAuthenticated);
};
+ if !auth.plan.upgraded {
+ println!("User plan not upgraded. Fetching and updating plan information.");
+ // Fetch and update plan information
+ if let Err(e) = AuthStore::fetch_and_update_plan(&app).await {
+ println!("Failed to update plan information: {}", e);
+ return Ok(UploadResult::PlanCheckFailed);
+ }
+
+ println!("Plan information updated. Refreshing auth information.");
+ // Refresh auth information after update
+ auth = match AuthStore::get(&app) {
+ Ok(Some(updated_auth)) => {
+ println!("Auth information refreshed successfully.");
+ updated_auth
+ }
+ Ok(None) => {
+ println!("Error: No auth information found after refresh.");
+ return Err("Authentication information not found".to_string());
+ }
+ Err(e) => {
+ println!("Error refreshing auth information: {}", e);
+ return Err("Failed to refresh authentication information".to_string());
+ }
+ };
+
+ // Re-check upgraded status after refresh
+ if !auth.plan.upgraded {
+ println!("User plan still not upgraded after refresh.");
+ open_upgrade_window(app).await;
+ return Ok(UploadResult::UpgradeRequired);
+ }
+ println!("User plan is now upgraded.");
+ } else {
+ println!("User plan is already upgraded.");
+ }
+
println!("Uploading screenshot: {:?}", screenshot_path);
let screenshot_dir = screenshot_path.parent().unwrap().to_path_buf();
@@ -1629,7 +1730,7 @@ async fn upload_screenshot(app: AppHandle, screenshot_path: PathBuf) -> Result<S
}
}
- Ok(share_link)
+ Ok(UploadResult::Success(share_link))
}
#[tauri::command]
@@ -1839,6 +1940,81 @@ fn get_recording_meta(app: AppHandle, id: String, file_type: String) -> Recordin
RecordingMeta::load_for_project(&meta_path).unwrap()
}
+#[tauri::command]
+#[specta::specta]
+fn list_recordings(app: AppHandle) -> Result<Vec<(String, PathBuf, RecordingMeta)>, String> {
+ let recordings_dir = recordings_path(&app);
+
+ let result = std::fs::read_dir(&recordings_dir)
+ .map_err(|e| format!("Failed to read recordings directory: {}", e))?
+ .filter_map(|entry| {
+ let entry = entry.ok()?;
+ let path = entry.path();
+ if path.is_dir() && path.extension().and_then(|s| s.to_str()) == Some("cap") {
+ let id = path.file_stem()?.to_str()?.to_string();
+ let meta = get_recording_meta(app.clone(), id.clone(), "recording".to_string());
+ Some((id, path, meta))
+ } else {
+ None
+ }
+ })
+ .collect::<Vec<_>>();
+
+ Ok(result)
+}
+
+#[tauri::command]
+#[specta::specta]
+fn list_screenshots(app: AppHandle) -> Result<Vec<(String, PathBuf, RecordingMeta)>, String> {
+ let screenshots_dir = screenshots_path(&app);
+
+ let result = std::fs::read_dir(&screenshots_dir)
+ .map_err(|e| format!("Failed to read screenshots directory: {}", e))?
+ .filter_map(|entry| {
+ let entry = entry.ok()?;
+ let path = entry.path();
+ if path.is_dir() && path.extension().and_then(|s| s.to_str()) == Some("cap") {
+ let id = path.file_stem()?.to_str()?.to_string();
+ let meta = get_recording_meta(app.clone(), id.clone(), "screenshot".to_string());
+
+ // Find the nearest .png file inside the .cap folder
+ let png_path = std::fs::read_dir(&path)
+ .ok()?
+ .filter_map(|e| e.ok())
+ .find(|e| e.path().extension().and_then(|s| s.to_str()) == Some("png"))
+ .map(|e| e.path())?;
+
+ Some((id, png_path, meta))
+ } else {
+ None
+ }
+ })
+ .collect::<Vec<_>>();
+
+ Ok(result)
+}
+
+#[tauri::command]
+#[specta::specta]
+async fn check_upgraded_and_update(app: AppHandle) -> Result<bool, String> {
+ if let Err(e) = AuthStore::fetch_and_update_plan(&app).await {
+ return Err(format!("Failed to update plan information: {}", e));
+ }
+
+ let auth = AuthStore::get(&app).map_err(|e| e.to_string())?;
+
+ Ok(auth.map_or(false, |a| a.plan.upgraded))
+}
+
+#[tauri::command]
+#[specta::specta]
+fn open_external_link(app: tauri::AppHandle, url: String) -> Result<(), String> {
+ app.shell()
+ .open(&url, None)
+ .map_err(|e| format!("Failed to open URL: {}", e))?;
+ Ok(())
+}
+
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let specta_builder = tauri_specta::Builder::new()
@@ -1884,7 +2060,12 @@ pub fn run() {
open_feedback_window,
open_settings_window,
open_changelog_window,
+ open_upgrade_window,
save_file_dialog,
+ list_recordings,
+ list_screenshots,
+ check_upgraded_and_update,
+ open_external_link,
hotkeys::set_hotkey
])
.events(tauri_specta::collect_events![
@@ -1902,6 +2083,7 @@ pub fn run() {
RequestRestartRecording,
RequestStopRecording,
RequestNewScreenshot,
+ RequestOpenSettings,
])
.ty::<ProjectConfiguration>()
.ty::<AuthStore>()
@@ -1991,7 +2173,6 @@ pub fn run() {
let app_handle_clone = app_handle.clone();
RequestRestartRecording::listen_any(app, move |_| {
let app_handle = app_handle_clone.clone();
- println!("RequestRestartRecording received");
tauri::async_runtime::spawn(async move {
let state = app_handle.state::<Arc<RwLock<App>>>();
@@ -2003,13 +2184,10 @@ pub fn run() {
.emit(&app_handle)
.ok();
- println!("Stopping and discarding current recording");
recording.stop_and_discard();
}
}
- // Start a new recording immediately
- println!("Starting new recording");
if let Err(e) = start_recording(app_handle.clone(), state).await {
eprintln!("Failed to start new recording: {}", e);
} else {
@@ -2028,6 +2206,14 @@ pub fn run() {
});
});
+ let app_handle_clone = app_handle.clone();
+ RequestOpenSettings::listen_any(app, move |e| {
+ let app_handle = app_handle_clone.clone();
+ tauri::async_runtime::spawn(async move {
+ open_settings_window(app_handle, e.payload.page).await;
+ });
+ });
+
Ok(())
})
.on_window_event(|window, event| {
diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rs
index afd8ad175..3cd12da56 100644
--- a/apps/desktop/src-tauri/src/tray.rs
+++ b/apps/desktop/src-tauri/src/tray.rs
@@ -1,15 +1,13 @@
use crate::{
- NewRecordingAdded, NewScreenshotAdded, RecordingStarted, RecordingStopped,
- RequestNewScreenshot, RequestStartRecording, RequestStopRecording,
+ RecordingStarted, RecordingStopped, RequestNewScreenshot, RequestOpenSettings,
+ RequestStartRecording, RequestStopRecording,
};
-use cap_project::RecordingMeta;
use std::path::PathBuf;
-use std::result::Result;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tauri::{
image::Image,
- menu::{IconMenuItem, IsMenuItem, Menu, MenuItem, MenuItemKind, Submenu},
+ menu::{IsMenuItem, Menu, MenuItem},
tray::TrayIconBuilder,
AppHandle, Manager, Runtime, WebviewWindow,
};
@@ -42,11 +40,21 @@ pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
None::<&str>,
)?;
- // Create a submenu for previous recordings
- let prev_recordings_submenu = create_prev_recordings_submenu(app)?;
+ let previous_recordings_i = MenuItem::with_id(
+ app,
+ "previous_recordings",
+ "Previous Recordings",
+ true,
+ None::<&str>,
+ )?;
- // Create a submenu for previous screenshots
- let prev_screenshots_submenu = create_prev_screenshots_submenu(app)?;
+ let previous_screenshots_i = MenuItem::with_id(
+ app,
+ "previous_screenshots",
+ "Previous Screenshots",
+ true,
+ None::<&str>,
+ )?;
let quit_i = MenuItem::with_id(app, "quit", "Quit Cap", true, None::<&str>)?;
@@ -56,8 +64,8 @@ pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
&version_i,
&new_recording_i,
&take_screenshot_i,
- &prev_recordings_submenu,
- &prev_screenshots_submenu,
+ &previous_recordings_i,
+ &previous_screenshots_i,
&quit_i,
],
)?;
@@ -107,22 +115,23 @@ pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
"take_screenshot" => {
let _ = RequestNewScreenshot.emit(&app_handle);
}
+ "previous_recordings" => {
+ let _ = RequestOpenSettings {
+ page: "recordings".to_string(),
+ }
+ .emit(&app_handle);
+ }
+ "previous_screenshots" => {
+ let _ = RequestOpenSettings {
+ page: "screenshots".to_string(),
+ }
+ .emit(&app_handle);
+ }
"quit" => {
app.exit(0);
}
_ => {
- // Handle previous recording menu item clicks
- if let Some(path) =
- get_recording_path_by_pretty_name(app, event.id.as_ref())
- {
- NewRecordingAdded { path }.emit(app).unwrap();
- } else if let Some(path) =
- get_screenshot_path_by_name(app, event.id.as_ref())
- {
- NewScreenshotAdded { path }.emit(app).unwrap();
- } else {
- println!("Unhandled menu item clicked: {:?}", event);
- }
+ println!("Unhandled menu item clicked: {:?}", event);
}
}
}
@@ -142,25 +151,22 @@ pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
})
.build(app);
- let app_handle = app.clone();
- NewRecordingAdded::listen_any(app, {
- println!("New recording added");
- let app_handle = app_handle.clone();
- move |event| {
- handle_new_recording_added(&app_handle, event.payload.path).unwrap();
- }
- });
-
RecordingStarted::listen_any(app, {
let app_handle = app.clone();
let is_recording = Arc::clone(&is_recording);
move |_| {
- is_recording.store(true, Ordering::Relaxed);
- if let Some(tray) = app_handle.tray_by_id("tray") {
- if let Ok(icon) = Image::from_bytes(include_bytes!("../icons/tray-stop-icon.png")) {
- let _ = tray.set_icon(Some(icon));
+ let app_handle = app_handle.clone();
+ let is_recording = Arc::clone(&is_recording);
+ tauri::async_runtime::spawn(async move {
+ is_recording.store(true, Ordering::Relaxed);
+ if let Some(tray) = app_handle.tray_by_id("tray") {
+ if let Ok(icon) =
+ Image::from_bytes(include_bytes!("../icons/tray-stop-icon.png"))
+ {
+ let _ = tray.set_icon(Some(icon));
+ }
}
- }
+ });
}
});
@@ -168,181 +174,24 @@ pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
let app_handle = app.clone();
let is_recording = Arc::clone(&is_recording);
move |_| {
- is_recording.store(false, Ordering::Relaxed);
- if let Some(tray) = app_handle.tray_by_id("tray") {
- if let Ok(icon) =
- Image::from_bytes(include_bytes!("../icons/tray-default-icon.png"))
- {
- let _ = tray.set_icon(Some(icon));
+ let app_handle = app_handle.clone();
+ let is_recording = Arc::clone(&is_recording);
+ tauri::async_runtime::spawn(async move {
+ is_recording.store(false, Ordering::Relaxed);
+ if let Some(tray) = app_handle.tray_by_id("tray") {
+ if let Ok(icon) =
+ Image::from_bytes(include_bytes!("../icons/tray-default-icon.png"))
+ {
+ let _ = tray.set_icon(Some(icon));
+ }
}
- }
+ });
}
});
Ok(())
}
-fn create_prev_recordings_submenu<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<Submenu<R>> {
- let prev_recordings = get_prev_recordings(app).unwrap_or_default();
-
- let items: Vec<MenuItemKind<R>> = if prev_recordings.is_empty() {
- vec![MenuItem::with_id(
- app,
- "no_recordings",
- "No recordings yet",
- false,
- None::<&str>,
- )
- .map(MenuItemKind::MenuItem)
- .unwrap()]
- } else {
- prev_recordings
- .iter()
- .filter_map(|path| {
- let Ok(meta) = RecordingMeta::load_for_project(path) else {
- return None;
- };
- let pretty_name = meta.pretty_name.clone();
- let id = pretty_name.clone();
-
- let screenshots_dir = path.join("screenshots");
- let png_files: Vec<_> = std::fs::read_dir(screenshots_dir)
- .ok()?
- .filter_map(|entry| {
- let entry = entry.ok()?;
- let path = entry.path();
- if path.extension()?.to_str()? == "png" {
- Some(path)
- } else {
- None
- }
- })
- .collect();
-
- if let Some(png_path) = png_files.first() {
- match Image::from_path(png_path) {
- Ok(image) => IconMenuItem::with_id(
- app,
- &id,
- &pretty_name,
- true,
- Some(image),
- None::<&str>,
- )
- .map(MenuItemKind::Icon)
- .ok(),
- Err(_) => MenuItem::with_id(app, &id, &pretty_name, true, None::<&str>)
- .map(MenuItemKind::MenuItem)
- .ok(),
- }
- } else {
- MenuItem::with_id(app, &id, &pretty_name, true, None::<&str>)
- .map(MenuItemKind::MenuItem)
- .ok()
- }
- })
- .collect()
- };
-
- let items_ref: Vec<&dyn IsMenuItem<R>> = items
- .iter()
- .map(|item| item as &dyn IsMenuItem<R>)
- .collect();
-
- Submenu::with_items(app, "Previous Recordings", true, &items_ref)
-}
-
-fn create_prev_screenshots_submenu<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<Submenu<R>> {
- let screenshots_dir = app
- .path()
- .app_data_dir()
- .map(|dir| dir.join("screenshots"))?;
-
- let items: Vec<MenuItemKind<R>> = if !screenshots_dir.exists() {
- vec![MenuItem::with_id(
- app,
- "no_screenshots",
- "No screenshots yet",
- false,
- None::<&str>,
- )
- .map(MenuItemKind::MenuItem)
- .unwrap()]
- } else {
- std::fs::read_dir(screenshots_dir)
- .map_err(tauri::Error::Io)?
- .filter_map(|entry| {
- let entry = entry.ok()?;
- let path = entry.path();
- if path.is_dir() {
- let png_files: Vec<_> = std::fs::read_dir(&path)
- .ok()?
- .filter_map(|file_entry| {
- let file_entry = file_entry.ok()?;
- let file_path = file_entry.path();
- if file_path.extension()?.to_str()? == "png" {
- Some(file_path)
- } else {
- None
- }
- })
- .collect();
-
- if let Some(png_path) = png_files.first() {
- let file_name = png_path.file_stem()?.to_str()?.to_string();
- let id = file_name.clone();
- match Image::from_path(png_path) {
- Ok(image) => IconMenuItem::with_id(
- app,
- &id,
- &file_name,
- true,
- Some(image),
- None::<&str>,
- )
- .map(MenuItemKind::Icon)
- .ok(),
- Err(_) => MenuItem::with_id(app, &id, &file_name, true, None::<&str>)
- .map(MenuItemKind::MenuItem)
- .ok(),
- }
- } else {
- None
- }
- } else {
- None
- }
- })
- .collect()
- };
-
- let items_ref: Vec<&dyn IsMenuItem<R>> = items
- .iter()
- .map(|item| item as &dyn IsMenuItem<R>)
- .collect();
-
- Submenu::with_items(app, "Previous Screenshots", true, &items_ref)
-}
-
-fn get_prev_recordings<R: Runtime>(app: &AppHandle<R>) -> Result<Vec<PathBuf>, tauri::Error> {
- let recordings_dir = app
- .path()
- .app_data_dir()
- .map(|dir| dir.join("recordings"))?;
-
- if !recordings_dir.exists() {
- return Ok(Vec::new());
- }
-
- let entries = std::fs::read_dir(recordings_dir).map_err(tauri::Error::Io)?;
-
- Ok(entries
- .filter_map(Result::ok)
- .filter(|entry| entry.path().extension().map_or(false, |ext| ext == "cap"))
- .map(|entry| entry.path())
- .collect())
-}
-
fn handle_new_recording_added<R: Runtime>(app: &AppHandle<R>, path: PathBuf) -> tauri::Result<()> {
if let Some(tray_handle) = app.tray_by_id("tray") {
// Recreate the entire menu
@@ -368,16 +217,28 @@ fn handle_new_recording_added<R: Runtime>(app: &AppHandle<R>, path: PathBuf) ->
true,
None::<&str>,
)?;
- let prev_recordings_submenu = create_prev_recordings_submenu(app)?;
- let prev_screenshots_submenu = create_prev_screenshots_submenu(app)?;
+ let previous_recordings_i = MenuItem::with_id(
+ app,
+ "previous_recordings",
+ "Previous Recordings",
+ true,
+ None::<&str>,
+ )?;
+ let previous_screenshots_i = MenuItem::with_id(
+ app,
+ "previous_screenshots",
+ "Previous Screenshots",
+ true,
+ None::<&str>,
+ )?;
let quit_i = MenuItem::with_id(app, "quit", "Quit Cap", true, None::<&str>)?;
let menu_items: Vec<&dyn IsMenuItem<R>> = vec![
&version_i,
&new_recording_i,
&take_screenshot_i,
- &prev_recordings_submenu,
- &prev_screenshots_submenu,
+ &previous_recordings_i,
+ &previous_screenshots_i,
&quit_i,
];
let menu = Menu::with_items(app, &menu_items)?;
@@ -388,41 +249,3 @@ fn handle_new_recording_added<R: Runtime>(app: &AppHandle<R>, path: PathBuf) ->
Ok(())
}
-
-fn get_recording_path_by_pretty_name<R: Runtime>(
- app: &AppHandle<R>,
- pretty_name: &str,
-) -> Option<PathBuf> {
- get_prev_recordings(app).ok()?.into_iter().find(|path| {
- let Ok(meta) = RecordingMeta::load_for_project(path) else {
- return false;
- };
- meta.pretty_name == pretty_name
- })
-}
-
-fn get_screenshot_path_by_name<R: Runtime>(app: &AppHandle<R>, name: &str) -> Option<PathBuf> {
- let screenshots_dir = app.path().app_data_dir().ok()?.join("screenshots");
-
- std::fs::read_dir(screenshots_dir)
- .ok()?
- .filter_map(Result::ok)
- .find_map(|entry| {
- let path = entry.path();
- if path.is_dir() {
- std::fs::read_dir(path)
- .ok()?
- .filter_map(Result::ok)
- .find_map(|file_entry| {
- let file_path = file_entry.path();
- if file_path.file_stem()?.to_str()? == name {
- Some(file_path)
- } else {
- None
- }
- })
- } else {
- None
- }
- })
-}
diff --git a/apps/desktop/src/flags.ts b/apps/desktop/src/flags.ts
index d7b3a5c36..d2a3cac0a 100644
--- a/apps/desktop/src/flags.ts
+++ b/apps/desktop/src/flags.ts
@@ -1,4 +1,4 @@
export const flags = {
- split: true,
+ split: import.meta.env.DEV,
pauseResume: import.meta.env.DEV,
};
diff --git a/apps/desktop/src/routes/(window-chrome)/index.tsx b/apps/desktop/src/routes/(window-chrome)/index.tsx
index 6ed49e587..a402e49b5 100644
--- a/apps/desktop/src/routes/(window-chrome)/index.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/index.tsx
@@ -35,7 +35,6 @@ import {
const getAuth = cache(async () => {
const value = await authStore.get();
- console.log({ value });
if (!value) return redirect("/signin");
return value;
}, "getAuth");
@@ -189,7 +188,10 @@ export default function () {
</div>
<div class="flex items-center justify-between pb-[0.25rem]">
<IconCapLogoFull class="w-[90px] h-auto" />
- <button type="button" onClick={() => commands.openSettingsWindow()}>
+ <button
+ type="button"
+ onClick={() => commands.openSettingsWindow("hotkeys")}
+ >
<IconCapSettings class="w-[1.25rem] h-[1.25rem] text-gray-400 hover:text-gray-500" />
</button>
</div>
diff --git a/apps/desktop/src/routes/(window-chrome)/settings.tsx b/apps/desktop/src/routes/(window-chrome)/settings.tsx
index 0feb113f3..83e6984f5 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings.tsx
@@ -1,22 +1,47 @@
-import { A, type RouteSectionProps } from "@solidjs/router";
+import { A, type RouteSectionProps, useLocation } from "@solidjs/router";
+import { cx } from "cva";
import { For } from "solid-js";
export default function (props: RouteSectionProps) {
+ const location = useLocation();
+
return (
<div class="h-full flex flex-row divide-x divide-gray-200 text-[0.875rem] leading-[1.25rem]">
- <ul class="min-w-[12rem] h-full p-[0.625rem]">
- <For each={[{ href: "hotkeys", name: "Shortcuts" }]}>
- {(item) => (
- <li>
- <A
- href={item.href}
- class="bg-gray-50 border border-gray-200 rounded-lg h-[2rem] px-[0.375rem] flex flex-row items-center gap-[0.375rem]"
- >
- <IconCapHotkeys class="size-[1.25rem]" />
- <span>{item.name}</span>
- </A>
- </li>
- )}
+ <ul class="min-w-[12rem] h-full p-[0.625rem] space-y-2">
+ <For
+ each={[
+ { href: "hotkeys", name: "Shortcuts", icon: IconCapHotkeys },
+ {
+ href: "recordings",
+ name: "Previous Recordings",
+ icon: IconLucideVideo,
+ },
+ {
+ href: "screenshots",
+ name: "Previous Screenshots",
+ icon: IconLucideCamera,
+ },
+ ]}
+ >
+ {(item) => {
+ const isActive = () => location.pathname.includes(item.href);
+ return (
+ <li>
+ <A
+ href={item.href}
+ class={cx(
+ "rounded-lg h-[2rem] px-[0.375rem] flex flex-row items-center gap-[0.375rem] transition-colors",
+ isActive()
+ ? "bg-blue-50 border border-blue-200 text-blue-700"
+ : "hover:bg-gray-100"
+ )}
+ >
+ <item.icon class="size-[1.25rem]" />
+ <span>{item.name}</span>
+ </A>
+ </li>
+ );
+ }}
</For>
</ul>
<div class="flex-1 bg-gray-50">{props.children}</div>
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/index.tsx b/apps/desktop/src/routes/(window-chrome)/settings/index.tsx
index 11977a3c8..4b721dde7 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings/index.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings/index.tsx
@@ -1,5 +1,9 @@
import { Navigate } from "@solidjs/router";
+import { useSearchParams } from "@solidjs/router";
-export default function () {
- return <Navigate href="hotkeys" />;
+export default function Settings() {
+ const [searchParams] = useSearchParams();
+ const page = searchParams.page || "hotkeys";
+
+ return <Navigate href={page} />;
}
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx
new file mode 100644
index 000000000..1a1c75803
--- /dev/null
+++ b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx
@@ -0,0 +1,130 @@
+import { createQuery } from "@tanstack/solid-query";
+import { For, Show, createSignal } from "solid-js";
+import { convertFileSrc } from "@tauri-apps/api/core";
+
+import { commands, events } from "~/utils/tauri";
+
+type MediaEntry = {
+ id: string;
+ path: string;
+ prettyName: string;
+ isNew: boolean;
+ thumbnailPath: string;
+};
+
+export default function Recordings() {
+ const fetchRecordings = createQuery(() => ({
+ queryKey: ["recordings"],
+ queryFn: async () => {
+ const result = await commands.listRecordings();
+ if (result.status === "ok") {
+ const recordings = await Promise.all(
+ result.data.map(async (file) => {
+ const [id, path, meta] = file;
+ const thumbnailPath = `${path}/screenshots/display.jpg`;
+
+ return {
+ id,
+ path,
+ prettyName: meta.pretty_name,
+ isNew: false,
+ thumbnailPath,
+ };
+ })
+ );
+ return recordings;
+ } else {
+ return [];
+ }
+ },
+ }));
+
+ const handleRecordingClick = (recording: MediaEntry) => {
+ events.newRecordingAdded.emit({ path: recording.path });
+ };
+
+ const handleOpenFolder = (path: string) => {
+ commands.openFilePath(path);
+ };
+
+ return (
+ <div class="flex flex-col w-full h-full divide-y divide-gray-200 pt-1 pb-12">
+ <div class="flex-1 overflow-y-auto">
+ <Show
+ when={!fetchRecordings.isLoading}
+ fallback={
+ <p class="text-center text-gray-500">Loading recordings...</p>
+ }
+ >
+ <ul class="p-[0.625rem] flex flex-col gap-[0.5rem] w-full">
+ <Show
+ when={fetchRecordings.data && fetchRecordings.data.length > 0}
+ fallback={
+ <p class="text-center text-gray-500">No recordings found</p>
+ }
+ >
+ <For each={fetchRecordings.data}>
+ {(recording) => (
+ <RecordingItem
+ recording={recording}
+ onClick={() => handleRecordingClick(recording)}
+ onOpenFolder={() => handleOpenFolder(recording.path)}
+ />
+ )}
+ </For>
+ </Show>
+ </ul>
+ </Show>
+ </div>
+ </div>
+ );
+}
+
+function RecordingItem(props: {
+ recording: MediaEntry;
+ onClick: () => void;
+ onOpenFolder: () => void;
+}) {
+ const [imageExists, setImageExists] = createSignal(true);
+
+ return (
+ <li class="w-full flex flex-row justify-between items-center p-2 hover:bg-gray-100 rounded">
+ <div class="flex items-center">
+ <Show
+ when={imageExists()}
+ fallback={<div class="w-8 h-8 bg-gray-400 mr-4 rounded" />}
+ >
+ <img
+ class="w-8 h-8 object-cover mr-4 rounded"
+ alt="Recording thumbnail"
+ src={`${convertFileSrc(
+ props.recording.thumbnailPath
+ )}?t=${Date.now()}`}
+ onError={() => setImageExists(false)}
+ />
+ </Show>
+ <span>{props.recording.prettyName}</span>
+ </div>
+ <div class="flex items-center">
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ props.onOpenFolder();
+ }}
+ class="p-2 hover:bg-gray-200 rounded-full mr-2"
+ >
+ <IconLucideFolder size={20} />
+ </button>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ props.onClick();
+ }}
+ class="p-2 hover:bg-gray-200 rounded-full"
+ >
+ <IconLucideEye size={20} />
+ </button>
+ </div>
+ </li>
+ );
+}
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/screenshots.tsx b/apps/desktop/src/routes/(window-chrome)/settings/screenshots.tsx
new file mode 100644
index 000000000..c0568c961
--- /dev/null
+++ b/apps/desktop/src/routes/(window-chrome)/settings/screenshots.tsx
@@ -0,0 +1,129 @@
+import { createQuery } from "@tanstack/solid-query";
+import { For, Show, createSignal } from "solid-js";
+import { convertFileSrc } from "@tauri-apps/api/core";
+
+import { commands, events } from "~/utils/tauri";
+
+type MediaEntry = {
+ id: string;
+ path: string;
+ prettyName: string;
+ isNew: boolean;
+ thumbnailPath: string;
+};
+
+export default function Screenshots() {
+ const fetchScreenshots = createQuery(() => ({
+ queryKey: ["screenshots"],
+ queryFn: async () => {
+ const result = await commands.listScreenshots();
+ if (result.status === "ok") {
+ const screenshots = await Promise.all(
+ result.data.map(async (file) => {
+ const [id, pngPath, meta] = file;
+
+ return {
+ id,
+ path: pngPath,
+ prettyName: meta.pretty_name,
+ isNew: false,
+ thumbnailPath: pngPath,
+ };
+ })
+ );
+ return screenshots;
+ } else {
+ return [];
+ }
+ },
+ }));
+
+ const handleScreenshotClick = (screenshot: MediaEntry) => {
+ events.newScreenshotAdded.emit({ path: screenshot.path });
+ };
+
+ const handleOpenFolder = (path: string) => {
+ commands.openFilePath(path);
+ };
+
+ return (
+ <div class="flex flex-col w-full h-full divide-y divide-gray-200 pt-1 pb-12">
+ <div class="flex-1 overflow-y-auto">
+ <Show
+ when={!fetchScreenshots.isLoading}
+ fallback={
+ <p class="text-center text-gray-500">Loading screenshots...</p>
+ }
+ >
+ <ul class="p-[0.625rem] flex flex-col gap-[0.5rem] w-full">
+ <Show
+ when={fetchScreenshots.data && fetchScreenshots.data.length > 0}
+ fallback={
+ <p class="text-center text-gray-500">No screenshots found</p>
+ }
+ >
+ <For each={fetchScreenshots.data}>
+ {(screenshot) => (
+ <ScreenshotItem
+ screenshot={screenshot}
+ onClick={() => handleScreenshotClick(screenshot)}
+ onOpenFolder={() => handleOpenFolder(screenshot.path)}
+ />
+ )}
+ </For>
+ </Show>
+ </ul>
+ </Show>
+ </div>
+ </div>
+ );
+}
+
+function ScreenshotItem(props: {
+ screenshot: MediaEntry;
+ onClick: () => void;
+ onOpenFolder: () => void;
+}) {
+ const [imageExists, setImageExists] = createSignal(true);
+
+ return (
+ <li class="w-full flex flex-row justify-between items-center p-2 hover:bg-gray-100 rounded">
+ <div class="flex items-center">
+ <Show
+ when={imageExists()}
+ fallback={<div class="w-8 h-8 bg-gray-400 mr-4 rounded" />}
+ >
+ <img
+ class="w-8 h-8 object-cover mr-4 rounded"
+ alt="Screenshot thumbnail"
+ src={`${convertFileSrc(
+ props.screenshot.thumbnailPath
+ )}?t=${Date.now()}`}
+ onError={() => setImageExists(false)}
+ />
+ </Show>
+ <span>{props.screenshot.prettyName}</span>
+ </div>
+ <div class="flex items-center">
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ props.onOpenFolder();
+ }}
+ class="p-2 hover:bg-gray-200 rounded-full mr-2"
+ >
+ <IconLucideFolder size={20} />
+ </button>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ props.onClick();
+ }}
+ class="p-2 hover:bg-gray-200 rounded-full"
+ >
+ <IconLucideEye size={20} />
+ </button>
+ </div>
+ </li>
+ );
+}
diff --git a/apps/desktop/src/routes/(window-chrome)/signin.tsx b/apps/desktop/src/routes/(window-chrome)/signin.tsx
index 53abef5cd..c1f8a01ed 100644
--- a/apps/desktop/src/routes/(window-chrome)/signin.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/signin.tsx
@@ -12,45 +12,52 @@ import { getCurrentWindow } from "@tauri-apps/api/window";
const signInAction = action(async () => {
let res: (url: URL) => void;
- const stopListening = await listen(
- "oauth://url",
- (data: { payload: string }) => {
- if (!data.payload.includes("token")) {
- return;
+ try {
+ const stopListening = await listen(
+ "oauth://url",
+ (data: { payload: string }) => {
+ if (!data.payload.includes("token")) {
+ return;
+ }
+
+ const urlObject = new URL(data.payload);
+ res(urlObject);
}
+ );
- const urlObject = new URL(data.payload);
+ const port: string = await invoke("plugin:oauth|start", {
+ config: { response: callbackTemplate },
+ });
- res(urlObject);
- }
- );
+ await shell.open(
+ `${clientEnv.VITE_SERVER_URL}/api/desktop/session/request?port=${port}`
+ );
- const port: string = await invoke("plugin:oauth|start", {
- config: { response: callbackTemplate },
- });
-
- await shell.open(
- `${clientEnv.VITE_SERVER_URL}/api/desktop/session/request?port=${port}`
- );
+ const url = await new Promise<URL>((r) => {
+ res = r;
+ });
+ stopListening();
- const url = await new Promise<URL>((r) => {
- res = r;
- });
- stopListening();
-
- const token = url.searchParams.get("token");
- const expires = Number(url.searchParams.get("expires"));
- if (!token || !expires) {
- throw new Error("Invalid token or expires");
- }
+ const token = url.searchParams.get("token");
+ const expires = Number(url.searchParams.get("expires"));
+ if (!token || !expires) {
+ throw new Error("Invalid token or expires");
+ }
- await authStore.set({ token, expires });
+ await authStore.set({
+ token,
+ expires,
+ plan: { upgraded: false, last_checked: 0 },
+ });
- getCurrentWindow()
- .setFocus()
- .catch(() => {});
+ getCurrentWindow()
+ .setFocus()
+ .catch(() => {});
- return redirect("/");
+ return redirect("/");
+ } catch (error) {
+ throw error;
+ }
});
export default function Page() {
diff --git a/apps/desktop/src/routes/(window-chrome)/upgrade.tsx b/apps/desktop/src/routes/(window-chrome)/upgrade.tsx
new file mode 100644
index 000000000..4fd75afc4
--- /dev/null
+++ b/apps/desktop/src/routes/(window-chrome)/upgrade.tsx
@@ -0,0 +1,202 @@
+import { createSignal, onCleanup, onMount } from "solid-js";
+import { getProPlanId } from "@cap/utils";
+import { commands } from "~/utils/tauri";
+import { clientEnv } from "~/utils/env";
+import { authStore } from "../../store";
+import { Button } from "@cap/ui-solid";
+import { getCurrentWindow } from "@tauri-apps/api/window";
+
+export default function Page() {
+ const proFeatures = [
+ "Unlimited cloud storage & Shareable links",
+ "Connect custom S3 storage bucket (soon!)",
+ "Advanced teams features",
+ "Unlimited views",
+ "Password protected videos",
+ "Advanced analytics",
+ "Priority support",
+ ];
+
+ const [isAnnual, setIsAnnual] = createSignal(true);
+ const [upgradeComplete, setUpgradeComplete] = createSignal(false);
+ const [loading, setLoading] = createSignal(false);
+
+ const togglePricing = () => {
+ setIsAnnual(!isAnnual());
+ };
+
+ const getCheckoutUrl = async () => {
+ setLoading(true);
+ const planId = getProPlanId(isAnnual() ? "yearly" : "monthly");
+
+ try {
+ const auth = await authStore.get();
+
+ if (!auth) {
+ console.error("User not authenticated");
+ const window = getCurrentWindow();
+ window.close();
+ return;
+ }
+
+ console.log("auth:", auth);
+
+ const response = await fetch(
+ `${clientEnv.VITE_SERVER_URL}/api/desktop/subscribe?origin=${window.location.origin}`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${auth.token}`,
+ },
+ body: JSON.stringify({ priceId: planId }),
+ }
+ );
+
+ if (response.ok) {
+ const data = await response.json();
+ commands.openExternalLink(data.url);
+ } else {
+ console.error("Failed to get checkout URL");
+ }
+ } catch (error) {
+ console.error("Error getting checkout URL:", error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const checkUpgradeStatus = async () => {
+ const result = await commands.checkUpgradedAndUpdate();
+ if (result.status === "ok" && result.data === true) {
+ setUpgradeComplete(true);
+ }
+ };
+
+ onMount(() => {
+ const interval = setInterval(checkUpgradeStatus, 5000);
+ onCleanup(() => clearInterval(interval));
+ });
+ return (
+ <div
+ class={`py-5 max-w-[700px] mx-auto relative ${
+ upgradeComplete() ? "h-full" : ""
+ }`}
+ >
+ {upgradeComplete() && (
+ <div class="h-full flex items-center justify-center bg-gray-800 bg-opacity-75">
+ <div class="bg-white p-6 rounded-lg shadow-lg text-center relative z-10">
+ <h2 class="text-2xl font-bold mb-4">
+ Upgrade complete - Welcome to Cap Pro!
+ </h2>
+ <Button
+ onClick={() => {
+ const window = getCurrentWindow();
+ window.close();
+ }}
+ variant="primary"
+ size="lg"
+ >
+ Close window
+ </Button>
+ </div>
+ </div>
+ )}
+ {!upgradeComplete() && (
+ <>
+ <div class="text-center">
+ <h1 class="text-4xl md:text-5xl mb-3 tracking-[-.05em] font-medium">
+ Upgrade to Cap Pro
+ </h1>
+ <p class="text-base font-normal leading-6 text-gray-400">
+ Cap is currently in public beta, and we're offering special early
+ adopter pricing to our first users. This pricing will be locked in
+ for the lifetime of your subscription.
+ </p>
+ </div>
+ <div class="flex flex-col p-[1rem] gap-[0.75rem] text-[0.875rem] font-[400] flex-1 bg-gray-100">
+ <div class="border text-card-foreground shadow-sm bg-blue-300 p-3 md:p-8 rounded-xl flex-grow border-blue-500/20">
+ <div class="space-y-3">
+ <div class="flex flex-col space-y-1.5 pt-6 px-6 pb-3">
+ <h3 class="font-medium tracking-tight text-3xl text-gray-50">
+ Cap Pro — Early Adopter Pricing
+ </h3>
+ <p class="text-[0.875rem] leading-[1.25rem] text-gray-50/80">
+ For professional use and teams.
+ </p>
+ <div>
+ <div class="flex items-center space-x-3">
+ <h3 class="text-4xl text-gray-50">
+ {isAnnual() ? "$6/mo" : "$9/mo"}
+ </h3>
+ <div>
+ <p class="text-sm font-medium text-gray-50/80">
+ {isAnnual()
+ ? "per user, billed annually."
+ : "per user, billed monthly."}
+ </p>
+ {isAnnual() && (
+ <p class="text-sm text-gray-50/80">
+ or, $9/month, billed monthly.
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="mt-3 px-3 md:px-8">
+ <div class="flex items-center mt-3 pt-4 pb-1 border-t-2 border-gray-50/20">
+ <span class="text-xs text-gray-50/80 mr-2">
+ Switch to {isAnnual() ? "monthly" : "annually"}
+ </span>
+ <button
+ type="button"
+ role="switch"
+ aria-checked={isAnnual()}
+ data-state={isAnnual() ? "unchecked" : "checked"}
+ value={isAnnual() ? "on" : "off"}
+ class="peer inline-flex h-4 w-8 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent 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 bg-blue-400"
+ onClick={togglePricing}
+ >
+ <span
+ data-state={isAnnual() ? "unchecked" : "checked"}
+ 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"
+ />
+ </button>
+ </div>
+ </div>
+ <div class="px-6 pb-4 pt-0">
+ <button
+ onClick={getCheckoutUrl}
+ class="flex items-center justify-center rounded-full bg-gray-50 text-gray-900 hover:bg-gray-200 disabled:bg-gray-100 border border-gray-300 font-medium text-lg px-6 h-12 w-full no-underline"
+ disabled={loading()}
+ >
+ {loading() ? "Loading..." : "Upgrade to Cap Pro"}
+ </button>
+ </div>
+ <div class="flex items-center px-6 pb-6 pt-0">
+ <div class="space-y-8">
+ <div>
+ <ul class="list-none p-0 space-y-3">
+ {proFeatures.map((feature) => (
+ <li class="flex items-center justify-start">
+ <div class="w-6 h-6 m-0 p-0 flex items-center border-[2px] border-white justify-center rounded-full">
+ <IconLucideCheck class="w-5 h-5 stroke-[4px] text-gray-50" />
+ </div>
+ <span class="ml-2 text-lg text-gray-50">
+ {feature}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/routes/in-progress-recording.tsx b/apps/desktop/src/routes/in-progress-recording.tsx
index aff461a8b..8a5e8b00d 100644
--- a/apps/desktop/src/routes/in-progress-recording.tsx
+++ b/apps/desktop/src/routes/in-progress-recording.tsx
@@ -1,6 +1,6 @@
import { createEffect, createSignal, type ComponentProps } from "solid-js";
-import { commands } from "~/utils/tauri";
+import { commands, events } from "~/utils/tauri";
import { createTimer } from "@solid-primitives/timer";
import { createMutation } from "@tanstack/solid-query";
import { flags } from "~/flags";
@@ -43,6 +43,15 @@ export default function () {
},
}));
+ const restartRecording = createMutation(() => ({
+ mutationFn: async () => {
+ await events.requestRestartRecording.emit();
+ setStopped(false);
+ setIsPaused(false);
+ setTime(Date.now());
+ },
+ }));
+
return (
<div
class="text-gray-400 flex flex-row items-stretch bg-gray-500 rounded-[0.75rem] w-full h-full animate-in fade-in"
@@ -68,6 +77,12 @@ export default function () {
{isPaused() ? <IconCapPlayCircle /> : <IconCapPauseCircle />}
</ActionButton>
)}
+ <ActionButton
+ disabled={restartRecording.isPending}
+ onClick={() => restartRecording.mutate()}
+ >
+ <IconCapRestart />
+ </ActionButton>
</div>
<div
class="bg-white-transparent-5 cursor-move flex items-center justify-center p-[0.25rem] border-l border-white-transparent-5"
diff --git a/apps/desktop/src/routes/prev-recordings.tsx b/apps/desktop/src/routes/prev-recordings.tsx
index ec832bd2e..65650ec38 100644
--- a/apps/desktop/src/routes/prev-recordings.tsx
+++ b/apps/desktop/src/routes/prev-recordings.tsx
@@ -23,7 +23,7 @@ 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 { commands, events, Result, UploadResult } from "~/utils/tauri";
import { DEFAULT_PROJECT_CONFIG } from "./editor/projectConfig";
import { createPresets } from "~/utils/createPresets";
@@ -189,18 +189,32 @@ export default function () {
return true;
},
}));
-
const uploadMedia = createMutation(() => ({
mutationFn: async () => {
+ let res: Result<UploadResult, string>;
if (isRecording) {
- const res = await commands.uploadRenderedVideo(
+ res = await commands.uploadRenderedVideo(
mediaId,
presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
);
- if (res.status !== "ok") throw new Error(res.error);
} else {
- const res = await commands.uploadScreenshot(media.path);
- if (res.status !== "ok") throw new Error(res.error);
+ res = await commands.uploadScreenshot(media.path);
+ }
+
+ if (res.status === "error") {
+ throw new Error(res.error);
+ }
+
+ switch (res.data) {
+ case "NotAuthenticated":
+ throw new Error("Not authenticated");
+ case "PlanCheckFailed":
+ throw new Error("Plan check failed");
+ case "UpgradeRequired":
+ throw new Error("Upgrade required");
+ default:
+ // Success case, do nothing
+ break;
}
},
onSuccess: () =>
@@ -230,6 +244,8 @@ export default function () {
});
const [imageExists, setImageExists] = createSignal(true);
+ const [showUpgradeTooltip, setShowUpgradeTooltip] =
+ createSignal(false);
const isLoading = () =>
copyMedia.isPending ||
@@ -279,7 +295,7 @@ export default function () {
<div
class={cx(
"w-full h-full absolute inset-0 transition-all",
- isLoading()
+ isLoading() || showUpgradeTooltip()
? "opacity-100"
: "opacity-0 group-hover:opacity-100",
"backdrop-blur bg-gray-500/80 text-white p-2"
@@ -370,11 +386,27 @@ export default function () {
? "Copy Shareable Link"
: uploadMedia.isPending
? "Uploading Cap"
+ : showUpgradeTooltip()
+ ? "Upgrade Required"
: "Create Shareable Link"
}
- forceOpen={uploadMedia.isPending}
+ forceOpen={
+ uploadMedia.isPending || showUpgradeTooltip()
+ }
tooltipPlacement="left"
- onClick={() => uploadMedia.mutate()}
+ onClick={() => {
+ uploadMedia.mutate(undefined, {
+ onError: (error) => {
+ if (error.message === "Upgrade required") {
+ setShowUpgradeTooltip(true);
+ setTimeout(
+ () => setShowUpgradeTooltip(false),
+ 10000
+ );
+ }
+ },
+ });
+ }}
disabled={
copyMedia.isPending ||
saveMedia.isPending ||
@@ -440,7 +472,7 @@ export default function () {
style={{ color: "white", "font-size": "14px" }}
class={cx(
"absolute bottom-0 left-0 right-0 font-medium bg-gray-500 bg-opacity-40 backdrop-blur p-2 flex justify-between items-center pointer-events-none transition-all",
- isLoading()
+ isLoading() || showUpgradeTooltip()
? "opacity-0"
: "group-hover:opacity-0"
)}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 490d89499..96d26e91e 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -200,7 +200,7 @@ 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<null, string>> {
+async uploadRenderedVideo(videoId: string, project: ProjectConfiguration) : Promise<Result<UploadResult, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("upload_rendered_video", { videoId, project }) };
} catch (e) {
@@ -208,7 +208,7 @@ async uploadRenderedVideo(videoId: string, project: ProjectConfiguration) : Prom
else return { status: "error", error: e as any };
}
},
-async uploadScreenshot(screenshotPath: string) : Promise<Result<string, string>> {
+async uploadScreenshot(screenshotPath: string) : Promise<Result<UploadResult, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("upload_screenshot", { screenshotPath }) };
} catch (e) {
@@ -222,12 +222,15 @@ async getRecordingMeta(id: string, fileType: string) : Promise<RecordingMeta> {
async openFeedbackWindow() : Promise<void> {
await TAURI_INVOKE("open_feedback_window");
},
-async openSettingsWindow() : Promise<void> {
- await TAURI_INVOKE("open_settings_window");
+async openSettingsWindow(page: string) : Promise<void> {
+ await TAURI_INVOKE("open_settings_window", { page });
},
async openChangelogWindow() : Promise<void> {
await TAURI_INVOKE("open_changelog_window");
},
+async openUpgradeWindow() : Promise<void> {
+ await TAURI_INVOKE("open_upgrade_window");
+},
async saveFileDialog(fileName: string, fileType: string) : Promise<Result<string | null, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("save_file_dialog", { fileName, fileType }) };
@@ -236,6 +239,38 @@ async saveFileDialog(fileName: string, fileType: string) : Promise<Result<string
else return { status: "error", error: e as any };
}
},
+async listRecordings() : Promise<Result<([string, string, RecordingMeta])[], string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("list_recordings") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async listScreenshots() : Promise<Result<([string, string, RecordingMeta])[], string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("list_screenshots") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async checkUpgradedAndUpdate() : Promise<Result<boolean, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("check_upgraded_and_update") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async openExternalLink(url: string) : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("open_external_link", { url }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
async setHotkey(action: HotkeyAction, hotkey: Hotkey | null) : Promise<Result<null, null>> {
try {
return { status: "ok", data: await TAURI_INVOKE("set_hotkey", { action, hotkey }) };
@@ -260,6 +295,7 @@ recordingStarted: RecordingStarted,
recordingStopped: RecordingStopped,
renderFrameEvent: RenderFrameEvent,
requestNewScreenshot: RequestNewScreenshot,
+requestOpenSettings: RequestOpenSettings,
requestRestartRecording: RequestRestartRecording,
requestStartRecording: RequestStartRecording,
requestStopRecording: RequestStopRecording,
@@ -275,6 +311,7 @@ recordingStarted: "recording-started",
recordingStopped: "recording-stopped",
renderFrameEvent: "render-frame-event",
requestNewScreenshot: "request-new-screenshot",
+requestOpenSettings: "request-open-settings",
requestRestartRecording: "request-restart-recording",
requestStartRecording: "request-start-recording",
requestStopRecording: "request-stop-recording",
@@ -291,7 +328,7 @@ 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 AudioMeta = { path: string }
-export type AuthStore = { token: string; expires: number }
+export type AuthStore = { token: string; expires: number; plan: Plan }
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]; angle?: number }
export type Bounds = { x: number; y: number; width: number; height: number }
@@ -320,6 +357,7 @@ export type NewScreenshotAdded = { path: string }
export type OSPermission = "screenRecording" | "camera" | "microphone" | "accessibility"
export 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 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[] }
@@ -332,6 +370,7 @@ export type RecordingStopped = { path: string }
export type RenderFrameEvent = { frame_number: number; project: ProjectConfiguration }
export type RenderProgress = { type: "Starting"; total_frames: number } | { type: "EstimatedTotalFrames"; total_frames: number } | { type: "FrameRendered"; current_frame: number }
export type RequestNewScreenshot = null
+export type RequestOpenSettings = { page: string }
export type RequestRestartRecording = null
export type RequestStartRecording = null
export type RequestStopRecording = null
@@ -340,6 +379,7 @@ export type SharingMeta = { id: string; link: string }
export type ShowCapturesPanel = null
export type TimelineConfiguration = { segments: TimelineSegment[] }
export type TimelineSegment = { timescale: number; start: number; end: number }
+export type UploadResult = { Success: string } | "NotAuthenticated" | "PlanCheckFailed" | "UpgradeRequired"
export type Video = { duration: number; width: number; height: number; fps: number }
export type VideoType = "screen" | "output"
export type XY<T> = { x: T; y: T }
diff --git a/apps/storybook/vite.config.ts.timestamp-1727734378066-39ed17d52516d.mjs b/apps/storybook/vite.config.ts.timestamp-1727734378066-39ed17d52516d.mjs
new file mode 100644
index 000000000..da9d40137
--- /dev/null
+++ b/apps/storybook/vite.config.ts.timestamp-1727734378066-39ed17d52516d.mjs
@@ -0,0 +1,11 @@
+// vite.config.ts
+import { defineConfig } from "file:///Users/macbookuser/Documents/GitHub/cap/node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/vite/dist/node/index.js";
+import solid from "file:///Users/macbookuser/Documents/GitHub/cap/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected]_@[email protected][email protected]_/node_modules/vite-plugin-solid/dist/esm/index.mjs";
+import capUIPlugin from "file:///Users/macbookuser/Documents/GitHub/cap/packages/ui-solid/vite.js";
+var vite_config_default = defineConfig({
+ plugins: [solid(), capUIPlugin]
+});
+export {
+ vite_config_default as default
+};
+//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvVXNlcnMvbWFjYm9va3VzZXIvRG9jdW1lbnRzL0dpdEh1Yi9jYXAvYXBwcy9zdG9yeWJvb2tcIjtjb25zdCBfX3ZpdGVfaW5qZWN0ZWRfb3JpZ2luYWxfZmlsZW5hbWUgPSBcIi9Vc2Vycy9tYWNib29rdXNlci9Eb2N1bWVudHMvR2l0SHViL2NhcC9hcHBzL3N0b3J5Ym9vay92aXRlLmNvbmZpZy50c1wiO2NvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9pbXBvcnRfbWV0YV91cmwgPSBcImZpbGU6Ly8vVXNlcnMvbWFjYm9va3VzZXIvRG9jdW1lbnRzL0dpdEh1Yi9jYXAvYXBwcy9zdG9yeWJvb2svdml0ZS5jb25maWcudHNcIjtpbXBvcnQgeyBkZWZpbmVDb25maWcgfSBmcm9tIFwidml0ZVwiO1xuaW1wb3J0IHNvbGlkIGZyb20gXCJ2aXRlLXBsdWdpbi1zb2xpZFwiO1xuaW1wb3J0IGNhcFVJUGx1Z2luIGZyb20gXCJAY2FwL3VpLXNvbGlkL3ZpdGVcIjtcblxuZXhwb3J0IGRlZmF1bHQgZGVmaW5lQ29uZmlnKHtcbiAgcGx1Z2luczogW3NvbGlkKCksIGNhcFVJUGx1Z2luXSxcbn0pO1xuIl0sCiAgIm1hcHBpbmdzIjogIjtBQUFvVixTQUFTLG9CQUFvQjtBQUNqWCxPQUFPLFdBQVc7QUFDbEIsT0FBTyxpQkFBaUI7QUFFeEIsSUFBTyxzQkFBUSxhQUFhO0FBQUEsRUFDMUIsU0FBUyxDQUFDLE1BQU0sR0FBRyxXQUFXO0FBQ2hDLENBQUM7IiwKICAibmFtZXMiOiBbXQp9Cg==
diff --git a/apps/web/app/api/desktop/plan/route.ts b/apps/web/app/api/desktop/plan/route.ts
index f50cd541a..87f4e26fb 100644
--- a/apps/web/app/api/desktop/plan/route.ts
+++ b/apps/web/app/api/desktop/plan/route.ts
@@ -1,10 +1,12 @@
import { type NextRequest } from "next/server";
import { db } from "@cap/database";
-import { videos } from "@cap/database/schema";
+import { users, videos } from "@cap/database/schema";
import { getCurrentUser } from "@cap/database/auth/session";
import { nanoId } from "@cap/database/helpers";
import { cookies } from "next/headers";
import { isUserOnProPlan } from "@cap/utils";
+import { stripe } from "@cap/utils";
+import { eq } from "drizzle-orm";
const allowedOrigins = [
process.env.NEXT_PUBLIC_URL,
@@ -61,9 +63,32 @@ export async function GET(req: NextRequest) {
});
}
- const isSubscribed = isUserOnProPlan({
+ let isSubscribed = isUserOnProPlan({
subscriptionStatus: user.stripeSubscriptionStatus as string,
});
+ if (!isSubscribed && !user.stripeSubscriptionId && user.stripeCustomerId) {
+ try {
+ const subscriptions = await stripe.subscriptions.list({
+ customer: user.stripeCustomerId,
+ });
+ const activeSubscription = subscriptions.data.find(
+ (sub) => sub.status === 'active'
+ );
+ if (activeSubscription) {
+ isSubscribed = true;
+ // Update the user's subscription status in the database
+ await db
+ .update(users)
+ .set({
+ stripeSubscriptionStatus: activeSubscription.status,
+ stripeSubscriptionId: activeSubscription.id,
+ })
+ .where(eq(users.id, user.id));
+ }
+ } catch (error) {
+ console.error('Error fetching subscription from Stripe:', error);
+ }
+ }
return new Response(
JSON.stringify({
@@ -84,4 +109,4 @@ export async function GET(req: NextRequest) {
},
}
);
-}
+}
\ No newline at end of file
diff --git a/apps/web/app/api/desktop/subscribe/route.ts b/apps/web/app/api/desktop/subscribe/route.ts
new file mode 100644
index 000000000..68d62baaa
--- /dev/null
+++ b/apps/web/app/api/desktop/subscribe/route.ts
@@ -0,0 +1,170 @@
+import { type NextRequest } from "next/server";
+import { db } from "@cap/database";
+import { users } from "@cap/database/schema";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { cookies } from "next/headers";
+import { isUserOnProPlan, stripe } from "@cap/utils";
+
+const allowedOrigins = [
+ process.env.NEXT_PUBLIC_URL,
+ "http://localhost:3001",
+ "tauri://localhost",
+ "http://tauri.localhost",
+ "https://tauri.localhost",
+];
+
+export async function OPTIONS(req: NextRequest) {
+ const params = req.nextUrl.searchParams;
+ const origin = params.get("origin") || null;
+ const originalOrigin = req.nextUrl.origin;
+
+ return new Response(null, {
+ status: 200,
+ headers: {
+ "Access-Control-Allow-Origin":
+ origin && allowedOrigins.includes(origin)
+ ? origin
+ : allowedOrigins.includes(originalOrigin)
+ ? originalOrigin
+ : "null",
+ "Access-Control-Allow-Credentials": "true",
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
+ "Access-Control-Allow-Headers": "Authorization, Content-Type, sentry-trace, baggage",
+ },
+ });
+}
+
+export async function POST(request: NextRequest) {
+ const token = request.headers.get("authorization")?.split(" ")[1];
+ if (token) {
+ cookies().set({
+ name: "next-auth.session-token",
+ value: token,
+ path: "/",
+ sameSite: "none",
+ secure: true,
+ httpOnly: true,
+ });
+ }
+
+ const user = await getCurrentUser();
+ let customerId = user?.stripeCustomerId;
+ const { priceId } = await request.json();
+ const params = request.nextUrl.searchParams;
+ const origin = params.get("origin") || null;
+ const originalOrigin = request.nextUrl.origin;
+
+ if (!priceId) {
+ return new Response(JSON.stringify({ error: true }), {
+ status: 400,
+ headers: {
+ "Content-Type": "application/json",
+ "Access-Control-Allow-Origin":
+ origin && allowedOrigins.includes(origin)
+ ? origin
+ : allowedOrigins.includes(originalOrigin)
+ ? originalOrigin
+ : "null",
+ "Access-Control-Allow-Credentials": "true",
+ },
+ });
+ }
+
+ if (!user) {
+ return new Response(JSON.stringify({ error: true, auth: false }), {
+ status: 401,
+ headers: {
+ "Content-Type": "application/json",
+ "Access-Control-Allow-Origin":
+ origin && allowedOrigins.includes(origin)
+ ? origin
+ : allowedOrigins.includes(originalOrigin)
+ ? originalOrigin
+ : "null",
+ "Access-Control-Allow-Credentials": "true",
+ },
+ });
+ }
+
+ if (
+ isUserOnProPlan({
+ subscriptionStatus: user.stripeSubscriptionStatus as string,
+ })
+ ) {
+ return new Response(JSON.stringify({ error: true, subscription: true }), {
+ status: 400,
+ headers: {
+ "Content-Type": "application/json",
+ "Access-Control-Allow-Origin":
+ origin && allowedOrigins.includes(origin)
+ ? origin
+ : allowedOrigins.includes(originalOrigin)
+ ? originalOrigin
+ : "null",
+ "Access-Control-Allow-Credentials": "true",
+ },
+ });
+ }
+
+ if (!user.stripeCustomerId) {
+ const customer = await stripe.customers.create({
+ email: user.email,
+ metadata: {
+ userId: user.id,
+ },
+ });
+
+ await db
+ .update(users)
+ .set({
+ stripeCustomerId: customer.id,
+ })
+ .where(eq(users.id, user.id));
+
+ customerId = customer.id;
+ }
+
+ const checkoutSession = await stripe.checkout.sessions.create({
+ customer: customerId as string,
+ line_items: [
+ {
+ price: priceId,
+ quantity: 1,
+ },
+ ],
+ mode: "subscription",
+ success_url: `${process.env.NEXT_PUBLIC_URL}/dashboard/caps?upgrade=true`,
+ cancel_url: `${process.env.NEXT_PUBLIC_URL}/pricing`,
+ allow_promotion_codes: true,
+ });
+
+ if (checkoutSession.url) {
+ return new Response(JSON.stringify({ url: checkoutSession.url }), {
+ status: 200,
+ headers: {
+ "Content-Type": "application/json",
+ "Access-Control-Allow-Origin":
+ origin && allowedOrigins.includes(origin)
+ ? origin
+ : allowedOrigins.includes(originalOrigin)
+ ? originalOrigin
+ : "null",
+ "Access-Control-Allow-Credentials": "true",
+ },
+ });
+ }
+
+ return new Response(JSON.stringify({ error: true }), {
+ status: 400,
+ headers: {
+ "Content-Type": "application/json",
+ "Access-Control-Allow-Origin":
+ origin && allowedOrigins.includes(origin)
+ ? origin
+ : allowedOrigins.includes(originalOrigin)
+ ? originalOrigin
+ : "null",
+ "Access-Control-Allow-Credentials": "true",
+ },
+ });
+}
\ No newline at end of file
diff --git a/apps/web/app/api/webhooks/stripe/route.ts b/apps/web/app/api/webhooks/stripe/route.ts
index d24079464..52b1de594 100644
--- a/apps/web/app/api/webhooks/stripe/route.ts
+++ b/apps/web/app/api/webhooks/stripe/route.ts
@@ -19,6 +19,7 @@ export const POST = async (req: Request) => {
try {
if (!sig || !webhookSecret) return;
event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);
+ console.log(`✅ Event received: ${event.type}`);
} catch (err: any) {
console.log(`❌ Error message: ${err.message}`);
return new Response(`Webhook Error: ${err.message}`, {
@@ -28,6 +29,7 @@ export const POST = async (req: Request) => {
if (relevantEvents.has(event.type)) {
try {
if (event.type === "checkout.session.completed") {
+ console.log("Processing checkout.session.completed event");
const customer = await stripe.customers.retrieve(
event.data.object.customer as string
);
@@ -36,6 +38,7 @@ export const POST = async (req: Request) => {
foundUserId = customer.metadata.userId;
}
if (!foundUserId) {
+ console.log("No user found in checkout.session.completed event");
return new Response("No user found", {
status: 400,
});
@@ -47,6 +50,7 @@ export const POST = async (req: Request) => {
.where(eq(users.id, foundUserId));
if (!user) {
+ console.log("No user found in database for checkout.session.completed event");
return new Response("No user found", {
status: 400,
});
@@ -59,9 +63,11 @@ export const POST = async (req: Request) => {
stripeSubscriptionStatus: event.data.object.status,
})
.where(eq(users.id, foundUserId));
+ console.log("User updated successfully for checkout.session.completed event");
}
if (event.type === "customer.subscription.updated") {
+ console.log("Processing customer.subscription.updated event");
const customer = await stripe.customers.retrieve(
event.data.object.customer as string
);
@@ -70,6 +76,7 @@ export const POST = async (req: Request) => {
foundUserId = customer.metadata.userId;
}
if (!foundUserId) {
+ console.log("No user found in customer.subscription.updated event");
return new Response("No user found", {
status: 400,
});
@@ -81,6 +88,7 @@ export const POST = async (req: Request) => {
.where(eq(users.id, foundUserId));
if (!user) {
+ console.log("No user found in database for customer.subscription.updated event");
return new Response("No user found", {
status: 400,
});
@@ -93,9 +101,11 @@ export const POST = async (req: Request) => {
stripeSubscriptionStatus: event.data.object.status,
})
.where(eq(users.id, foundUserId));
+ console.log("User updated successfully for customer.subscription.updated event");
}
if (event.type === "customer.subscription.deleted") {
+ console.log("Processing customer.subscription.deleted event");
const customer = await stripe.customers.retrieve(
event.data.object.customer as string
);
@@ -104,6 +114,7 @@ export const POST = async (req: Request) => {
foundUserId = customer.metadata.userId;
}
if (!foundUserId) {
+ console.log("No user found in customer.subscription.deleted event");
return new Response("No user found", {
status: 400,
});
@@ -115,6 +126,7 @@ export const POST = async (req: Request) => {
.where(eq(users.id, foundUserId));
if (!user) {
+ console.log("No user found in database for customer.subscription.deleted event");
return new Response("No user found", {
status: 400,
});
@@ -127,8 +139,10 @@ export const POST = async (req: Request) => {
stripeSubscriptionStatus: event.data.object.status,
})
.where(eq(users.id, foundUserId));
+ console.log("User updated successfully for customer.subscription.deleted event");
}
} catch (error) {
+ console.log('❌ Webhook handler failed. View logs.');
return new Response(
'Webhook error: "Webhook handler failed. View logs."',
{
@@ -137,10 +151,12 @@ export const POST = async (req: Request) => {
);
}
} else {
+ console.log(`Unrecognised event: ${event.type}`);
return new Response(`Unrecognised event: ${event.type}`, {
status: 400,
});
}
+ console.log("✅ Webhook processed successfully");
return NextResponse.json({ received: true });
};
diff --git a/apps/web/app/onboarding/Onboarding.tsx b/apps/web/app/onboarding/Onboarding.tsx
index 018816b0a..9a68a8361 100644
--- a/apps/web/app/onboarding/Onboarding.tsx
+++ b/apps/web/app/onboarding/Onboarding.tsx
@@ -63,7 +63,7 @@ export const Onboarding = ({
<Card noStyle>
<CardContent>
<div className="space-y-3">
- <div>
+ <div className="flex flex-col space-y-1 items-center">
<Label htmlFor="firstName">First name *</Label>
<Input
type="text"
@@ -74,7 +74,7 @@ export const Onboarding = ({
onChange={(e) => setFirstNameInput(e.target.value)}
/>
</div>
- <div>
+ <div className="flex flex-col space-y-1 items-center">
<Label htmlFor="lastName">Last name</Label>
<Input type="text" id="lastName" name="lastName" />
</div>
diff --git a/apps/web/components/pages/DownloadPage.tsx b/apps/web/components/pages/DownloadPage.tsx
index 51b8eaffd..d8e56a770 100644
--- a/apps/web/components/pages/DownloadPage.tsx
+++ b/apps/web/components/pages/DownloadPage.tsx
@@ -20,19 +20,21 @@ export const DownloadPage = () => {
};
return (
- <div className="wrapper wrapper-sm py-32">
+ <div className="wrapper wrapper-sm py-16 md:py-32">
<div className="text-center space-y-4">
- <h1 className="fade-in-down animate-delay-1">Download Cap</h1>
- <p className="fade-in-down animate-delay-2">
+ <h1 className="fade-in-down animate-delay-1 text-2xl md:text-4xl">
+ Download Cap
+ </h1>
+ <p className="fade-in-down animate-delay-2 text-sm md:text-base px-4 md:px-0">
The quickest way to share your screen. Pin to your dock and record in
seconds.
</p>
- <div className="flex items-center justify-center space-x-2 fade-in-up animate-delay-2">
+ <div className="flex flex-col md:flex-row items-center justify-center space-y-2 md:space-y-0 md:space-x-2 fade-in-up animate-delay-2">
<Button
spinner={loading}
size="lg"
href="https://cdn.crabnebula.app/download/cap/cap/latest/platform/dmg-aarch64"
- className=" mx-auto"
+ className="w-full md:w-auto"
>
Download for Apple Silicon
</Button>
@@ -40,12 +42,15 @@ export const DownloadPage = () => {
<Button
size="lg"
href="https://cdn.crabnebula.app/download/cap/cap/latest/platform/dmg-x86_64"
- className=" mx-auto"
+ className="w-full md:w-auto"
>
Download for Intel
</Button>
)}
</div>
+ <div className="fade-in-up animate-delay-2">
+ <p className="text-xs">macOS 12.3+ or later recommended.</p>
+ </div>
{!showOtherOptions && (
<button
onClick={() => setShowOtherOptions(true)}
diff --git a/apps/web/components/pages/HomePage.tsx b/apps/web/components/pages/HomePage.tsx
index 87c6e7593..d058db4be 100644
--- a/apps/web/components/pages/HomePage.tsx
+++ b/apps/web/components/pages/HomePage.tsx
@@ -92,7 +92,7 @@ export const HomePage = () => {
<div className="mb-auto text-center px-4 pt-40 pb-52 md:pb-64 -mt-40">
<Link
href="/updates/cap-v03-launch"
- className="mx-auto mb-4 inline-flex justify-center font-medium transition-colors focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50 bg-blue-400 hover:bg-blue-500 h-9 px-4 py-2 rounded-full space-x-2 items-center"
+ className="mx-auto mb-4 inline-flex justify-center font-medium transition-colors focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50 bg-blue-400 hover:bg-blue-500 h-9 px-4 py-2 rounded-full space-x-2 items-center animate-pulse"
>
<span className="text-sm text-white">
NEW: Cap v0.3 is here!
@@ -144,22 +144,35 @@ export const HomePage = () => {
</div>
</div>
</div>
- <div id="cloud-1" className="absolute top-0 -right-20 opacity-70">
+ <div
+ id="cloud-1"
+ className="absolute top-0 -right-20 opacity-70 md:opacity-70 opacity-90"
+ >
<img
- className="max-w-[40vw] h-auto"
+ className="max-w-[60vw] md:max-w-[40vw] h-auto"
src="/illustrations/cloud-1.png"
alt="Homepage Cloud One"
/>
</div>
- <div id="cloud-2" className="absolute top-0 left-0 opacity-70">
+ <div
+ id="cloud-2"
+ className="absolute top-0 left-0 opacity-70 md:opacity-70 opacity-90"
+ >
<img
- className="max-w-[40vw] h-auto"
+ className="max-w-[60vw] md:max-w-[40vw] h-auto"
src="/illustrations/cloud-2.png"
alt="Homepage Cloud Two"
/>
</div>
- <div id="cloud-3" className="absolute -bottom-10 -left-20 opacity-70">
- <img src="/illustrations/cloud-3.png" alt="Homepage Cloud Three" />
+ <div
+ id="cloud-3"
+ className="absolute -bottom-20 left-0 transform opacity-70 md:opacity-70 opacity-90"
+ >
+ <img
+ className="max-w-[60vw] md:max-w-[100vw] h-auto"
+ src="/illustrations/cloud-3.png"
+ alt="Homepage Cloud Three"
+ />
</div>
</div>
<div
diff --git a/apps/web/components/pages/PricingPage.tsx b/apps/web/components/pages/PricingPage.tsx
index 63309de33..fee3857a4 100644
--- a/apps/web/components/pages/PricingPage.tsx
+++ b/apps/web/components/pages/PricingPage.tsx
@@ -62,7 +62,7 @@ export const PricingPage = () => {
const proList = [
{
- text: "Unlimited cloud storage",
+ text: "Unlimited cloud storage & Shareable links",
available: true,
},
{
diff --git a/apps/web/content/changelog/4.mdx b/apps/web/content/changelog/4.mdx
new file mode 100644
index 000000000..02036122c
--- /dev/null
+++ b/apps/web/content/changelog/4.mdx
@@ -0,0 +1,20 @@
+---
+title: Performance Improvements, New Features & more
+app: Cap Desktop
+publishedAt: "2024-09-30"
+version: 0.3.0-beta.2
+image:
+---
+
+- Performance fix when saving a file
+- Performance improvements when using the editor
+- New "Previous Recordings" window in settings + button in tray menu
+- New "Previous Screenshots" window in settings + button in tray menu
+- New "Restart Recording" button in the in-progress recording window
+- New Shortcuts for taking screenshots and restarting a recording
+- New camera size option in editor
+- New gradient direction toggle in editor
+- Plan upgrade directly from the app
+- Fixed an issue where the app would crash sometimes after signing in
+- Fixed issue with audio exporting (syncing)
+- Updated ffmpeg crates to 7.1
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index 3d2b7b708..3b857b4c8 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -39,6 +39,7 @@ declare global {
const IconCapPlayCircle: typeof import('~icons/cap/play-circle.jsx')['default']
const IconCapPresets: typeof import('~icons/cap/presets.jsx')['default']
const IconCapRedo: typeof import('~icons/cap/redo.jsx')['default']
+ const IconCapRestart: typeof import('~icons/cap/restart.jsx')['default']
const IconCapScissors: typeof import('~icons/cap/scissors.jsx')['default']
const IconCapSettings: typeof import('~icons/cap/settings.jsx')['default']
const IconCapShadow: typeof import('~icons/cap/shadow.jsx')['default']
@@ -50,6 +51,10 @@ declare global {
const IconLucideCamera: typeof import('~icons/lucide/camera.jsx')['default']
const IconLucideCheck: typeof import('~icons/lucide/check.jsx')['default']
const IconLucideEye: typeof import('~icons/lucide/eye.jsx')['default']
+ const IconLucideFolder: typeof import('~icons/lucide/folder.jsx')['default']
+ const IconLucideFoler: typeof import('~icons/lucide/foler.jsx')['default']
const IconLucideLoaderCircle: typeof import('~icons/lucide/loader-circle.jsx')['default']
+ const IconLucideRewind: typeof import('~icons/lucide/rewind.jsx')['default']
const IconLucideSmile: typeof import('~icons/lucide/smile.jsx')['default']
+ const IconLucideVideo: typeof import('~icons/lucide/video.jsx')['default']
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b22031126..029973195 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -139,6 +139,9 @@ importers:
solid-markdown:
specifier: ^2.0.13
version: 2.0.13([email protected])
+ solid-particles:
+ specifier: ^2.9.3
+ version: 2.9.3([email protected])
solid-presence:
specifier: ^0.1.8
version: 0.1.8([email protected])
@@ -220,7 +223,7 @@ importers:
version: 2.30.1
next:
specifier: 14.2.9
next-auth:
specifier: ^4.24.5
@@ -687,7 +690,7 @@ importers:
version: 5.0.7
next:
specifier: 14.2.9
next-auth:
specifier: ^4.24.5
@@ -9180,6 +9183,12 @@ packages:
peerDependencies:
solid-js: ^1.6.0
+ resolution: {integrity: sha512-YkzpYppHSJZjx0AJsKziGMgGXZXzMh4MrH2gGO9GY6vELVkLBd80rJxYXmPc6pvlp9aNLKHrNOCppgbC8xWx/Q==}
+ deprecated: '@tsparticles/solid is the new package compatible with v3, please use that'
+ peerDependencies:
+ solid-js: '>=1.0.0'
+
resolution: {integrity: sha512-pWGtXUFWYYUZNbg5YpG5vkQJyOtzn2KXhxYaMx/4I+lylTLYkITOLevaCwMRN+liCVk0pqB6EayLWojNqBFECA==}
peerDependencies:
@@ -9689,6 +9698,10 @@ packages:
resolution: {integrity: sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==}
+ resolution: {integrity: sha512-ZjDIYex6jBJ4iMc9+z0uPe7SgBnmb6l+EJm83MPIsOny9lPpetMsnw/8YJ3xdxn8hV+S3myTpTN1CkOVmFv0QQ==}
+ deprecated: starting from tsparticles v3 the packages are now moved to @tsparticles/package-name instead of tsparticles-package-name
+
resolution: {integrity: sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==}
engines: {node: '>= 6'}
@@ -16479,7 +16492,7 @@ snapshots:
doctrine: 2.1.0
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.15.1
is-glob: 4.0.3
@@ -19130,7 +19143,7 @@ snapshots:
'@panva/hkdf': 1.2.1
cookie: 0.5.0
jose: 4.15.9
oauth: 0.9.15
openid-client: 5.7.0
preact: 10.24.1
@@ -19179,7 +19192,7 @@ snapshots:
- '@babel/core'
- babel-plugin-macros
dependencies:
'@next/env': 14.2.9
'@swc/helpers': 0.5.5
@@ -20530,6 +20543,12 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ fast-deep-equal: 3.1.3
+ solid-js: 1.9.1
+ tsparticles-engine: 2.12.0
+
dependencies:
'@corvu/utils': 0.4.2([email protected])
@@ -21083,6 +21102,8 @@ snapshots:
+
dependencies:
tslib: 1.14.1