Skip to content

Commit

Permalink
app.authed_api_request
Browse files Browse the repository at this point in the history
  • Loading branch information
Brendonovich committed Oct 8, 2024
1 parent 8652b5e commit 6433a21
Show file tree
Hide file tree
Showing 6 changed files with 166 additions and 114 deletions.
20 changes: 12 additions & 8 deletions apps/desktop/src-tauri/src/auth.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use serde::{Deserialize, Serialize};
use specta::Type;
use tauri::{AppHandle, Manager, Wry};
use tauri::{AppHandle, Manager, Runtime, Wry};
use tauri_plugin_store::{with_store, StoreCollection};

use web_api::ManagerExt;

use crate::web_api;

#[derive(Serialize, Deserialize, Type)]
Expand All @@ -19,9 +21,9 @@ pub struct Plan {
}

impl AuthStore {
pub fn get(app: &AppHandle) -> Result<Option<Self>, String> {
pub fn get<R: Runtime>(app: &AppHandle<R>) -> Result<Option<Self>, String> {
let stores = app
.try_state::<StoreCollection<Wry>>()
.try_state::<StoreCollection<R>>()
.ok_or("Store not found")?;
with_store(app.clone(), stores, "store", |store| {
let Some(store) = store.get("auth").cloned() else {
Expand All @@ -39,11 +41,10 @@ impl AuthStore {
return Err("User not authenticated".to_string());
};

let response = web_api::do_authed_request(&auth, |client| {
client.get(web_api::make_url("/api/desktop/plan"))
})
.await
.map_err(|e| e.to_string())?;
let response = app
.authed_api_request(|client| client.get(web_api::make_url("/api/desktop/plan")))
.await
.map_err(|e| e.to_string())?;

if response.status() == reqwest::StatusCode::UNAUTHORIZED {
println!("Authentication expired. Please log in again.");
Expand Down Expand Up @@ -88,3 +89,6 @@ impl AuthStore {
.map_err(|e| e.to_string())
}
}

#[derive(specta::Type, serde::Serialize, tauri_specta::Event, Debug, Clone)]
pub struct AuthenticationInvalid;
Empty file.
67 changes: 17 additions & 50 deletions apps/desktop/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ mod flags;
mod general_settings;
mod hotkeys;
mod macos;
mod main_window;
mod notifications;
mod permissions;
mod recording;
Expand All @@ -29,6 +30,7 @@ use cap_utils::create_named_pipe;
use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
use general_settings::GeneralSettingsStore;
use image::{ImageBuffer, Rgba};
use main_window::create_main_window;
use mp4::Mp4Reader;
use num_traits::ToBytes;
use objc2_app_kit::NSScreenSaverWindowLevel;
Expand Down Expand Up @@ -1435,47 +1437,12 @@ async fn list_audio_devices() -> Result<Vec<String>, ()> {
#[tauri::command(async)]
#[specta::specta]
fn open_main_window(app: AppHandle) {
if let Some(window) = app.get_webview_window("main") {
println!("Main window already exists, setting focus");
window.set_focus().ok();
return;
}

let permissions = permissions::do_permissions_check(false);
if !permissions.screen_recording.permitted() || !permissions.accessibility.permitted() {
return;
}

println!("Creating new main window");
let Some(window) = WebviewWindow::builder(&app, "main", tauri::WebviewUrl::App("/".into()))
.title("Cap")
.inner_size(300.0, 375.0)
.resizable(false)
.maximized(false)
.shadow(true)
.accept_first_mouse(true)
.transparent(true)
.hidden_title(true)
.title_bar_style(tauri::TitleBarStyle::Overlay)
.theme(Some(tauri::Theme::Light))
.build()
.ok()
else {
println!("Failed to create main window");
return;
};

println!("Creating overlay titlebar");
window.create_overlay_titlebar().unwrap();
#[cfg(target_os = "macos")]
{
println!("Setting traffic lights inset for macOS");
window.set_traffic_lights_inset(14.0, 22.0).unwrap();
}

println!("Showing main window");
window.show().unwrap();
println!("Main window opened successfully");
create_main_window(app);
}

#[tauri::command]
Expand Down Expand Up @@ -1579,37 +1546,37 @@ async fn open_settings_window(app: AppHandle, page: String) {
#[tauri::command]
#[specta::specta]
async fn upload_rendered_video(
_app: AppHandle,
app: AppHandle,
video_id: String,
project: ProjectConfiguration,
) -> Result<UploadResult, String> {
let Ok(Some(mut auth)) = AuthStore::get(&_app) else {
let Ok(Some(mut auth)) = AuthStore::get(&app) else {
println!("not authenticated!");
return Ok(UploadResult::NotAuthenticated);
};

notifications::send_notification(&_app, notifications::NotificationType::ShareableLinkCopied);
notifications::send_notification(&app, notifications::NotificationType::ShareableLinkCopied);

// Check if user has an upgraded plan
if !auth.is_upgraded() {
// Fetch and update plan information
if let Err(e) = AuthStore::fetch_and_update_plan(&_app).await {
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();
auth = AuthStore::get(&app).unwrap().unwrap();

// Re-check upgraded status after refresh
if !auth.is_upgraded() {
// Open upgrade window instead of returning an error
open_upgrade_window(_app).await;
open_upgrade_window(app).await;
return Ok(UploadResult::UpgradeRequired);
}
}

let editor_instance = upsert_editor_instance(&_app, video_id.clone()).await;
let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;

let mut meta = editor_instance.meta();

Expand All @@ -1627,12 +1594,12 @@ async fn upload_rendered_video(
}
};

let uploaded_video = upload_video(video_id.clone(), &auth, output_path, false).await?;
let uploaded_video = upload_video(&app, video_id.clone(), output_path, false).await?;

let general_settings = GeneralSettingsStore::get(&_app)?;
let general_settings = GeneralSettingsStore::get(&app)?;
if let Some(settings) = general_settings {
if settings.upload_individual_files {
let video_dir = _app
let video_dir = app
.path()
.app_data_dir()
.unwrap()
Expand All @@ -1650,7 +1617,7 @@ async fn upload_rendered_video(
let file_name = file_path.file_name().unwrap().to_str().unwrap();
let result = if is_audio {
upload_individual_file(
&auth,
&app,
file_path.clone(),
uploaded_video.config.clone(),
file_name,
Expand All @@ -1659,7 +1626,7 @@ async fn upload_rendered_video(
.await
} else {
upload_individual_file(
&auth,
&app,
file_path.clone(),
uploaded_video.config.clone(),
file_name,
Expand All @@ -1684,7 +1651,7 @@ async fn upload_rendered_video(
id: uploaded_video.id.clone(),
});
meta.save_for_project();
RecordingMetaChanged { id: video_id }.emit(&_app).ok();
RecordingMetaChanged { id: video_id }.emit(&app).ok();

uploaded_video.link
};
Expand Down Expand Up @@ -1773,7 +1740,7 @@ async fn upload_screenshot(
sharing.link.clone()
} else {
// Upload the screenshot
let uploaded = upload_image(&auth, screenshot_path.clone())
let uploaded = upload_image(&app, screenshot_path.clone())
.await
.map_err(|e| e.to_string())?;

Expand Down
41 changes: 41 additions & 0 deletions apps/desktop/src-tauri/src/main_window.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use tauri::{AppHandle, Manager, WebviewWindow};

pub fn create_main_window(app: AppHandle) -> WebviewWindow {
if let Some(window) = app.get_webview_window("main") {
println!("Main window already exists, setting focus");
window.set_focus().ok();
return window;
}

println!("Creating new main window");
let window = WebviewWindow::builder(&app, "main", tauri::WebviewUrl::App("/".into()))
.title("Cap")
.inner_size(300.0, 375.0)
.resizable(false)
.maximized(false)
.shadow(true)
.accept_first_mouse(true)
.transparent(true)
.hidden_title(true)
.title_bar_style(tauri::TitleBarStyle::Overlay)
.theme(Some(tauri::Theme::Light))
.build()
.unwrap();

#[cfg(target_os = "macos")]
{
use tauri_plugin_decorum::WebviewWindowExt;

println!("Creating overlay titlebar");
window.create_overlay_titlebar().unwrap();

println!("Setting traffic lights inset for macOS");
window.set_traffic_lights_inset(14.0, 22.0).unwrap();
}

println!("Showing main window");
window.show().unwrap();
println!("Main window opened successfully");

window
}
Loading

1 comment on commit 6433a21

@vercel
Copy link

@vercel vercel bot commented on 6433a21 Oct 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.