mirror of
https://github.com/storytold/artcraft.git
synced 2026-10-23 18:19:30 -04:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3849a18c8e | ||
|
|
ce7b180c7e | ||
|
|
3f5bc6edf8 | ||
|
|
0de867ad13 | ||
|
|
a1cb1b2629 |
Generated
+494
-564
File diff suppressed because it is too large
Load Diff
+5
-5
@@ -342,11 +342,11 @@ sha2 = "0.11.0-rc.5"
|
||||
sha3 = "0.10.8"
|
||||
speculoos = "0.11.0"
|
||||
strum = { version = "0.28.0", features = ["derive"] }
|
||||
tauri = { version = "2.8.3", features = ["unstable", "devtools", "protocol-asset"] } # NB: "devtools" prevents App Store distribution; "ubstable" is needed for window access
|
||||
tauri-plugin-dialog = "2.3.3"
|
||||
tauri-plugin-fs = "2.4.2"
|
||||
tauri-plugin-log = "2.6.0"
|
||||
tauri-plugin-upload = "2.3.1"
|
||||
tauri = { version = "2.11.2", features = ["unstable", "devtools", "protocol-asset"] } # NB: "devtools" prevents App Store distribution; "ubstable" is needed for window access
|
||||
tauri-plugin-dialog = "2.7.1"
|
||||
tauri-plugin-fs = "2.5.1"
|
||||
tauri-plugin-log = "2.8.0"
|
||||
tauri-plugin-upload = "2.4.0"
|
||||
tempdir = "0.3.7"
|
||||
tempfile = "3.27.0"
|
||||
thiserror = "2.0.18"
|
||||
|
||||
@@ -19,7 +19,7 @@ name = "artcraft_app_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2.1.1", features = [] }
|
||||
tauri-build = { version = "2.6.2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
# Workspace hack (faster compile times)
|
||||
|
||||
@@ -1,15 +1,36 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use log::info;
|
||||
|
||||
use errors::AnyhowResult;
|
||||
use shared_env_var_config::mysql::env_get_mysql_connection_string_or_default;
|
||||
use sqlx::mysql::MySqlPoolOptions;
|
||||
use sqlx::MySqlPool;
|
||||
|
||||
pub async fn connect_to_database() -> AnyhowResult<MySqlPool>{
|
||||
pub async fn connect_to_database() -> AnyhowResult<MySqlPool> {
|
||||
let db_connection_string = env_get_mysql_connection_string_or_default();
|
||||
|
||||
let pool_options = MySqlPoolOptions::new()
|
||||
.max_connections(easyenv::get_env_num("MYSQL_MAX_CONNECTIONS", 5)?);
|
||||
// NB: The managed DB's connection ceiling is far above what we use, so the binding
|
||||
// constraint is this per-pod pool. Keep `replicas * MYSQL_MAX_CONNECTIONS` (plus the
|
||||
// background jobs' small pools) comfortably under the server's `max_connections`.
|
||||
let max_connections = easyenv::get_env_num("MYSQL_MAX_CONNECTIONS", 20)?;
|
||||
let min_connections = easyenv::get_env_num("MYSQL_MIN_CONNECTIONS", 0)?;
|
||||
|
||||
// TODO(bt,2024-09-17): Configure logging, etc. after we've upgraded sqlx
|
||||
// NB: Fail fast under pool saturation rather than stacking up on sqlx's 30s default — a
|
||||
// shorter timeout sheds load and surfaces the problem instead of hiding it behind long waits.
|
||||
let acquire_timeout_seconds = easyenv::get_env_num::<u64>("MYSQL_ACQUIRE_TIMEOUT_SECONDS", 10)?;
|
||||
|
||||
// NB: Log the settings before building/connecting so a connect failure has context. We do NOT
|
||||
// log the connection string (it contains credentials).
|
||||
info!(
|
||||
"Building MySQL pool: max_connections={}, min_connections={}, acquire_timeout_seconds={}",
|
||||
max_connections, min_connections, acquire_timeout_seconds,
|
||||
);
|
||||
|
||||
let pool_options = MySqlPoolOptions::new()
|
||||
.max_connections(max_connections)
|
||||
.min_connections(min_connections)
|
||||
.acquire_timeout(Duration::from_secs(acquire_timeout_seconds));
|
||||
|
||||
let pool = pool_options
|
||||
.connect(&db_connection_string)
|
||||
|
||||
+4
@@ -86,6 +86,10 @@ pub async fn enqueue_gptsovits_model_download_handler(
|
||||
&server_state.session_checker,
|
||||
&mut *mysql_connection).await?;
|
||||
|
||||
// NB: The connection isn't needed past this point (the enqueue below uses the pool directly),
|
||||
// so release it now rather than holding a pool slot for the rest of the handler.
|
||||
drop(mysql_connection);
|
||||
|
||||
// ==================== PAID PLAN + PRIORITY ==================== //
|
||||
|
||||
let plan = get_correct_plan_for_session(server_state.server_environment, Some(&user_session));
|
||||
|
||||
+7
-1
@@ -143,14 +143,20 @@ pub async fn omni_gen_image_generate_handler(
|
||||
|
||||
// ==================== PIPELINE ==================== //
|
||||
|
||||
// NB: Release the pooled DB connection before the (slow, external) generation call so we don't
|
||||
// hold a pool slot idle while waiting on the provider — that's what starves the pool and causes
|
||||
// PoolTimedOut on unrelated endpoints. We re-acquire below to write the result.
|
||||
drop(mysql_connection);
|
||||
|
||||
let pipeline_result = run_pipeline_v2(RunPipelineV2Args {
|
||||
router_builder: &router_builder,
|
||||
server_state: &server_state,
|
||||
mysql_connection: &mut mysql_connection,
|
||||
user_token,
|
||||
resolved_media: &resolved_media,
|
||||
}).await?;
|
||||
|
||||
let mut mysql_connection = server_state.mysql_pool.acquire().await?;
|
||||
|
||||
// ==================== DEBUG LOG: FAL REQUEST ==================== //
|
||||
|
||||
if let GenerateImageResponse::Fal(ref fal_payload) = pipeline_result.response {
|
||||
|
||||
+12
-3
@@ -25,18 +25,20 @@ use crate::util::lookup::lookup_media_files_as_cdn_url_list_and_map::MediaFilesA
|
||||
pub struct RunPipelineV2Args<'a> {
|
||||
pub router_builder: &'a GenerateImageRequestBuilder,
|
||||
pub server_state: &'a ServerState,
|
||||
pub mysql_connection: &'a mut sqlx::pool::PoolConnection<sqlx::MySql>,
|
||||
pub user_token: &'a UserToken,
|
||||
pub resolved_media: &'a MediaFilesAsCdnUrlListAndMap,
|
||||
}
|
||||
|
||||
// NB: This pipeline does an external generation call (`finalize_and_generate`) that can take many
|
||||
// seconds. It deliberately does NOT hold a pooled DB connection across that call — it acquires a
|
||||
// short-lived connection only for the wallet deduction. Holding a pooled connection across the
|
||||
// external call is what starves the pool and causes `PoolTimedOut`.
|
||||
pub async fn run_pipeline_v2(
|
||||
args: RunPipelineV2Args<'_>,
|
||||
) -> Result<ImagePipelineResult, CommonWebError> {
|
||||
let RunPipelineV2Args {
|
||||
router_builder,
|
||||
server_state,
|
||||
mysql_connection,
|
||||
user_token,
|
||||
resolved_media,
|
||||
} = args;
|
||||
@@ -55,17 +57,24 @@ pub async fn run_pipeline_v2(
|
||||
let apriori_job_token = InferenceJobToken::generate();
|
||||
|
||||
let maybe_wallet_ledger_entry_token = if cost > 0 {
|
||||
// NB: Short-lived connection — released before the external call below.
|
||||
let mut billing_connection = server_state.mysql_pool.acquire().await
|
||||
.map_err(|err| {
|
||||
warn!("Failed to acquire MySQL connection for image billing: {:?}", err);
|
||||
CommonWebError::from_error(err)
|
||||
})?;
|
||||
let deduction = attempt_wallet_deduction_else_common_web_error(
|
||||
user_token,
|
||||
Some(apriori_job_token.as_str()),
|
||||
cost,
|
||||
mysql_connection,
|
||||
&mut billing_connection,
|
||||
).await?;
|
||||
Some(deduction.ledger_entry_token)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// NB: No pooled DB connection is held across this external generation call.
|
||||
let response = finalize_and_generate(draft_or_request, server_state, resolved_media).await?;
|
||||
|
||||
Ok(ImagePipelineResult {
|
||||
|
||||
+7
-1
@@ -200,16 +200,22 @@ pub async fn omni_gen_video_generate_handler(
|
||||
warn!("Failed to insert HTTP request debug log: {:?}", err);
|
||||
}
|
||||
|
||||
// NB: Release the pooled DB connection before the (slow, external) generation call so we don't
|
||||
// hold a pool slot idle while waiting on the provider — that's what starves the pool and causes
|
||||
// PoolTimedOut on unrelated endpoints. We re-acquire below to write the result.
|
||||
drop(mysql_connection);
|
||||
|
||||
let pipeline_result = run_pipeline_v2(RunPipelineV2Args {
|
||||
router_builder: &router_builder,
|
||||
server_state: &server_state,
|
||||
mysql_connection: &mut mysql_connection,
|
||||
user_token,
|
||||
media_file_to_url_map: &media_file_to_url_map,
|
||||
kinovi_character_id_map: &kinovi_character_id_map,
|
||||
kinovi_account,
|
||||
}).await?;
|
||||
|
||||
let mut mysql_connection = server_state.mysql_pool.acquire().await?;
|
||||
|
||||
// ==================== DEBUG LOG: FAL REQUEST ==================== //
|
||||
|
||||
if let GenerateVideoResponse::Fal(ref fal_payload) = pipeline_result.response {
|
||||
|
||||
+23
-9
@@ -3,7 +3,6 @@ use std::convert::TryFrom;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use log::{error, info, warn};
|
||||
use sqlx::pool::PoolConnection;
|
||||
use artcraft_router::api::router_video_model::RouterVideoModel;
|
||||
use artcraft_router::api::router_provider::RouterProvider;
|
||||
use artcraft_router::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
|
||||
@@ -28,18 +27,20 @@ use crate::state::server_state::ServerState;
|
||||
pub struct RunPipelineV2Args<'a> {
|
||||
pub router_builder: &'a GenerateVideoRequestBuilder,
|
||||
pub server_state: &'a ServerState,
|
||||
pub mysql_connection: &'a mut PoolConnection<sqlx::MySql>,
|
||||
pub user_token: &'a UserToken,
|
||||
pub media_file_to_url_map: &'a Option<HashMap<MediaFileToken, String>>,
|
||||
pub kinovi_character_id_map: &'a Option<HashMap<CharacterToken, String>>,
|
||||
pub kinovi_account: KinoviAccount,
|
||||
}
|
||||
|
||||
// NB: This pipeline does an external generation call (`upload_and_generate`) that can take many
|
||||
// seconds. It deliberately does NOT hold a pooled DB connection across that call — it acquires
|
||||
// short-lived connections only for the billing and (on failure) refund writes. Holding a pooled
|
||||
// connection across the external call is what starves the pool and causes `PoolTimedOut`.
|
||||
pub async fn run_pipeline_v2(args: RunPipelineV2Args<'_>) -> Result<PipelineResult, CommonWebError> {
|
||||
let RunPipelineV2Args {
|
||||
router_builder,
|
||||
server_state,
|
||||
mysql_connection,
|
||||
user_token,
|
||||
media_file_to_url_map,
|
||||
kinovi_character_id_map,
|
||||
@@ -137,11 +138,19 @@ pub async fn run_pipeline_v2(args: RunPipelineV2Args<'_>) -> Result<PipelineResu
|
||||
|
||||
info!("v2 estimated cost: {} credits (estimates: {:?})", cost, cost_estimates);
|
||||
|
||||
// 3. Bill wallet
|
||||
let billing = bill_wallet(user_token, cost, mysql_connection).await?;
|
||||
// 3. Bill wallet (short-lived connection — released before the external call below).
|
||||
let billing = {
|
||||
let mut billing_connection = server_state.mysql_pool.acquire().await
|
||||
.map_err(|err| {
|
||||
error!("Failed to acquire MySQL connection for billing: {:?}", err);
|
||||
CommonWebError::from_error(err)
|
||||
})?;
|
||||
bill_wallet(user_token, cost, &mut billing_connection).await?
|
||||
};
|
||||
|
||||
// 4. Upload media (if draft) and generate video.
|
||||
// The entire block is wrapped so Kinovi failures trigger a refund.
|
||||
// NB: No pooled DB connection is held across this call.
|
||||
let result = upload_and_generate(
|
||||
draft_or_request,
|
||||
server_state,
|
||||
@@ -156,10 +165,15 @@ pub async fn run_pipeline_v2(args: RunPipelineV2Args<'_>) -> Result<PipelineResu
|
||||
if let Some(ledger_entry_token) = billing.maybe_wallet_ledger_entry_token.as_ref() {
|
||||
warn!("Kinovi v2 generation failed, issuing refund for {}: {:?}", ledger_entry_token.as_str(), err);
|
||||
|
||||
let result = refund_wallet_after_api_failure(ledger_entry_token, mysql_connection).await;
|
||||
|
||||
if let Err(refund_err) = result {
|
||||
error!("Failed to refund wallet after Kinovi v2 failure: {:?}", refund_err);
|
||||
match server_state.mysql_pool.acquire().await {
|
||||
Ok(mut refund_connection) => {
|
||||
if let Err(refund_err) = refund_wallet_after_api_failure(ledger_entry_token, &mut refund_connection).await {
|
||||
error!("Failed to refund wallet after Kinovi v2 failure: {:?}", refund_err);
|
||||
}
|
||||
}
|
||||
Err(acquire_err) => {
|
||||
error!("Failed to acquire MySQL connection to refund wallet after Kinovi v2 failure: {:?}", acquire_err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+4
@@ -192,6 +192,10 @@ pub async fn enqueue_studio_gen2_handler(
|
||||
CommonWebError::BadInputWithSimpleMessage("invalid idempotency token".to_string())
|
||||
})?;
|
||||
|
||||
// NB: The connection isn't needed past this point (the enqueue below uses the pool directly),
|
||||
// so release it now rather than holding a pool slot for the rest of the handler.
|
||||
drop(mysql_connection);
|
||||
|
||||
// ==================== LOOK UP MODEL INFO ==================== //
|
||||
|
||||
// TODO(bt): CHECK DATABASE FOR TOKENS!
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@ ios = { level = "full", notes = "" }
|
||||
|
||||
[build-dependencies]
|
||||
#tauri-plugin = { workspace = true, features = ["build"] }
|
||||
tauri-plugin = { version = "2.2.0", features = ["build"] }
|
||||
tauri-plugin = { version = "2.6.2", features = ["build"] }
|
||||
#schemars = { workspace = true }
|
||||
schemars = { version = "0.8" }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -91,7 +91,7 @@ sqlx-sqlite = { version = "0.7.3", default-features = false, features = ["any",
|
||||
stable_deref_trait = { version = "1.2.0" }
|
||||
subtle = { version = "2.5.0", default-features = false, features = ["i128"] }
|
||||
syn-f595c2ba2a3f28df = { package = "syn", version = "2.0.87", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] }
|
||||
tauri-utils = { version = "2.4.0", default-features = false, features = ["build", "compression", "resources"] }
|
||||
tauri-utils = { version = "2.9.2", default-features = false, features = ["build", "compression", "resources"] }
|
||||
time = { version = "0.3.36", features = ["local-offset", "macros", "serde-well-known"] }
|
||||
tokio = { version = "1.45.1", features = ["full"] }
|
||||
tokio-stream = { version = "0.1.16", features = ["fs"] }
|
||||
@@ -171,8 +171,8 @@ stable_deref_trait = { version = "1.2.0" }
|
||||
subtle = { version = "2.5.0", default-features = false, features = ["i128"] }
|
||||
syn-dff4ba8e3ae991db = { package = "syn", version = "1.0.109", features = ["extra-traits", "fold", "full", "visit-mut"] }
|
||||
syn-f595c2ba2a3f28df = { package = "syn", version = "2.0.87", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] }
|
||||
tauri-build = { version = "2.1.1" }
|
||||
tauri-utils = { version = "2.4.0", default-features = false, features = ["build", "compression", "resources"] }
|
||||
tauri-build = { version = "2.6.2" }
|
||||
tauri-utils = { version = "2.9.2", default-features = false, features = ["build", "compression", "resources"] }
|
||||
time-macros = { version = "0.2.18", default-features = false, features = ["formatting", "parsing", "serde"] }
|
||||
tokio = { version = "1.45.1", features = ["full"] }
|
||||
tokio-stream = { version = "0.1.16", features = ["fs"] }
|
||||
|
||||
@@ -0,0 +1,567 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button } from "@storyteller/ui-button";
|
||||
import { Input } from "@storyteller/ui-input";
|
||||
import { Modal } from "@storyteller/ui-modal";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import {
|
||||
faSpinnerThird,
|
||||
faCopy,
|
||||
faCheck,
|
||||
faKey,
|
||||
faTrash,
|
||||
} from "@fortawesome/pro-solid-svg-icons";
|
||||
import {
|
||||
UserApiKeysApi,
|
||||
type ApiKeyInfo,
|
||||
type CreatedApiKey,
|
||||
type UserInfo,
|
||||
} from "@storyteller/api";
|
||||
import { toast } from "../toast/toast";
|
||||
|
||||
const NAME_MAX = 255;
|
||||
const DESCRIPTION_MAX = 512;
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
const INPUT_CLASS =
|
||||
"w-full bg-black/20 border border-white/10 focus:border-primary/50 rounded-lg px-3 py-2 text-sm text-white placeholder-white/30 outline-none";
|
||||
|
||||
interface ApiKeySectionProps {
|
||||
user: UserInfo;
|
||||
}
|
||||
|
||||
export function ApiKeySection(_props: ApiKeySectionProps) {
|
||||
const [api] = useState(() => new UserApiKeysApi());
|
||||
|
||||
const [keys, setKeys] = useState<ApiKeyInfo[]>([]);
|
||||
// Rows fetched so far (including deleted ones we hide), drives the next
|
||||
// offset. The backend returns no total count, so we offer "Load more" while
|
||||
// the last page came back full.
|
||||
const [fetchedCount, setFetchedCount] = useState(0);
|
||||
const [hasMore, setHasMore] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [editingToken, setEditingToken] = useState<string | null>(null);
|
||||
const [pendingDelete, setPendingDelete] = useState<ApiKeyInfo | null>(null);
|
||||
// The full secret, shown exactly once right after a key is created.
|
||||
const [createdKey, setCreatedKey] = useState<CreatedApiKey | null>(null);
|
||||
|
||||
// `reset` reloads from offset 0; otherwise appends the next page.
|
||||
const load = async (reset: boolean) => {
|
||||
if (reset) {
|
||||
setLoading(true);
|
||||
} else {
|
||||
setLoadingMore(true);
|
||||
}
|
||||
const offset = reset ? 0 : fetchedCount;
|
||||
const response = await api.ListApiKeys({ limit: PAGE_SIZE, offset });
|
||||
setLoading(false);
|
||||
setLoadingMore(false);
|
||||
if (response.success && response.data) {
|
||||
const fetched = response.data.api_keys;
|
||||
// The list includes soft-deleted keys; only show live ones.
|
||||
const live = fetched.filter((k) => k.maybe_deleted_at === null);
|
||||
setKeys((prev) => (reset ? live : [...prev, ...live]));
|
||||
setFetchedCount((prev) => (reset ? fetched.length : prev + fetched.length));
|
||||
setHasMore(fetched.length === PAGE_SIZE);
|
||||
} else {
|
||||
toast.error(response.errorMessage ?? "Could not load API keys.");
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
load(true);
|
||||
// Load once on mount; pagination drives subsequent loads explicitly.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const handleCreated = (created: CreatedApiKey) => {
|
||||
setCreating(false);
|
||||
// Reveal the full secret once; the truncated key then appears in the list.
|
||||
setCreatedKey(created);
|
||||
load(true);
|
||||
};
|
||||
|
||||
const handleDeleteConfirmed = async () => {
|
||||
if (!pendingDelete) return;
|
||||
const target = pendingDelete;
|
||||
setPendingDelete(null);
|
||||
const response = await api.DeleteApiKey({ token: target.token });
|
||||
if (response.success) {
|
||||
toast.success("API key deleted.");
|
||||
// Drop it locally so the list updates without a full reload.
|
||||
setKeys((prev) => prev.filter((k) => k.token !== target.token));
|
||||
} else {
|
||||
toast.error(response.errorMessage ?? "Could not delete API key.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<p className="text-sm font-medium">API keys</p>
|
||||
<p className="text-xs opacity-70">
|
||||
Create and manage keys to access the API programmatically.
|
||||
</p>
|
||||
</div>
|
||||
{!creating && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
className="h-9 px-3 shrink-0"
|
||||
onClick={() => setCreating(true)}
|
||||
>
|
||||
Create key
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{createdKey && (
|
||||
<NewKeyReveal
|
||||
created={createdKey}
|
||||
onDismiss={() => setCreatedKey(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{creating && (
|
||||
<CreateKeyForm
|
||||
api={api}
|
||||
onCreated={handleCreated}
|
||||
onCancel={() => setCreating(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<hr className="border-ui-panel-border" />
|
||||
|
||||
{loading ? (
|
||||
<div className="py-6 text-center text-xs opacity-60">
|
||||
<FontAwesomeIcon icon={faSpinnerThird} className="animate-spin" />
|
||||
</div>
|
||||
) : keys.length === 0 ? (
|
||||
<div className="py-6 text-center text-xs opacity-60">
|
||||
You don't have any API keys yet.
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
{keys.map((item) => (
|
||||
<ApiKeyRow
|
||||
key={item.token}
|
||||
api={api}
|
||||
item={item}
|
||||
isEditing={editingToken === item.token}
|
||||
onOpenEdit={() => setEditingToken(item.token)}
|
||||
onCloseEdit={() => setEditingToken(null)}
|
||||
onUpdated={(updated) => {
|
||||
setEditingToken(null);
|
||||
setKeys((prev) =>
|
||||
prev.map((k) => (k.token === updated.token ? updated : k)),
|
||||
);
|
||||
}}
|
||||
onRequestDelete={() => setPendingDelete(item)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasMore && (
|
||||
<div className="flex justify-center pt-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="h-8 px-3"
|
||||
disabled={loadingMore}
|
||||
onClick={() => load(false)}
|
||||
>
|
||||
{loadingMore ? (
|
||||
<FontAwesomeIcon icon={faSpinnerThird} className="animate-spin" />
|
||||
) : (
|
||||
"Load more"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DeleteConfirmModal
|
||||
item={pendingDelete}
|
||||
onCancel={() => setPendingDelete(null)}
|
||||
onConfirm={handleDeleteConfirmed}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateKeyForm({
|
||||
api,
|
||||
onCreated,
|
||||
onCancel,
|
||||
}: {
|
||||
api: UserApiKeysApi;
|
||||
onCreated: (created: CreatedApiKey) => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const [name, setName] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const trimmedName = name.trim();
|
||||
const canSubmit = trimmedName.length > 0;
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
if (!canSubmit) {
|
||||
setError("Enter a name for the key.");
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
const trimmedDescription = description.trim();
|
||||
const response = await api.CreateApiKey({
|
||||
name: trimmedName,
|
||||
maybeDescription:
|
||||
trimmedDescription.length > 0 ? trimmedDescription : undefined,
|
||||
});
|
||||
setSubmitting(false);
|
||||
|
||||
if (response.success && response.data) {
|
||||
toast.success("API key created.");
|
||||
onCreated(response.data);
|
||||
} else {
|
||||
setError(response.errorMessage ?? "Could not create API key.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-2">
|
||||
<Input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Name (required)"
|
||||
maxLength={NAME_MAX}
|
||||
autoFocus
|
||||
inputClassName={INPUT_CLASS}
|
||||
/>
|
||||
<Input
|
||||
type="text"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="Description (optional)"
|
||||
maxLength={DESCRIPTION_MAX}
|
||||
inputClassName={INPUT_CLASS}
|
||||
/>
|
||||
{error && <FormError message={error} />}
|
||||
<FormActions
|
||||
onCancel={onCancel}
|
||||
submitting={submitting}
|
||||
disabled={!canSubmit}
|
||||
submitLabel="Create"
|
||||
/>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function NewKeyReveal({
|
||||
created,
|
||||
onDismiss,
|
||||
}: {
|
||||
created: CreatedApiKey;
|
||||
onDismiss: () => void;
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const handleCopy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(created.api_key);
|
||||
setCopied(true);
|
||||
toast.success("Copied to clipboard.");
|
||||
} catch {
|
||||
toast.error("Could not copy. Select and copy it manually.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 rounded-lg border border-primary/40 bg-primary/10 p-3">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<FontAwesomeIcon icon={faKey} className="opacity-80" />
|
||||
<span>API key created</span>
|
||||
</div>
|
||||
<p className="text-xs opacity-80">
|
||||
Copy your key now. For security, you won't be able to see it again.
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="min-w-0 flex-1 truncate rounded-md bg-black/40 px-3 py-2 font-mono text-xs text-white">
|
||||
{created.api_key}
|
||||
</code>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="h-9 px-3 shrink-0"
|
||||
onClick={handleCopy}
|
||||
>
|
||||
<FontAwesomeIcon icon={copied ? faCheck : faCopy} className="mr-1.5" />
|
||||
{copied ? "Copied" : "Copy"}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex justify-end pt-0.5">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="h-8 px-3"
|
||||
onClick={onDismiss}
|
||||
>
|
||||
Done
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ApiKeyRow({
|
||||
api,
|
||||
item,
|
||||
isEditing,
|
||||
onOpenEdit,
|
||||
onCloseEdit,
|
||||
onUpdated,
|
||||
onRequestDelete,
|
||||
}: {
|
||||
api: UserApiKeysApi;
|
||||
item: ApiKeyInfo;
|
||||
isEditing: boolean;
|
||||
onOpenEdit: () => void;
|
||||
onCloseEdit: () => void;
|
||||
onUpdated: (updated: ApiKeyInfo) => void;
|
||||
onRequestDelete: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-2 rounded-lg border border-ui-panel-border p-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
<p className="truncate text-sm font-medium">{item.name}</p>
|
||||
{item.maybe_description && (
|
||||
<p className="truncate text-xs opacity-70">
|
||||
{item.maybe_description}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
{/* Truncated, display-only — the full secret is only shown on create. */}
|
||||
<code className="min-w-0 truncate rounded bg-black/30 px-2 py-1 font-mono text-[11px] text-white/70">
|
||||
{item.truncated_api_key}
|
||||
</code>
|
||||
<span className="text-[10px] uppercase tracking-wider text-white/40">
|
||||
{formatDate(item.created_at)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{!isEditing && (
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="h-8 px-3"
|
||||
onClick={onOpenEdit}
|
||||
>
|
||||
Edit
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="h-8 px-2.5 text-red-400"
|
||||
onClick={onRequestDelete}
|
||||
>
|
||||
<FontAwesomeIcon icon={faTrash} />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{isEditing && (
|
||||
<EditDescriptionForm
|
||||
api={api}
|
||||
item={item}
|
||||
onUpdated={onUpdated}
|
||||
onCancel={onCloseEdit}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EditDescriptionForm({
|
||||
api,
|
||||
item,
|
||||
onUpdated,
|
||||
onCancel,
|
||||
}: {
|
||||
api: UserApiKeysApi;
|
||||
item: ApiKeyInfo;
|
||||
onUpdated: (updated: ApiKeyInfo) => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const initial = item.maybe_description ?? "";
|
||||
const [value, setValue] = useState(initial);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const trimmed = value.trim();
|
||||
const isDirty = trimmed !== initial.trim();
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
if (!isDirty) {
|
||||
onCancel();
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
const nextDescription = trimmed.length > 0 ? trimmed : null;
|
||||
const response = await api.UpdateApiKey({
|
||||
token: item.token,
|
||||
maybeDescription: nextDescription,
|
||||
});
|
||||
setSubmitting(false);
|
||||
|
||||
if (response.success) {
|
||||
toast.success("API key updated.");
|
||||
// Update endpoint returns only { success }; merge the new description in.
|
||||
onUpdated({ ...item, maybe_description: nextDescription });
|
||||
} else {
|
||||
setError(response.errorMessage ?? "Could not update API key.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-2 pt-1">
|
||||
<Input
|
||||
type="text"
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
placeholder="Description (optional)"
|
||||
maxLength={DESCRIPTION_MAX}
|
||||
autoFocus
|
||||
inputClassName={INPUT_CLASS}
|
||||
/>
|
||||
{error && <FormError message={error} />}
|
||||
<FormActions
|
||||
onCancel={onCancel}
|
||||
submitting={submitting}
|
||||
disabled={!isDirty}
|
||||
submitLabel="Save"
|
||||
/>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function DeleteConfirmModal({
|
||||
item,
|
||||
onCancel,
|
||||
onConfirm,
|
||||
}: {
|
||||
item: ApiKeyInfo | null;
|
||||
onCancel: () => void;
|
||||
onConfirm: () => void;
|
||||
}) {
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
const handleConfirm = async () => {
|
||||
setDeleting(true);
|
||||
await onConfirm();
|
||||
setDeleting(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isOpen={item !== null} onClose={onCancel} className="max-w-sm">
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h3 className="text-base font-semibold">Delete API key</h3>
|
||||
<p className="text-sm opacity-70">
|
||||
Delete "{item?.name}"? Any application using this key will stop
|
||||
working. This can't be undone.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="h-9 px-3"
|
||||
onClick={onCancel}
|
||||
disabled={deleting}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
className="h-9 px-4 bg-red-500 hover:bg-red-600"
|
||||
onClick={handleConfirm}
|
||||
disabled={deleting}
|
||||
>
|
||||
{deleting ? (
|
||||
<FontAwesomeIcon icon={faSpinnerThird} className="animate-spin" />
|
||||
) : (
|
||||
"Delete"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function FormActions({
|
||||
onCancel,
|
||||
submitting,
|
||||
disabled,
|
||||
submitLabel,
|
||||
}: {
|
||||
onCancel: () => void;
|
||||
submitting: boolean;
|
||||
disabled: boolean;
|
||||
submitLabel: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center justify-end gap-2 pt-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="h-9 px-3"
|
||||
onClick={onCancel}
|
||||
disabled={submitting}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
className="h-9 px-4"
|
||||
disabled={submitting || disabled}
|
||||
>
|
||||
{submitting ? (
|
||||
<FontAwesomeIcon icon={faSpinnerThird} className="animate-spin" />
|
||||
) : (
|
||||
submitLabel
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FormError({ message }: { message: string }) {
|
||||
return <p className="text-xs text-red-400 leading-tight">{message}</p>;
|
||||
}
|
||||
|
||||
function formatDate(raw: string): string {
|
||||
const date = new Date(raw);
|
||||
if (Number.isNaN(date.getTime())) return raw;
|
||||
return date.toLocaleDateString(undefined, {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
});
|
||||
}
|
||||
@@ -1,36 +1,65 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Modal } from "@storyteller/ui-modal";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faCog, faUser } from "@fortawesome/pro-solid-svg-icons";
|
||||
import { faCog, faUser, faKey } from "@fortawesome/pro-solid-svg-icons";
|
||||
import { Switch } from "@storyteller/ui-switch";
|
||||
import { USER_FEATURE_FLAGS } from "@storyteller/api";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { useEnterToGenerateStore } from "../../lib/enter-to-generate-store";
|
||||
import { useSession } from "../../lib/session";
|
||||
import { AccountSection } from "./AccountSection";
|
||||
import { ApiKeySection } from "./ApiKeySection";
|
||||
|
||||
type Tab = "general" | "account";
|
||||
type Tab = "general" | "account" | "apiKeys";
|
||||
|
||||
interface SettingsModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const TABS: { id: Tab; label: string; icon: typeof faCog }[] = [
|
||||
const BASE_TABS: { id: Tab; label: string; icon: typeof faCog }[] = [
|
||||
{ id: "general", label: "General", icon: faCog },
|
||||
{ id: "account", label: "Account", icon: faUser },
|
||||
];
|
||||
|
||||
const API_KEYS_TAB: { id: Tab; label: string; icon: typeof faCog } = {
|
||||
id: "apiKeys",
|
||||
label: "API Keys",
|
||||
icon: faKey,
|
||||
};
|
||||
|
||||
export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
|
||||
const { user } = useSession();
|
||||
const [tab, setTab] = useState<Tab>("general");
|
||||
|
||||
const hasApiKeyFlag = !!user?.maybe_feature_flags?.includes(
|
||||
USER_FEATURE_FLAGS.API_KEY,
|
||||
);
|
||||
|
||||
const tabs = useMemo(
|
||||
() => (hasApiKeyFlag ? [...BASE_TABS, API_KEYS_TAB] : BASE_TABS),
|
||||
[hasApiKeyFlag],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) setTab("general");
|
||||
}, [isOpen]);
|
||||
|
||||
const activeLabel = TABS.find((t) => t.id === tab)?.label ?? "";
|
||||
// If the only-conditional tab disappears (e.g. flag revoked while open),
|
||||
// fall back to a visible tab.
|
||||
useEffect(() => {
|
||||
if (!tabs.some((t) => t.id === tab)) setTab("general");
|
||||
}, [tabs, tab]);
|
||||
|
||||
const activeLabel = tabs.find((t) => t.id === tab)?.label ?? "";
|
||||
|
||||
return (
|
||||
<Modal isOpen={isOpen} onClose={onClose} className="max-w-3xl" childPadding={false}>
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
className="max-w-3xl"
|
||||
childPadding={false}
|
||||
>
|
||||
<div className="h-[100dvh] sm:h-[560px]">
|
||||
<div className="flex h-full flex-col sm:grid sm:grid-cols-12 sm:gap-3">
|
||||
<div className="relative shrink-0 border-b border-ui-panel-border p-4 sm:col-span-4 sm:border-b-0 sm:p-3 sm:pt-2 sm:after:absolute sm:after:right-0 sm:after:top-0 sm:after:h-full sm:after:w-px sm:after:bg-ui-panel-border">
|
||||
@@ -39,7 +68,7 @@ export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
|
||||
</div>
|
||||
<hr className="my-2 hidden w-full border-ui-panel-border sm:block" />
|
||||
<div className="flex gap-2 overflow-x-auto pe-10 sm:block sm:space-y-1 sm:overflow-visible sm:pe-0">
|
||||
{TABS.map((t) => (
|
||||
{tabs.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
onClick={() => setTab(t.id)}
|
||||
@@ -64,6 +93,7 @@ export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
|
||||
<div className="h-full p-4 text-sm sm:p-3 sm:ps-0">
|
||||
{tab === "general" && <GeneralPanel />}
|
||||
{tab === "account" && <AccountPanel />}
|
||||
{tab === "apiKeys" && <ApiKeysPanel />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -82,12 +112,16 @@ function GeneralPanel() {
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<p className="text-sm font-medium">Enter to generate</p>
|
||||
<p className="text-xs opacity-70">
|
||||
When on, pressing Enter submits the prompt and Shift+Enter
|
||||
adds a new line. When off (default), both Enter and
|
||||
Shift+Enter add a new line, use the button to submit.
|
||||
When on, pressing Enter submits the prompt and Shift+Enter adds a
|
||||
new line. When off (default), both Enter and Shift+Enter add a new
|
||||
line, use the button to submit.
|
||||
</p>
|
||||
</div>
|
||||
<Switch enabled={enterToGenerate} setEnabled={setEnterToGenerate} offClassName="bg-white/20" />
|
||||
<Switch
|
||||
enabled={enterToGenerate}
|
||||
setEnabled={setEnterToGenerate}
|
||||
offClassName="bg-white/20"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -116,3 +150,25 @@ function AccountPanel() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ApiKeysPanel() {
|
||||
const { user, authChecked } = useSession();
|
||||
|
||||
if (!authChecked) {
|
||||
return <div className="pt-3 text-xs opacity-60">Loading API keys...</div>;
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<div className="pt-3 text-xs opacity-60">
|
||||
You need to be signed in to manage API keys.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="pt-3">
|
||||
<ApiKeySection user={user} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/plugin-dialog": "^2.2.1",
|
||||
"@tauri-apps/plugin-upload": "2.2.1"
|
||||
"@tauri-apps/plugin-dialog": "^2.7.1",
|
||||
"@tauri-apps/plugin-upload": "2.4.0"
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ export * from "./lib/PromptsApi.js";
|
||||
export * from "./lib/TtsApi.js";
|
||||
export * from "./lib/UserBookmarksApi.js";
|
||||
export * from "./lib/PasswordResetApi.js";
|
||||
export * from "./lib/UserApiKeysApi.js";
|
||||
export * from "./lib/UserReferralCodesApi.js";
|
||||
export * from "./lib/UsersApi.js";
|
||||
export * from "./lib/VideoApi.js";
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import { ApiManager, ApiResponse, buildSessionHeaders } from "./ApiManager.js";
|
||||
import { FetchProxy as fetch } from "@storyteller/tauri-utils";
|
||||
|
||||
// Canonical wire shape for an API key (list rows + single-key GET). Mirrors the
|
||||
// backend `ApiKeyInfo`. The full secret is NEVER here — only
|
||||
// `truncated_api_key` (first 20 chars). The full value is returned exactly once
|
||||
// at creation time (see CreatedApiKey).
|
||||
export interface ApiKeyInfo {
|
||||
token: string;
|
||||
truncated_api_key: string;
|
||||
name: string;
|
||||
maybe_description: string | null;
|
||||
owner_user_token: string;
|
||||
ip_address_creation: string;
|
||||
ip_address_update: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
// Soft-delete timestamp; null means live. The list includes deleted keys, so
|
||||
// the UI filters these out.
|
||||
maybe_deleted_at: string | null;
|
||||
}
|
||||
|
||||
// Create response: the `api_key_token` (used for all subsequent management) plus
|
||||
// the full secret `api_key`, returned exactly once.
|
||||
export interface CreatedApiKey {
|
||||
api_key_token: string;
|
||||
api_key: string;
|
||||
}
|
||||
|
||||
interface ErrorBody {
|
||||
success: boolean;
|
||||
error_code?: number;
|
||||
error_code_str?: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export class UserApiKeysApi extends ApiManager {
|
||||
public ListApiKeys({
|
||||
limit,
|
||||
offset,
|
||||
}: {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
} = {}): Promise<ApiResponse<{ api_keys: ApiKeyInfo[] }>> {
|
||||
const query = new URLSearchParams();
|
||||
if (limit !== undefined) query.set("limit", String(limit));
|
||||
if (offset !== undefined) query.set("offset", String(offset));
|
||||
const suffix = query.toString() ? `?${query.toString()}` : "";
|
||||
const endpoint = `${this.getApiSchemeAndHost()}/v1/api_keys/list${suffix}`;
|
||||
return this.jsonFetch<{
|
||||
success: boolean;
|
||||
api_keys?: ApiKeyInfo[];
|
||||
} & ErrorBody>(endpoint, { method: "GET" })
|
||||
.then((response) => {
|
||||
if (!response.success) {
|
||||
return {
|
||||
success: false,
|
||||
errorMessage: response.message ?? this.statusFallback(response),
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
data: { api_keys: response.api_keys ?? [] },
|
||||
};
|
||||
})
|
||||
.catch((err) => ({ success: false, errorMessage: err.message }));
|
||||
}
|
||||
|
||||
// Single-key lookup. Not currently used by the settings UI (the list already
|
||||
// carries everything), but provided for parity with the backend.
|
||||
public GetApiKey({
|
||||
token,
|
||||
}: {
|
||||
token: string;
|
||||
}): Promise<ApiResponse<ApiKeyInfo>> {
|
||||
const endpoint = `${this.getApiSchemeAndHost()}/v1/api_keys/${encodeURIComponent(token)}`;
|
||||
return this.jsonFetch<
|
||||
{ success: boolean; api_key?: ApiKeyInfo } & ErrorBody
|
||||
>(endpoint, { method: "GET" })
|
||||
.then((response) => {
|
||||
if (!response.success || !response.api_key) {
|
||||
return {
|
||||
success: false,
|
||||
errorMessage: response.message ?? this.statusFallback(response),
|
||||
};
|
||||
}
|
||||
return { success: true, data: response.api_key };
|
||||
})
|
||||
.catch((err) => ({ success: false, errorMessage: err.message }));
|
||||
}
|
||||
|
||||
public CreateApiKey({
|
||||
name,
|
||||
maybeDescription,
|
||||
}: {
|
||||
name: string;
|
||||
maybeDescription?: string;
|
||||
}): Promise<ApiResponse<CreatedApiKey>> {
|
||||
const endpoint = `${this.getApiSchemeAndHost()}/v1/api_keys/create`;
|
||||
return this.jsonFetch<
|
||||
{
|
||||
success: boolean;
|
||||
api_key_token?: string;
|
||||
api_key?: string;
|
||||
} & ErrorBody
|
||||
>(endpoint, {
|
||||
method: "POST",
|
||||
body: { name, maybe_description: maybeDescription ?? null },
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.success || !response.api_key_token || !response.api_key) {
|
||||
return {
|
||||
success: false,
|
||||
errorMessage: response.message ?? this.statusFallback(response),
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
api_key_token: response.api_key_token,
|
||||
api_key: response.api_key,
|
||||
},
|
||||
};
|
||||
})
|
||||
.catch((err) => ({ success: false, errorMessage: err.message }));
|
||||
}
|
||||
|
||||
public UpdateApiKey({
|
||||
token,
|
||||
maybeDescription,
|
||||
}: {
|
||||
token: string;
|
||||
maybeDescription: string | null;
|
||||
}): Promise<ApiResponse<null>> {
|
||||
const endpoint = `${this.getApiSchemeAndHost()}/v1/api_keys/${encodeURIComponent(token)}`;
|
||||
return this.jsonFetch<{ success: boolean } & ErrorBody>(endpoint, {
|
||||
method: "PUT",
|
||||
body: { maybe_description: maybeDescription },
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.success) {
|
||||
return {
|
||||
success: false,
|
||||
errorMessage: response.message ?? this.statusFallback(response),
|
||||
};
|
||||
}
|
||||
return { success: true };
|
||||
})
|
||||
.catch((err) => ({ success: false, errorMessage: err.message }));
|
||||
}
|
||||
|
||||
public DeleteApiKey({ token }: { token: string }): Promise<ApiResponse<null>> {
|
||||
const endpoint = `${this.getApiSchemeAndHost()}/v1/api_keys/${encodeURIComponent(token)}`;
|
||||
return this.jsonFetch<{ success: boolean } & ErrorBody>(endpoint, {
|
||||
method: "DELETE",
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.success) {
|
||||
return {
|
||||
success: false,
|
||||
errorMessage: response.message ?? this.statusFallback(response),
|
||||
};
|
||||
}
|
||||
return { success: true };
|
||||
})
|
||||
.catch((err) => ({ success: false, errorMessage: err.message }));
|
||||
}
|
||||
|
||||
// Parses JSON for both 2xx and 4xx so `BadInputWithSimpleMessage` text
|
||||
// reaches the caller. The base ApiManager.fetch throws on non-2xx.
|
||||
private async jsonFetch<T>(
|
||||
endpoint: string,
|
||||
{ method, body }: { method: string; body?: unknown },
|
||||
): Promise<T> {
|
||||
const response = await fetch(endpoint, {
|
||||
method,
|
||||
headers: buildSessionHeaders({
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
}),
|
||||
credentials: "include",
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
const text = await response.text();
|
||||
try {
|
||||
return JSON.parse(text) as T;
|
||||
} catch {
|
||||
throw new Error(text || `Request failed with status ${response.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
private statusFallback(response: ErrorBody): string {
|
||||
if (response.error_code_str) return response.error_code_str;
|
||||
if (response.error_code) return `Request failed (${response.error_code})`;
|
||||
return "Request failed";
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
export enum USER_FEATURE_FLAGS {
|
||||
API_KEY = "api_key",
|
||||
EXPLORE_MEDIA = "explore_media",
|
||||
REFERRALS = "referrals",
|
||||
STUDIO = "studio",
|
||||
|
||||
@@ -15,6 +15,6 @@
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/plugin-dialog": "^2.2.1"
|
||||
"@tauri-apps/plugin-dialog": "^2.7.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,6 @@
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.4.0"
|
||||
"@tauri-apps/api": "^2.11.0"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+106
-310
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user