Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix auth and make config backwards compatible

Brendan Allan75136c068931
diff --git a/apps/desktop/src-tauri/src/auth.rs b/apps/desktop/src-tauri/src/auth.rs
index 49cfe610d..ac81256c7 100644
--- a/apps/desktop/src-tauri/src/auth.rs
+++ b/apps/desktop/src-tauri/src/auth.rs
@@ -45,7 +45,7 @@ impl AuthStore {
serde_json::from_value(store).map_err(|e| e.to_string())
}
- pub async fn fetch_and_update_plan(app: &AppHandle) -> Result<(), String> {
+ pub async fn update_auth_plan(app: &AppHandle) -> Result<(), String> {
let auth = Self::get(app)?;
let Some(auth) = auth else {
return Err("User not authenticated".to_string());
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index ee4259a49..ce0e677f9 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1131,17 +1131,6 @@ async fn list_audio_devices() -> Result<Vec<String>, ()> {
Ok(AudioInputFeed::list_devices().keys().cloned().collect())
}
-#[tauri::command(async)]
-#[specta::specta]
-fn open_main_window(app: AppHandle) {
- let permissions = permissions::do_permissions_check(false);
- if !permissions.screen_recording.permitted() || !permissions.accessibility.permitted() {
- return;
- }
-
- ShowCapWindow::Main.show(&app).ok();
-}
-
#[derive(Serialize, Type, tauri_specta::Event, Debug, Clone)]
pub struct UploadProgress {
progress: f64,
@@ -1293,28 +1282,8 @@ async fn upload_screenshot(
};
if !auth.is_upgraded() {
- match AuthStore::fetch_and_update_plan(&app).await {
- Ok(_) => match AuthStore::get(&app) {
- Ok(Some(updated_auth)) => {
- auth = updated_auth;
- }
- Ok(None) => {
- return Ok(UploadResult::NotAuthenticated);
- }
- Err(e) => return Err(format!("Failed to refresh auth: {}", e)),
- },
- Err(e) => {
- if e.contains("Authentication expired") {
- return Ok(UploadResult::NotAuthenticated);
- }
- return Ok(UploadResult::PlanCheckFailed);
- }
- }
-
- if !auth.is_upgraded() {
- ShowCapWindow::Upgrade.show(&app).ok();
- return Ok(UploadResult::UpgradeRequired);
- }
+ ShowCapWindow::Upgrade.show(&app).ok();
+ return Ok(UploadResult::UpgradeRequired);
}
println!("Uploading screenshot: {:?}", screenshot_path);
@@ -1790,30 +1759,6 @@ fn open_external_link(app: tauri::AppHandle, url: String) -> Result<(), String>
Ok(())
}
-#[tauri::command]
-#[specta::specta]
-async fn delete_auth_open_signin(app: AppHandle) -> Result<(), String> {
- AuthStore::set(&app, None).map_err(|e| e.to_string())?;
-
- if let Some(window) = CapWindowId::Settings.get(&app) {
- window.close().ok();
- }
-
- if let Some(window) = CapWindowId::Camera.get(&app) {
- window.close().ok();
- }
- if let Some(window) = CapWindowId::Main.get(&app) {
- window.close().ok();
- }
-
- // Show the signin window
- ShowCapWindow::SignIn
- .show(&app)
- .map_err(|e| e.to_string())?;
-
- Ok(())
-}
-
#[tauri::command]
#[specta::specta]
async fn reset_camera_permissions(_app: AppHandle) -> Result<(), ()> {
@@ -1960,6 +1905,12 @@ async fn get_wallpaper_path(app: AppHandle, filename: String) -> Result<String,
}
}
+#[tauri::command]
+#[specta::specta]
+async fn update_auth_plan(app: AppHandle) {
+ AuthStore::update_auth_plan(&app).await.ok();
+}
+
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub async fn run() {
let tauri_context = tauri::generate_context!();
@@ -2002,7 +1953,6 @@ pub async fn run() {
set_playhead_position,
set_project_config,
open_editor,
- open_main_window,
permissions::open_permission_settings,
permissions::do_permissions_check,
permissions::request_permission,
@@ -2015,7 +1965,6 @@ pub async fn run() {
check_upgraded_and_update,
open_external_link,
hotkeys::set_hotkey,
- delete_auth_open_signin,
reset_camera_permissions,
reset_microphone_permissions,
is_camera_window_open,
@@ -2027,7 +1976,8 @@ pub async fn run() {
show_window,
write_clipboard_string,
platform::perform_haptic_feedback,
- get_wallpaper_path
+ get_wallpaper_path,
+ update_auth_plan
])
.events(tauri_specta::collect_events![
RecordingOptionsChanged,
@@ -2259,10 +2209,6 @@ pub async fn run() {
.ok();
});
- AuthenticationInvalid::listen_any_spawn(&app, |_, app| async move {
- delete_auth_open_signin(app).await.ok();
- });
-
Ok(())
})
.on_window_event(|window, event| {
@@ -2340,8 +2286,7 @@ pub async fn run() {
window.set_focus().ok();
}
} else {
- // No editor, settings or signin window open, show main window
- open_main_window(handle.clone());
+ ShowCapWindow::Main.show(handle).ok();
}
}
_ => {}
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index f38065c0d..364ea9b40 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -1,7 +1,7 @@
#![allow(unused_mut)]
#![allow(unused_imports)]
-use crate::{fake_window, general_settings::AppTheme};
+use crate::{fake_window, general_settings::AppTheme, permissions};
use cap_flags::FLAGS;
use cap_media::sources::CaptureScreen;
use serde::Deserialize;
@@ -170,13 +170,18 @@ impl ShowCapWindow {
.maximizable(false)
.shadow(true)
.build()?,
- Self::Main => self
- .window_builder(app, "/")
- .resizable(false)
- .maximized(false)
- .maximizable(false)
- .center()
- .build()?,
+ Self::Main => {
+ if permissions::do_permissions_check(false).necessary_granted() {
+ self.window_builder(app, "/")
+ .resizable(false)
+ .maximized(false)
+ .maximizable(false)
+ .center()
+ .build()?
+ } else {
+ Self::Setup.show(app)?
+ }
+ }
Self::SignIn => self
.window_builder(app, "/signin")
.resizable(false)
diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx
index 3cf326c47..49aa54e8f 100644
--- a/apps/desktop/src/App.tsx
+++ b/apps/desktop/src/App.tsx
@@ -1,6 +1,7 @@
import { Router, useCurrentMatches } from "@solidjs/router";
import { FileRoutes } from "@solidjs/start/router";
import {
+ createEffect,
createResource,
ErrorBoundary,
onCleanup,
@@ -16,7 +17,6 @@ import "unfonts.css";
import "./styles/theme.css";
import { generalSettingsStore } from "./store";
import { commands, type AppTheme } from "./utils/tauri";
-import type { UnlistenFn } from "@tauri-apps/api/event";
import {
getCurrentWebviewWindow,
WebviewWindow,
@@ -37,9 +37,11 @@ const queryClient = new QueryClient({
export default function App() {
return (
- <Suspense>
- <Inner />
- </Suspense>
+ <QueryClientProvider client={queryClient}>
+ <Suspense>
+ <Inner />
+ </Suspense>
+ </QueryClientProvider>
);
}
@@ -97,58 +99,51 @@ function Inner() {
);
}}
>
- <QueryClientProvider client={queryClient}>
- <Router
- root={(props) => {
- const matches = useCurrentMatches();
+ <Router
+ root={(props) => {
+ const matches = useCurrentMatches();
- onMount(() => {
- for (const match of matches()) {
- if (match.route.info?.AUTO_SHOW_WINDOW === false) return;
- }
+ onMount(() => {
+ for (const match of matches()) {
+ if (match.route.info?.AUTO_SHOW_WINDOW === false) return;
+ }
- currentWindow.show();
- });
+ currentWindow.show();
+ });
- return (
- <Suspense
- fallback={
- (() => {
- console.log("Root suspense fallback showing");
- }) as any
- }
- >
- {props.children}
- </Suspense>
- );
- }}
- >
- <FileRoutes />
- </Router>
- </QueryClientProvider>
+ return (
+ <Suspense
+ fallback={
+ (() => {
+ console.log("Root suspense fallback showing");
+ }) as any
+ }
+ >
+ {props.children}
+ </Suspense>
+ );
+ }}
+ >
+ <FileRoutes />
+ </Router>
</ErrorBoundary>
</>
);
}
function createThemeListener(currentWindow: WebviewWindow) {
- const [theme, themeActions] = createResource<AppTheme | null>(() =>
- generalSettingsStore.get().then((s) => {
- const t = s?.theme ?? null;
- update(t);
- return t;
- })
- );
- generalSettingsStore.listen((s) => {
- themeActions.mutate(s?.theme ?? null);
- update(theme());
+ const generalSettings = generalSettingsStore.createQuery();
+
+ createEffect(() => {
+ update(generalSettings.data?.theme ?? null);
});
- let unlisten: UnlistenFn | undefined;
onMount(async () => {
- unlisten = await currentWindow.onThemeChanged((_) => update(theme()));
+ const unlisten = await currentWindow.onThemeChanged((_) =>
+ update(generalSettings.data?.theme)
+ );
+ onCleanup(() => unlisten?.());
});
- onCleanup(() => unlisten?.());
function update(appTheme: AppTheme | null | undefined) {
if (appTheme === undefined || appTheme === null) return;
diff --git a/apps/desktop/src/routes/(window-chrome)/settings.tsx b/apps/desktop/src/routes/(window-chrome)/settings.tsx
index e5f1dfe37..ad0d14908 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings.tsx
@@ -5,9 +5,9 @@ import { getVersion } from "@tauri-apps/api/app";
import "@total-typescript/ts-reset/filter-boolean";
import toast from "solid-toast";
-import { commands } from "~/utils/tauri";
import { authStore } from "~/store";
import { trackEvent } from "~/utils/analytics";
+import { commands } from "~/utils/tauri";
type MenuItem =
| { type?: "link"; href: string; name: string; icon: any }
@@ -16,15 +16,15 @@ type MenuItem =
let intercomInitialized = false;
export default function Settings(props: RouteSectionProps) {
- const [auth] = createResource(() => authStore.get());
+ const auth = authStore.createQuery();
const [version] = createResource(() => getVersion());
const handleAuth = async () => {
- if (auth()) {
+ if (auth.data) {
trackEvent("user_signed_out", { platform: "desktop" });
- await commands.deleteAuthOpenSignin();
+ authStore.set(undefined);
} else {
- await commands.deleteAuthOpenSignin();
+ commands.showWindow("SignIn");
}
};
@@ -34,8 +34,8 @@ export default function Settings(props: RouteSectionProps) {
Intercom({
app_id: "efxq71cv",
hide_default_launcher: true,
- user_id: auth()?.user_id ?? "",
- user_hash: auth()?.intercom_hash ?? "",
+ user_id: auth.data?.user_id ?? "",
+ user_hash: auth.data?.intercom_hash ?? "",
utm_source: "desktop",
});
intercomInitialized = true;
@@ -43,7 +43,7 @@ export default function Settings(props: RouteSectionProps) {
};
const handleLiveChat = async () => {
- if (!auth()) {
+ if (!auth.data) {
toast.error("Please sign in to access live chat support");
return;
}
@@ -147,7 +147,7 @@ export default function Settings(props: RouteSectionProps) {
{(v) => <p class="text-xs text-gray-400 mb-1">v{v()}</p>}
</Show>
<Button onClick={handleAuth} variant="secondary" class="w-full">
- {auth() ? "Sign Out" : "Sign In"}
+ {auth.data ? "Sign Out" : "Sign In"}
</Button>
</div>
</div>
diff --git a/apps/desktop/src/routes/(window-chrome)/setup.tsx b/apps/desktop/src/routes/(window-chrome)/setup.tsx
index 2cf7dac64..369976be1 100644
--- a/apps/desktop/src/routes/(window-chrome)/setup.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/setup.tsx
@@ -145,7 +145,7 @@ export default function () {
undefined
}
onClick={() => {
- commands.openMainWindow().then(() => {
+ commands.showWindow("Main").then(() => {
getCurrentWindow().close();
});
}}
@@ -482,7 +482,7 @@ function Startup(props: { onClose: () => void }) {
size="lg"
onClick={async () => {
handleStartupCompleted();
- await commands.openMainWindow();
+ await commands.showWindow("Main");
getCurrentWindow().close();
}}
>
diff --git a/apps/desktop/src/routes/(window-chrome)/signin.tsx b/apps/desktop/src/routes/(window-chrome)/signin.tsx
index b31eb500b..9666f3c15 100644
--- a/apps/desktop/src/routes/(window-chrome)/signin.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/signin.tsx
@@ -2,231 +2,43 @@ import { Button } from "@cap/ui-solid";
import * as shell from "@tauri-apps/plugin-shell";
import { listen } from "@tauri-apps/api/event";
import { invoke } from "@tauri-apps/api/core";
-import {
- action,
- redirect,
- useAction,
- useSubmission,
- useNavigate,
-} from "@solidjs/router";
-import { onMount, onCleanup, createSignal } from "solid-js";
import { onOpenUrl } from "@tauri-apps/plugin-deep-link";
+import { Window } from "@tauri-apps/api/window";
+import { createMutation } from "@tanstack/solid-query";
import callbackTemplate from "./callback.template";
import { authStore } from "~/store";
import { clientEnv } from "~/utils/env";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { commands } from "~/utils/tauri";
-import { Window } from "@tauri-apps/api/window";
import { identifyUser, trackEvent } from "~/utils/analytics";
-const signInAction = action(async () => {
- let res: (url: URL) => void;
-
- try {
- const stopListening = await listen(
- "oauth://url",
- (data: { payload: string }) => {
- if (!data.payload.includes("token")) {
- return;
- }
-
- const urlObject = new URL(data.payload);
- res(urlObject);
- }
- );
-
- // Stop any existing OAuth server first
- try {
- await invoke("plugin:oauth|stop");
- } catch (e) {
- // Ignore errors if no server is running
- }
-
- const port: string = await invoke("plugin:oauth|start", {
- config: {
- response: callbackTemplate,
- headers: {
- "Content-Type": "text/html; charset=utf-8",
- "Cache-Control": "no-store, no-cache, must-revalidate",
- Pragma: "no-cache",
- },
- // Add a cleanup function to stop the server after handling the request
- cleanup: true,
- },
- });
-
- // prettier-ignore
- const platform = import.meta.env.VITE_ENVIRONMENT === "development" ? "web" : "desktop";
-
- const callbackUrl = new URL(
- `${clientEnv.VITE_SERVER_URL}/api/desktop/session/request`
- );
- callbackUrl.searchParams.set("port", port);
- callbackUrl.searchParams.set("platform", platform);
-
- await shell.open(callbackUrl.toString());
-
- const url = await new Promise<URL>((r) => {
- res = r;
- });
- stopListening();
-
- const isDevMode = import.meta.env.VITE_ENVIRONMENT === "development";
- if (!isDevMode) {
- return;
- }
-
- const token = url.searchParams.get("token");
- const user_id = url.searchParams.get("user_id");
- const expires = Number(url.searchParams.get("expires"));
- if (!token || !expires || !user_id) {
- throw new Error("Invalid token or expires");
- }
-
- const existingAuth = await authStore.get();
- await authStore.set({
- token,
- user_id,
- intercom_hash: existingAuth?.intercom_hash ?? "",
- expires,
- plan: {
- upgraded: false,
- last_checked: 0,
- manual: existingAuth?.plan?.manual ?? false,
- },
- });
-
- identifyUser(user_id);
- trackEvent("user_signed_in", { platform: "desktop" });
+export default function Page() {
+ const signIn = createMutation(() => ({
+ mutationFn: async (abort: AbortController) => {
+ const platform = import.meta.env.DEV ? "web" : "desktop";
- const currentWindow = await Window.getByLabel("signin");
- await commands.openMainWindow();
+ let session;
- // Add a small delay to ensure window is ready
- await new Promise((resolve) => setTimeout(resolve, 500));
+ if (platform === "web")
+ session = await createLocalServerSession(abort.signal);
+ else session = await createDeepLinkSession(abort.signal);
- const mainWindow = await Window.getByLabel("main");
- console.log("Main window reference:", mainWindow ? "found" : "not found");
+ await shell.open(session.url.toString());
- if (mainWindow) {
- try {
- await mainWindow.setFocus();
- console.log("Successfully set focus on main window");
- } catch (e) {
- console.error("Failed to focus main window:", e);
- }
- }
+ await processAuthData(await session.complete());
- if (currentWindow) {
- await currentWindow.close();
- }
+ await commands.showWindow("Main");
- return redirect("/");
- } catch (error) {
- console.error("Sign in failed:", error);
- await authStore.set();
- throw error;
- }
-});
+ // Add a small delay to ensure window is ready
+ await new Promise((resolve) => setTimeout(resolve, 500));
-export default function Page() {
- const signIn = useAction(signInAction);
- const submission = useSubmission(signInAction);
- const navigate = useNavigate();
- const [isSignedIn, setIsSignedIn] = createSignal(false);
-
- // Listen for auth changes and redirect to signin if auth is cleared
- onMount(async () => {
- let unsubscribe: (() => void) | undefined;
-
- try {
- unsubscribe = await authStore.listen((auth) => {
- if (!auth) {
- // Replace the current route with signin
- navigate("/signin", { replace: true });
- }
- });
- } catch (error) {
- console.error("Failed to set up auth listener:", error);
- }
+ const mainWindow = await Window.getByLabel("main");
+ mainWindow?.setFocus();
- // Clean up OAuth server on component unmount
- onCleanup(async () => {
- try {
- await invoke("plugin:oauth|stop");
- } catch (e) {
- // Ignore errors if no server is running
- }
- unsubscribe?.();
- });
-
- const unsubscribeDeepLink = await onOpenUrl(async (urls) => {
- const isDevMode = import.meta.env.VITE_ENVIRONMENT === "development";
- if (isDevMode) {
- return;
- }
-
- for (const url of urls) {
- if (!url.includes("token=")) return;
-
- const urlObject = new URL(url);
- const token = urlObject.searchParams.get("token");
- const user_id = urlObject.searchParams.get("user_id");
- const expires = Number(urlObject.searchParams.get("expires"));
-
- if (!token || !expires || !user_id) {
- throw new Error("Invalid signin params");
- }
-
- const existingAuth = await authStore.get();
- await authStore.set({
- token,
- user_id,
- expires,
- intercom_hash: existingAuth?.intercom_hash ?? "",
- plan: {
- upgraded: false,
- last_checked: 0,
- manual: existingAuth?.plan?.manual ?? false,
- },
- });
-
- identifyUser(user_id);
- trackEvent("user_signed_in", { platform: "desktop" });
-
- setIsSignedIn(true);
- const currentWindow = await Window.getByLabel("signin");
- await commands.openMainWindow();
-
- // Add a small delay to ensure window is ready
- await new Promise((resolve) => setTimeout(resolve, 500));
-
- const mainWindow = await Window.getByLabel("main");
- console.log(
- "Main window reference:",
- mainWindow ? "found" : "not found"
- );
-
- if (mainWindow) {
- try {
- await mainWindow.setFocus();
- console.log("Successfully set focus on main window");
- } catch (e) {
- console.error("Failed to focus main window:", e);
- }
- }
-
- if (currentWindow) {
- await currentWindow.close();
- }
- }
- });
-
- onCleanup(() => {
- unsubscribeDeepLink();
- });
- });
+ getCurrentWindow().close();
+ },
+ }));
return (
<div class="flex flex-col p-[1rem] gap-[0.75rem] text-[0.875rem] font-[400] flex-1 bg-gray-100">
@@ -237,35 +49,143 @@ export default function Page() {
</h1>
<p class="text-gray-400">Beautiful screen recordings, owned by you.</p>
</div>
- {isSignedIn() ? (
+ {signIn.isPending ? (
<Button
variant="secondary"
- onClick={async () => {
- const currentWindow = getCurrentWindow();
- await currentWindow.close();
+ onClick={() => {
+ signIn.variables.abort();
+ signIn.reset();
}}
>
- Close window
- </Button>
- ) : submission.pending ? (
- <Button variant="secondary" onClick={() => submission.clear()}>
Cancel sign in
</Button>
) : (
<div class="flex flex-col gap-2">
- <Button onClick={() => signIn()}>Sign in with your browser</Button>
- <Button
- variant="secondary"
- onClick={async () => {
- const currentWindow = getCurrentWindow();
- await commands.openMainWindow();
- await currentWindow.close();
- }}
- >
- Continue without signing in
+ <Button onClick={() => signIn.mutate(new AbortController())}>
+ Sign in with your browser
</Button>
</div>
)}
</div>
);
}
+
+function createSessionRequestUrl(
+ port: string | null,
+ platform: "web" | "desktop"
+) {
+ const callbackUrl = new URL(
+ `${clientEnv.VITE_SERVER_URL}/api/desktop/session/request`
+ );
+
+ if (port !== null) callbackUrl.searchParams.set("port", port);
+ callbackUrl.searchParams.set("platform", platform);
+
+ return callbackUrl;
+}
+
+type AuthData = { token: string; user_id: string; expires: number };
+
+async function createLocalServerSession(signal: AbortSignal) {
+ await invoke("plugin:oauth|stop").catch(() => {});
+
+ const port: string = await invoke("plugin:oauth|start", {
+ config: {
+ response: callbackTemplate,
+ headers: {
+ "Content-Type": "text/html; charset=utf-8",
+ "Cache-Control": "no-store, no-cache, must-revalidate",
+ Pragma: "no-cache",
+ },
+ // Add a cleanup function to stop the server after handling the request
+ cleanup: true,
+ },
+ });
+
+ signal.onabort = () => {
+ invoke("plugin:oauth|stop").catch(() => {});
+ };
+
+ let res: (url: URL) => void;
+ const stopListening = await listen(
+ "oauth://url",
+ (data: { payload: string }) => {
+ if (!data.payload.includes("token")) {
+ return;
+ }
+
+ const urlObject = new URL(data.payload);
+ res(urlObject);
+ }
+ );
+
+ return {
+ url: createSessionRequestUrl(port, "web"),
+ complete: async () => {
+ const url = await new Promise<URL>((r) => {
+ res = r;
+ });
+
+ stopListening();
+
+ if (signal.aborted) throw new Error("Sign in aborted");
+
+ const token = url.searchParams.get("token");
+ const user_id = url.searchParams.get("user_id");
+ const expires = Number(url.searchParams.get("expires"));
+ if (!token || !expires || !user_id)
+ throw new Error("Invalid token or expires");
+
+ return { token, user_id, expires };
+ },
+ };
+}
+
+async function createDeepLinkSession(signal: AbortSignal) {
+ let res: (data: AuthData) => void;
+ const p = new Promise<AuthData>((r) => {
+ res = r;
+ });
+ const stopListening = await onOpenUrl(async (urls) => {
+ for (const url of urls) {
+ if (!url.includes("token=")) return;
+ if (signal.aborted) return;
+
+ const urlObject = new URL(url);
+ const token = urlObject.searchParams.get("token");
+ const user_id = urlObject.searchParams.get("user_id");
+ const expires = Number(urlObject.searchParams.get("expires"));
+
+ if (!token || !expires || !user_id) {
+ throw new Error("Invalid signin params");
+ }
+
+ res({ token, user_id, expires });
+ }
+ });
+
+ signal.onabort = () => {
+ stopListening();
+ };
+
+ return {
+ url: createSessionRequestUrl(null, "desktop"),
+ complete: () => p,
+ };
+}
+
+async function processAuthData({ token, user_id, expires }: AuthData) {
+ identifyUser(user_id);
+ trackEvent("user_signed_in", { platform: "desktop" });
+
+ const existingAuth = await authStore.get();
+ await authStore.set({
+ token,
+ user_id,
+ intercom_hash: existingAuth?.intercom_hash ?? "",
+ expires,
+ plan: null,
+ });
+
+ await commands.updateAuthPlan();
+}
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index 91b549273..a5f632d3d 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -33,7 +33,6 @@ import {
import { formatTime } from "./utils";
export function Player() {
- const [auth] = createResource(() => authStore.get());
const {
project,
videoId,
diff --git a/apps/desktop/src/store.ts b/apps/desktop/src/store.ts
index 218351e8b..cb8261de3 100644
--- a/apps/desktop/src/store.ts
+++ b/apps/desktop/src/store.ts
@@ -1,4 +1,6 @@
+import { createQuery, queryOptions } from "@tanstack/solid-query";
import { Store } from "@tauri-apps/plugin-store";
+import { onCleanup } from "solid-js";
import {
type AuthStore,
@@ -24,52 +26,44 @@ export type PresetsStore = {
default?: number;
};
-export const presetsStore = {
- get: () => store().then((s) => s.get<PresetsStore>("presets")),
- set: async (value: PresetsStore) => {
- const s = await store();
- await s.set("presets", value);
- await s.save();
- },
- listen: (fn: (data?: PresetsStore | undefined) => void) =>
- store().then((s) => s.onKeyChange<PresetsStore>("presets", fn)),
-};
+function declareStore<T extends object>(name: string) {
+ const get = () => store().then((s) => s.get<T>(name));
+ const listen = (fn: (data?: T | undefined) => void) =>
+ store().then((s) => s.onKeyChange<T>(name, fn));
-export const authStore = {
- get: () => store().then((s) => s.get<AuthStore>("auth")),
- set: async (value?: AuthStore | undefined) => {
- const s = await store();
- await s.set("auth", value);
- await s.save();
- },
- listen: (fn: (data?: AuthStore | undefined) => void) =>
- store().then((s) => s.onKeyChange<AuthStore>("auth", fn)),
-};
+ return {
+ get,
+ listen,
+ set: async (value?: Partial<T>) => {
+ const s = await store();
+ if (value === undefined) s.delete(name);
+ else {
+ const current = (await s.get<T>(name)) || {};
+ await s.set(name, {
+ ...current,
+ ...value,
+ });
+ }
+ await s.save();
+ },
+ createQuery: () => {
+ const query = createQuery(() => ({
+ queryKey: ["store", name],
+ queryFn: async () => (await get()) ?? null,
+ }));
-export const hotkeysStore = {
- get: () => store().then((s) => s.get<HotkeysStore>("hotkeys")),
- set: async (value: HotkeysStore) => {
- const s = await store();
- await s.set("hotkeys", value);
- await s.save();
- },
-};
+ const cleanup = listen(() => {
+ query.refetch();
+ });
+ onCleanup(() => cleanup.then((c) => c()));
-export const generalSettingsStore = {
- get: () =>
- store().then((s) => s.get<GeneralSettingsStore>("general_settings")),
- set: async (value: Partial<GeneralSettingsStore>) => {
- const s = await store();
- const current =
- (await s.get<GeneralSettingsStore>("general_settings")) || {};
- await s.set("general_settings", {
- ...current,
- ...value,
- });
- await s.save();
- },
- listen: (fn: (data?: GeneralSettingsStore | undefined) => void) =>
- store().then((s) =>
- s.onKeyChange<GeneralSettingsStore>("general_settings", fn)
- ),
-};
+ return query;
+ },
+ };
+}
+
+export const presetsStore = declareStore<PresetsStore>("presets");
+export const authStore = declareStore<AuthStore>("auth");
+export const hotkeysStore = declareStore<HotkeysStore>("hotkeys");
+export const generalSettingsStore =
+ declareStore<GeneralSettingsStore>("general_settings");
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 1a5ae2cda..1aaceb092 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -92,9 +92,6 @@ async setProjectConfig(config: ProjectConfiguration) : Promise<null> {
async openEditor(id: string) : Promise<void> {
await TAURI_INVOKE("open_editor", { id });
},
-async openMainWindow() : Promise<void> {
- await TAURI_INVOKE("open_main_window");
-},
async openPermissionSettings(permission: OSPermission) : Promise<void> {
await TAURI_INVOKE("open_permission_settings", { permission });
},
@@ -131,9 +128,6 @@ async openExternalLink(url: string) : Promise<null> {
async setHotkey(action: HotkeyAction, hotkey: Hotkey | null) : Promise<null> {
return await TAURI_INVOKE("set_hotkey", { action, hotkey });
},
-async deleteAuthOpenSignin() : Promise<null> {
- return await TAURI_INVOKE("delete_auth_open_signin");
-},
async resetCameraPermissions() : Promise<null> {
return await TAURI_INVOKE("reset_camera_permissions");
},
@@ -169,6 +163,9 @@ async performHapticFeedback(pattern: HapticPattern | null, time: HapticPerforman
},
async getWallpaperPath(filename: string) : Promise<string> {
return await TAURI_INVOKE("get_wallpaper_path", { filename });
+},
+async updateAuthPlan() : Promise<void> {
+ await TAURI_INVOKE("update_auth_plan");
}
}
diff --git a/apps/web/app/api/desktop/session/request/route.ts b/apps/web/app/api/desktop/session/request/route.ts
index 4061b16ac..cc104f004 100644
--- a/apps/web/app/api/desktop/session/request/route.ts
+++ b/apps/web/app/api/desktop/session/request/route.ts
@@ -9,31 +9,26 @@ export async function GET(req: NextRequest) {
const searchParams = req.nextUrl.searchParams;
const session = await getServerSession(authOptions);
const port = searchParams.get("port") || "";
+
const platform = searchParams.get("platform") || "web";
const secret = serverEnv.NEXTAUTH_SECRET;
- const loginRedirectUrl = `${clientEnv.NEXT_PUBLIC_WEB_URL}/login?next=${clientEnv.NEXT_PUBLIC_WEB_URL}/api/desktop/session/request?port=${port}`;
- if (!session) {
- return Response.redirect(loginRedirectUrl);
- }
+ const loginRedirectUrl = `${clientEnv.NEXT_PUBLIC_WEB_URL}/login?next=${clientEnv.NEXT_PUBLIC_WEB_URL}${req.nextUrl.pathname}${req.nextUrl.search}`;
+ if (!session) return Response.redirect(loginRedirectUrl);
const token = req.cookies.get("next-auth.session-token") ?? null;
const tokenValue = token?.value ?? null;
const user = await getCurrentUser();
- if (!tokenValue || !user) {
- return Response.redirect(loginRedirectUrl);
- }
+ if (!tokenValue || !user) return Response.redirect(loginRedirectUrl);
const decodedToken = await decode({
token: tokenValue,
secret: secret as string,
});
- if (!decodedToken) {
- return Response.redirect(loginRedirectUrl);
- }
+ if (!decodedToken) return Response.redirect(loginRedirectUrl);
const params = `token=${tokenValue}&expires=${decodedToken?.exp}&user_id=${user.id}`;
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 123e5a8c9..6df6a1517 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -177,6 +177,7 @@ pub struct BackgroundConfiguration {
pub rounding: f64,
pub inset: u32,
pub crop: Option<Crop>,
+ #[serde(default)]
pub shadow: f32,
#[serde(default)]
pub advanced_shadow: Option<ShadowConfiguration>,
@@ -229,6 +230,7 @@ pub struct Camera {
pub size: f32,
pub zoom_size: Option<f32>,
pub rounding: f32,
+ #[serde(default)]
pub shadow: f32,
#[serde(default)]
pub advanced_shadow: Option<ShadowConfiguration>,