mirror of
https://github.com/storytold/artcraft.git
synced 2026-11-19 16:15:04 +00:00
new sora login controls
This commit is contained in:
1 parent
2d44b92bfc
commit
b7dabdd6c7
10 files changed
+135
-598
No files matched your search
@@ -41,8 +41,7 @@ use crate::services::midjourney::commands::midjourney_open_login_command::midjou
|
||||
use crate::services::midjourney::state::midjourney_credential_manager::MidjourneyCredentialManager;
|
||||
use crate::services::sora::commands::check_sora_session_command::check_sora_session_command;
|
||||
use crate::services::sora::commands::open_sora_login_command::open_sora_login_command;
|
||||
use crate::services::sora::commands::sora_image_generation_command::sora_image_generation_command;
|
||||
use crate::services::sora::commands::sora_image_remix_command::sora_image_remix_command;
|
||||
use crate::services::sora::commands::sora_get_credential_info_command::sora_get_credential_info_command;
|
||||
use crate::services::sora::commands::sora_logout_command::sora_logout_command;
|
||||
use crate::services::sora::state::sora_credential_manager::SoraCredentialManager;
|
||||
use crate::services::sora::state::sora_task_queue::SoraTaskQueue;
|
||||
@@ -200,8 +199,7 @@ pub fn run() {
|
||||
platform_info_command,
|
||||
set_fal_api_key_command,
|
||||
set_provider_order_command,
|
||||
sora_image_generation_command,
|
||||
sora_image_remix_command,
|
||||
sora_get_credential_info_command,
|
||||
sora_logout_command,
|
||||
storyteller_get_credits_command,
|
||||
storyteller_get_subscription_command,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
pub mod check_sora_session_command;
|
||||
pub mod open_sora_login_command;
|
||||
pub mod sora_image_generation_command;
|
||||
pub mod sora_image_remix_command;
|
||||
pub mod sora_get_credential_info_command;
|
||||
pub mod sora_logout_command;
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
use crate::core::commands::response::shorthand::{Response, ResponseOrErrorMessage};
|
||||
use crate::core::commands::response::success_response_wrapper::SerializeMarker;
|
||||
use crate::services::fal::state::fal_credential_manager::FalCredentialManager;
|
||||
use crate::services::midjourney::state::midjourney_credential_manager::MidjourneyCredentialManager;
|
||||
use crate::services::sora::state::sora_credential_manager::SoraCredentialManager;
|
||||
use errors::AnyhowResult;
|
||||
use log::{error, info};
|
||||
use serde_derive::Serialize;
|
||||
use tauri::State;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct SoraGetCredentialInfoResponse {
|
||||
pub maybe_email: Option<String>,
|
||||
pub can_clear_state: bool,
|
||||
}
|
||||
|
||||
impl SerializeMarker for SoraGetCredentialInfoResponse {}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn sora_get_credential_info_command(
|
||||
sora_creds_manager: State<'_, SoraCredentialManager>,
|
||||
) -> ResponseOrErrorMessage<SoraGetCredentialInfoResponse> {
|
||||
info!("sora_get_credential_info_command called");
|
||||
|
||||
let info = get_info(&sora_creds_manager)
|
||||
.map_err(|err| {
|
||||
error!("Error getting info: {:?}", err);
|
||||
"error getting info"
|
||||
})?;
|
||||
|
||||
Ok(info.into())
|
||||
}
|
||||
|
||||
fn get_info(
|
||||
sora_creds_manager: &SoraCredentialManager,
|
||||
) -> AnyhowResult<SoraGetCredentialInfoResponse> {
|
||||
|
||||
let maybe_creds = sora_creds_manager.get_credentials()?;
|
||||
|
||||
let mut can_clear_state = maybe_creds.is_some();
|
||||
let mut maybe_email = None;
|
||||
|
||||
if let Some(creds) = maybe_creds {
|
||||
if let Some(jwt) = &creds.jwt_bearer_token {
|
||||
maybe_email = Some(jwt.jwt_claims().email.clone());
|
||||
}
|
||||
|
||||
// TODO: This was cargo culted from Midjourney. Probably not quite right.
|
||||
// We probably need an Option<T> for cookie rather than an empty / partial string as
|
||||
// well as timestamps, invalidation states, etc.
|
||||
if creds.jwt_bearer_token.is_none() && creds.sora_sentinel.is_none() {
|
||||
can_clear_state = false;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(SoraGetCredentialInfoResponse {
|
||||
maybe_email,
|
||||
can_clear_state,
|
||||
})
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
use crate::core::state::data_dir::app_data_root::AppDataRoot;
|
||||
use crate::services::sora::state::read_sora_credentials_from_disk::read_sora_credentials_from_disk;
|
||||
use crate::services::sora::state::sora_credential_holder::SoraCredentialHolder;
|
||||
use base64::prelude::BASE64_STANDARD;
|
||||
use base64::Engine;
|
||||
use errors::AnyhowResult;
|
||||
use log::{error, info};
|
||||
use openai_sora_client::requests::image_gen::common::{ImageSize, NumImages};
|
||||
use openai_sora_client::requests::image_gen::sora_image_gen_remix::{sora_image_gen_remix, SoraImageGenRemixRequest};
|
||||
use openai_sora_client::requests::upload::upload_media_from_bytes::sora_media_upload_from_bytes;
|
||||
use std::time::Duration;
|
||||
use tauri::{AppHandle, State};
|
||||
|
||||
const SORA_IMAGE_UPLOAD_TIMEOUT: Duration = Duration::from_millis(1000 * 30); // 30 seconds
|
||||
|
||||
const SORA_IMAGE_REMIX_TIMEOUT: Duration = Duration::from_millis(1000 * 30); // 30 seconds
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn sora_image_generation_command(
|
||||
prompt: &str,
|
||||
image: Option<&str>,
|
||||
_app: AppHandle,
|
||||
app_data_root: State<'_, AppDataRoot>,
|
||||
sora_creds_holder: State<'_, SoraCredentialHolder>,
|
||||
) -> Result<String, String> {
|
||||
info!("image_generation_command called; processing image...");
|
||||
|
||||
generate_image(image, prompt, &app_data_root, &sora_creds_holder)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
error!("error: {:?}", err);
|
||||
"there was an error".to_string()
|
||||
})?;
|
||||
|
||||
Ok("success".to_string())
|
||||
}
|
||||
|
||||
pub async fn generate_image(
|
||||
maybe_image: Option<&str>,
|
||||
prompt: &str,
|
||||
app_data_root: &AppDataRoot,
|
||||
sora_creds_holder: &SoraCredentialHolder,
|
||||
) -> AnyhowResult<()> {
|
||||
|
||||
let creds = read_sora_credentials_from_disk(app_data_root)
|
||||
.map_err(|err| {
|
||||
error!("Failed to read Sora credentials from disk: {:?}", err);
|
||||
err
|
||||
})?;
|
||||
|
||||
let mut sora_media_tokens = vec![];
|
||||
|
||||
if let Some(image) = maybe_image {
|
||||
let image_bytes = BASE64_STANDARD.decode(image)?;
|
||||
|
||||
let filename = "image.png".to_string();
|
||||
|
||||
|
||||
let response = sora_media_upload_from_bytes(
|
||||
image_bytes,
|
||||
filename,
|
||||
&creds,
|
||||
Some(SORA_IMAGE_UPLOAD_TIMEOUT))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
error!("Failed to upload image to Sora: {:?}", err);
|
||||
err
|
||||
})?;
|
||||
|
||||
sora_media_tokens.push(response.id);
|
||||
}
|
||||
|
||||
let response = sora_image_gen_remix(SoraImageGenRemixRequest {
|
||||
prompt: prompt.to_string(),
|
||||
num_images: NumImages::One,
|
||||
image_size: ImageSize::Square,
|
||||
sora_media_tokens: sora_media_tokens.clone(),
|
||||
credentials: &creds,
|
||||
request_timeout: Some(SORA_IMAGE_REMIX_TIMEOUT),
|
||||
}).await
|
||||
.map_err(|err| {
|
||||
error!("Failed to call Sora image generation: {:?}", err);
|
||||
err
|
||||
})?;
|
||||
|
||||
println!(">> TASK ID: {:?} ", response.task_id);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,312 +0,0 @@
|
||||
use crate::core::commands::response::failure_response_wrapper::{CommandErrorResponseWrapper, CommandErrorStatus};
|
||||
use crate::core::commands::response::shorthand::Response;
|
||||
use crate::core::events::basic_sendable_event_trait::BasicSendableEvent;
|
||||
use crate::core::events::generation_events::common::{GenerationAction, GenerationServiceProvider};
|
||||
use crate::core::events::generation_events::generation_enqueue_failure_event::GenerationEnqueueFailureEvent;
|
||||
use crate::core::events::generation_events::generation_enqueue_success_event::GenerationEnqueueSuccessEvent;
|
||||
use crate::core::events::sendable_event_trait::SendableEvent;
|
||||
use crate::core::state::app_env_configs::app_env_configs::AppEnvConfigs;
|
||||
use crate::core::state::data_dir::app_data_root::AppDataRoot;
|
||||
use crate::core::state::data_dir::trait_data_subdir::DataSubdir;
|
||||
use crate::core::utils::get_url_file_extension::get_url_file_extension;
|
||||
use crate::core::utils::simple_http_download::simple_http_download;
|
||||
use crate::services::sora::state::sora_credential_manager::SoraCredentialManager;
|
||||
use crate::services::sora::state::sora_task_queue::SoraTaskQueue;
|
||||
use errors::AnyhowError;
|
||||
use log::{error, info, warn};
|
||||
use openai_sora_client::error::sora_error::SoraError;
|
||||
use openai_sora_client::error::sora_specific_api_error::SoraSpecificApiError;
|
||||
use openai_sora_client::recipes::image_remix_with_session_auto_renew::{image_remix_with_session_auto_renew, ImageRemixAutoRenewRequest};
|
||||
use openai_sora_client::recipes::image_upload_from_file_with_session_auto_renew::{image_upload_from_file_with_session_auto_renew, ImageUploadFromFileAutoRenewRequest};
|
||||
use openai_sora_client::recipes::maybe_upgrade_or_renew_session::maybe_upgrade_or_renew_session;
|
||||
use openai_sora_client::requests::image_gen::common::{ImageSize, NumImages};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
use storyteller_client::endpoints::media_files::get_media_file::get_media_file;
|
||||
use storyteller_client::error::storyteller_error::StorytellerError;
|
||||
use tauri::{AppHandle, Manager, State};
|
||||
use tokens::tokens::media_files::MediaFileToken;
|
||||
|
||||
const SORA_IMAGE_UPLOAD_TIMEOUT: Duration = Duration::from_millis(1000 * 30); // 30 seconds
|
||||
|
||||
const SORA_IMAGE_REMIX_TIMEOUT: Duration = Duration::from_millis(1000 * 30); // 30 seconds
|
||||
|
||||
const DEFAULT_ASPECT_RATIO : SoraAspectRatio = SoraAspectRatio::Square;
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct SoraImageRemixCommand {
|
||||
/// Image media file; the engine or canvas snapshot (screenshot).
|
||||
pub snapshot_media_token: MediaFileToken,
|
||||
|
||||
/// The user's image generation prompt.
|
||||
pub prompt: String,
|
||||
|
||||
/// Turn off the system prompt.
|
||||
pub disable_system_prompt: Option<bool>,
|
||||
|
||||
/// Additional images to include (optional). Up to nine images.
|
||||
pub maybe_additional_images: Option<Vec<MediaFileToken>>,
|
||||
|
||||
pub maybe_number_of_samples: Option<u32>,
|
||||
|
||||
/// Aspect ratio.
|
||||
pub aspect_ratio: Option<SoraAspectRatio>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Copy, Clone)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SoraAspectRatio {
|
||||
Square,
|
||||
Wide,
|
||||
Tall,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SoraImageRemixErrorType {
|
||||
/// Generic server error
|
||||
ServerError,
|
||||
/// The user is sending too many requests
|
||||
TooManyConcurrentTasks,
|
||||
/// User is not logged into Sora!
|
||||
SoraLoginRequired,
|
||||
/// The user needs to create a Sora account
|
||||
SoraUsernameNotYetCreated,
|
||||
/// The Sora service is having problems. Try again soon.
|
||||
SoraIsHavingProblems,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn sora_image_remix_command(
|
||||
app: AppHandle,
|
||||
request: SoraImageRemixCommand,
|
||||
app_env_configs: State<'_, AppEnvConfigs>,
|
||||
app_data_root: State<'_, AppDataRoot>,
|
||||
sora_creds_manager: State<'_, SoraCredentialManager>,
|
||||
sora_task_queue: State<'_, SoraTaskQueue>,
|
||||
) -> Response<(), SoraImageRemixErrorType, ()> {
|
||||
|
||||
info!("image_generation_command called; scene media token: {:?}, additional images: {:?}, full request: {:?}",
|
||||
&request.snapshot_media_token, &request.maybe_additional_images, &request);
|
||||
|
||||
// TODO(bt,2025-04-24): Better error messages to caller
|
||||
|
||||
let has_credentials = sora_creds_manager
|
||||
.has_apparently_complete_credentials()
|
||||
.unwrap_or(true); // NB: Failures would be lock issues
|
||||
|
||||
if !has_credentials {
|
||||
warn!("No apparently completed credentials found");
|
||||
|
||||
let error_message = "You need to log into Sora to continue. See the settings menu.";
|
||||
|
||||
let event = GenerationEnqueueFailureEvent {
|
||||
action: GenerationAction::GenerateImage,
|
||||
service: GenerationServiceProvider::Sora,
|
||||
model: None,
|
||||
reason: Some(error_message.to_string()),
|
||||
};
|
||||
|
||||
if let Err(err) = event.send(&app) {
|
||||
error!("Failed to emit event: {:?}", err); // Fail open.
|
||||
}
|
||||
|
||||
return Err(CommandErrorResponseWrapper {
|
||||
status: CommandErrorStatus::Unauthorized,
|
||||
error_message: Some(error_message.to_string()),
|
||||
error_type: Some(SoraImageRemixErrorType::SoraLoginRequired),
|
||||
error_details: None,
|
||||
});
|
||||
}
|
||||
|
||||
let result = generate_image(
|
||||
request,
|
||||
&app_env_configs,
|
||||
&app_data_root,
|
||||
&sora_creds_manager,
|
||||
&sora_task_queue
|
||||
).await;
|
||||
|
||||
match result {
|
||||
Err(err) => {
|
||||
error!("Sora image remix error: {:?}", err);
|
||||
|
||||
let mut status = CommandErrorStatus::ServerError;
|
||||
let mut error_type = SoraImageRemixErrorType::ServerError;
|
||||
let mut error_message = "An error occurred. Please try again. If it continues, please tell our staff about the problem.";
|
||||
|
||||
match (err) {
|
||||
InnerError::SoraError(SoraError::ApiSpecific(SoraSpecificApiError::TooManyConcurrentTasks)) => {
|
||||
error_type = SoraImageRemixErrorType::TooManyConcurrentTasks;
|
||||
status = CommandErrorStatus::ServerError;
|
||||
error_message = "You have too many Sora image generation tasks running. Please wait a moment.";
|
||||
},
|
||||
InnerError::SoraError(SoraError::ApiSpecific(SoraSpecificApiError::SoraUsernameNotYetCreated)) => {
|
||||
error_type = SoraImageRemixErrorType::SoraUsernameNotYetCreated;
|
||||
status = CommandErrorStatus::BadRequest;
|
||||
error_message = "Your Sora username is not yet created. Please visit the Sora.com website to create it first.";
|
||||
},
|
||||
InnerError::SoraError(err) => {
|
||||
if err.is_sora_having_downtime_issues() {
|
||||
error_type = SoraImageRemixErrorType::SoraIsHavingProblems;
|
||||
status = CommandErrorStatus::ServerError;
|
||||
error_message = "Sora is having problems. Please try again later.";
|
||||
}
|
||||
}
|
||||
_ => {},
|
||||
}
|
||||
|
||||
let event = GenerationEnqueueFailureEvent {
|
||||
action: GenerationAction::GenerateImage,
|
||||
service: GenerationServiceProvider::Sora,
|
||||
model: None,
|
||||
reason: Some(error_message.to_string()),
|
||||
};
|
||||
|
||||
if let Err(err) = event.send(&app) {
|
||||
error!("Failed to emit event: {:?}", err); // Fail open.
|
||||
}
|
||||
|
||||
Err(CommandErrorResponseWrapper {
|
||||
status,
|
||||
error_message: Some(error_message.to_string()),
|
||||
error_type: Some(error_type),
|
||||
error_details: None,
|
||||
})
|
||||
}
|
||||
Ok(_) => {
|
||||
let event = GenerationEnqueueSuccessEvent {
|
||||
action: GenerationAction::GenerateImage,
|
||||
service: GenerationServiceProvider::Sora,
|
||||
model: None,
|
||||
};
|
||||
|
||||
if let Err(err) = event.send(&app) {
|
||||
error!("Failed to emit event: {:?}", err); // Fail open.
|
||||
}
|
||||
|
||||
Ok(().into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum InnerError {
|
||||
SoraError(SoraError),
|
||||
AnyhowError(AnyhowError),
|
||||
StorytellerError(StorytellerError),
|
||||
}
|
||||
|
||||
impl From<AnyhowError> for InnerError {
|
||||
fn from(value: AnyhowError) -> Self {
|
||||
Self::AnyhowError(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SoraError> for InnerError {
|
||||
fn from(value: SoraError) -> Self {
|
||||
Self::SoraError(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<StorytellerError> for InnerError {
|
||||
fn from(value: StorytellerError) -> Self {
|
||||
Self::StorytellerError(value)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn generate_image(
|
||||
request: SoraImageRemixCommand,
|
||||
app_env_configs: &AppEnvConfigs,
|
||||
app_data_root: &AppDataRoot,
|
||||
sora_creds_manager: &SoraCredentialManager,
|
||||
sora_task_queue: &SoraTaskQueue,
|
||||
) -> Result<(), InnerError> {
|
||||
|
||||
let response = get_media_file(
|
||||
&app_env_configs.storyteller_host,
|
||||
&request.snapshot_media_token
|
||||
).await?;
|
||||
|
||||
let media_file_url = &response.media_file.media_links.cdn_url;
|
||||
let extension_with_dot = get_url_file_extension(media_file_url)
|
||||
.map(|ext| format!(".{}", ext))
|
||||
.unwrap_or_else(|| ".png".to_string());
|
||||
|
||||
let filename = format!("{}{}", response.media_file.token.as_str(), extension_with_dot);
|
||||
let filename = app_data_root.downloads_dir().path().join(&filename);
|
||||
|
||||
simple_http_download(&media_file_url, &filename).await?;
|
||||
|
||||
let files_to_upload = vec![filename];
|
||||
|
||||
let mut creds = sora_creds_manager.get_credentials_required()?;
|
||||
|
||||
let credential_updated = maybe_upgrade_or_renew_session(&mut creds)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
error!("Failed to upgrade or renew session: {:?}", err);
|
||||
err
|
||||
})?;
|
||||
|
||||
if credential_updated {
|
||||
info!("Storing updated credentials");
|
||||
sora_creds_manager.set_credentials(&creds)?;
|
||||
}
|
||||
|
||||
let mut sora_media_tokens = Vec::with_capacity(files_to_upload.len());
|
||||
|
||||
for (i, file_path) in files_to_upload.iter().enumerate() {
|
||||
info!("Uploading image {} of {}...", (i+1), files_to_upload.len());
|
||||
|
||||
let (response, maybe_new_credentials) =
|
||||
image_upload_from_file_with_session_auto_renew(ImageUploadFromFileAutoRenewRequest {
|
||||
file_path,
|
||||
credentials: &creds,
|
||||
request_timeout: Some(SORA_IMAGE_UPLOAD_TIMEOUT),
|
||||
}).await?;
|
||||
|
||||
if let Some(new_creds) = maybe_new_credentials {
|
||||
info!("Storing updated credentials.");
|
||||
sora_creds_manager.set_credentials(&new_creds)?;
|
||||
creds = new_creds;
|
||||
}
|
||||
|
||||
sora_media_tokens.push(response.id);
|
||||
}
|
||||
|
||||
let aspect_ratio = request.aspect_ratio.unwrap_or(DEFAULT_ASPECT_RATIO);
|
||||
|
||||
let aspect_ratio = match aspect_ratio {
|
||||
SoraAspectRatio::Square => ImageSize::Square,
|
||||
SoraAspectRatio::Wide => ImageSize::Wide,
|
||||
SoraAspectRatio::Tall => ImageSize::Tall,
|
||||
};
|
||||
|
||||
info!("Calling image generation...");
|
||||
|
||||
// TODO(bt,2025-04-21): Download media tokens.
|
||||
// Note: This is incredibly inefficient. We should keep a local cache.
|
||||
// Also, if they've already been uploaded to OpenAI, we shouldn't continue to re-upload.
|
||||
|
||||
let (response, maybe_new_creds) =
|
||||
image_remix_with_session_auto_renew(ImageRemixAutoRenewRequest {
|
||||
prompt: request.prompt.to_string(),
|
||||
num_images: NumImages::One,
|
||||
image_size: aspect_ratio,
|
||||
sora_media_tokens: sora_media_tokens.clone(),
|
||||
credentials: &creds,
|
||||
request_timeout: Some(SORA_IMAGE_REMIX_TIMEOUT),
|
||||
}).await?;
|
||||
|
||||
if let Some(new_creds) = maybe_new_creds {
|
||||
info!("Storing updated credentials.");
|
||||
sora_creds_manager.set_credentials(&new_creds)?;
|
||||
}
|
||||
|
||||
info!("New Sora Task ID: {:?} ", response.task_id);
|
||||
|
||||
sora_task_queue.insert(&response.task_id)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+9
-9
@@ -32,15 +32,6 @@ export const MidjourneyAccountBlock = () => {
|
||||
fetchSession();
|
||||
});
|
||||
|
||||
const handleMidjourneyButton = async () => {
|
||||
if (midjourneySession?.payload?.can_clear_state) {
|
||||
await clearState();
|
||||
setMidjourneySession(undefined);
|
||||
} else {
|
||||
await openLogin();
|
||||
}
|
||||
};
|
||||
|
||||
const clearState = async() => {
|
||||
try {
|
||||
await invoke("midjourney_clear_credentials_command");
|
||||
@@ -57,6 +48,15 @@ export const MidjourneyAccountBlock = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const handleMidjourneyButton = async () => {
|
||||
if (midjourneySession?.payload?.can_clear_state) {
|
||||
await clearState();
|
||||
setMidjourneySession(undefined);
|
||||
} else {
|
||||
await openLogin();
|
||||
}
|
||||
};
|
||||
|
||||
return(
|
||||
<div className="flex justify-between items-center">
|
||||
<span>Midjourney Account:</span>
|
||||
|
||||
+46
-70
@@ -3,99 +3,75 @@ import { Button } from "@storyteller/ui-button";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faSpinnerThird } from "@fortawesome/pro-solid-svg-icons";
|
||||
import {
|
||||
CheckSoraSession,
|
||||
SoraGetCredentialInfo,
|
||||
SoraSessionState,
|
||||
LogoutSoraSession,
|
||||
useSoraLoginListener,
|
||||
CheckSoraSessionResult,
|
||||
SoraGetCredentialInfoSuccess,
|
||||
} from "@storyteller/tauri-api";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { RefreshAccountStateEvent, useRefreshAccountStateEvent } from "libs/tauri-events/src/lib/events/functional/RefreshAccountStateEvent";
|
||||
|
||||
const DEFAULT_CACHE_TTL_MS = 1 * 60 * 1000; // 1 minute
|
||||
|
||||
interface SoraAccountBlockProps {
|
||||
cacheKey?: string;
|
||||
cacheTtlMs?: number;
|
||||
}
|
||||
|
||||
export const SoraAccountBlock = ({
|
||||
cacheKey = "soraSettingsSessionCache",
|
||||
cacheTtlMs = DEFAULT_CACHE_TTL_MS,
|
||||
}: SoraAccountBlockProps) => {
|
||||
const [soraSession, setSoraSession] = useState<CheckSoraSessionResult| undefined>(undefined);
|
||||
export const SoraAccountBlock = () => {
|
||||
const [soraSession, setSoraSession] = useState<SoraGetCredentialInfoSuccess| undefined>(undefined);
|
||||
const [isCheckingSoraSession, setIsCheckingSoraSession] = useState(false);
|
||||
|
||||
useSoraLoginListener(() => {
|
||||
const fetchSession = async () => {
|
||||
setIsCheckingSoraSession(true);
|
||||
CheckSoraSession()
|
||||
.then((result) => {
|
||||
setSoraSession(result);
|
||||
localStorage.setItem(
|
||||
cacheKey,
|
||||
JSON.stringify({ session: result, timestamp: Date.now() })
|
||||
);
|
||||
})
|
||||
.finally(() => setIsCheckingSoraSession(false));
|
||||
});
|
||||
try {
|
||||
const result = await SoraGetCredentialInfo();
|
||||
setSoraSession(result);
|
||||
} catch (e) {
|
||||
console.error("Error fetching Sora session", e);
|
||||
setSoraSession(undefined);
|
||||
} finally {
|
||||
setIsCheckingSoraSession(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const fetchSession = async () => {
|
||||
setIsCheckingSoraSession(true);
|
||||
try {
|
||||
const cached = localStorage.getItem(cacheKey);
|
||||
if (cached) {
|
||||
const { session, timestamp } = JSON.parse(cached);
|
||||
if (Date.now() - timestamp < cacheTtlMs) {
|
||||
setSoraSession(session);
|
||||
setIsCheckingSoraSession(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const result = await CheckSoraSession();
|
||||
setSoraSession(result);
|
||||
localStorage.setItem(
|
||||
cacheKey,
|
||||
JSON.stringify({ session: result, timestamp: Date.now() })
|
||||
);
|
||||
} catch (e) {
|
||||
console.error("Error fetching Sora session", e);
|
||||
setSoraSession(undefined);
|
||||
} finally {
|
||||
setIsCheckingSoraSession(false);
|
||||
}
|
||||
};
|
||||
fetchSession();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [cacheKey, cacheTtlMs]);
|
||||
}, []);
|
||||
|
||||
useRefreshAccountStateEvent(async (event: RefreshAccountStateEvent) => {
|
||||
fetchSession();
|
||||
});
|
||||
|
||||
const clearState = async() => {
|
||||
try {
|
||||
await LogoutSoraSession();
|
||||
//await invoke("sora_clear_credentials_command"); // TODO: Wrong command name
|
||||
} catch (e) {
|
||||
console.error("Error clearing Sora credentials", e);
|
||||
}
|
||||
}
|
||||
|
||||
const openLogin = async() => {
|
||||
try {
|
||||
await invoke("open_sora_login_command");
|
||||
} catch (e) {
|
||||
console.error("Error opening Sora login", e);
|
||||
}
|
||||
}
|
||||
|
||||
const handleSoraButton = async () => {
|
||||
if (isCheckingSoraSession) return;
|
||||
if (soraSession?.state === SoraSessionState.Valid) {
|
||||
setIsCheckingSoraSession(true);
|
||||
await LogoutSoraSession();
|
||||
setSoraSession({state: SoraSessionState.NotSetUp});
|
||||
localStorage.removeItem(cacheKey);
|
||||
setIsCheckingSoraSession(false);
|
||||
if (soraSession?.payload?.can_clear_state) {
|
||||
await clearState();
|
||||
setSoraSession(undefined);
|
||||
} else {
|
||||
setIsCheckingSoraSession(true);
|
||||
try {
|
||||
await invoke("open_sora_login_command");
|
||||
} catch (e) {
|
||||
} finally {
|
||||
setIsCheckingSoraSession(false);
|
||||
}
|
||||
await openLogin();
|
||||
}
|
||||
};
|
||||
|
||||
return(
|
||||
<div className="flex justify-between items-center">
|
||||
<span>OpenAI / Sora Account:</span>
|
||||
<pre>{soraSession?.maybe_account_email || ""}</pre>
|
||||
<pre>{soraSession?.payload?.maybe_email || "Not logged in"}</pre>
|
||||
<Button
|
||||
variant={
|
||||
soraSession?.state === SoraSessionState.Valid && !isCheckingSoraSession
|
||||
soraSession?.payload?.can_clear_state && !isCheckingSoraSession
|
||||
? "destructive"
|
||||
: soraSession?.state === SoraSessionState.NotSetUp
|
||||
: soraSession?.payload?.can_clear_state
|
||||
? "primary"
|
||||
: "secondary"
|
||||
}
|
||||
@@ -108,7 +84,7 @@ export const SoraAccountBlock = ({
|
||||
icon={faSpinnerThird}
|
||||
className="animate-spin text-sm"
|
||||
/>
|
||||
) : soraSession?.state === SoraSessionState.Valid ? (
|
||||
) : soraSession?.payload?.can_clear_state ? (
|
||||
"Disconnect"
|
||||
) : (
|
||||
"Connect"
|
||||
|
||||
-112
@@ -1,112 +0,0 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@storyteller/ui-button";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faSpinnerThird } from "@fortawesome/pro-solid-svg-icons";
|
||||
import {
|
||||
CheckSoraSession,
|
||||
SoraSessionState,
|
||||
LogoutSoraSession,
|
||||
useSoraLoginListener,
|
||||
} from "@storyteller/tauri-api";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
|
||||
interface SoraAccountButtonProps {
|
||||
cacheKey?: string;
|
||||
cacheTtlMs?: number;
|
||||
}
|
||||
|
||||
export const SoraAccountButton = ({
|
||||
cacheKey = "soraSettingsSessionCache",
|
||||
cacheTtlMs = 5 * 60 * 1000,
|
||||
}: SoraAccountButtonProps) => {
|
||||
const [soraSession, setSoraSession] = useState<SoraSessionState | null>(null);
|
||||
const [isCheckingSoraSession, setIsCheckingSoraSession] = useState(false);
|
||||
|
||||
useSoraLoginListener(() => {
|
||||
setIsCheckingSoraSession(true);
|
||||
CheckSoraSession()
|
||||
.then((result) => {
|
||||
setSoraSession(result.state);
|
||||
localStorage.setItem(
|
||||
cacheKey,
|
||||
JSON.stringify({ state: result.state, timestamp: Date.now() })
|
||||
);
|
||||
})
|
||||
.finally(() => setIsCheckingSoraSession(false));
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const fetchSession = async () => {
|
||||
setIsCheckingSoraSession(true);
|
||||
try {
|
||||
const cached = localStorage.getItem(cacheKey);
|
||||
if (cached) {
|
||||
const { state, timestamp } = JSON.parse(cached);
|
||||
if (Date.now() - timestamp < cacheTtlMs) {
|
||||
setSoraSession(state);
|
||||
setIsCheckingSoraSession(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const result = await CheckSoraSession();
|
||||
setSoraSession(result.state);
|
||||
localStorage.setItem(
|
||||
cacheKey,
|
||||
JSON.stringify({ state: result.state, timestamp: Date.now() })
|
||||
);
|
||||
} catch (e) {
|
||||
console.error("Error fetching Sora session", e);
|
||||
setSoraSession(null);
|
||||
} finally {
|
||||
setIsCheckingSoraSession(false);
|
||||
}
|
||||
};
|
||||
fetchSession();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [cacheKey, cacheTtlMs]);
|
||||
|
||||
const handleSoraButton = async () => {
|
||||
if (isCheckingSoraSession) return;
|
||||
if (soraSession === SoraSessionState.Valid) {
|
||||
setIsCheckingSoraSession(true);
|
||||
await LogoutSoraSession();
|
||||
setSoraSession(SoraSessionState.NotSetUp);
|
||||
localStorage.removeItem(cacheKey);
|
||||
setIsCheckingSoraSession(false);
|
||||
} else {
|
||||
setIsCheckingSoraSession(true);
|
||||
try {
|
||||
await invoke("open_sora_login_command");
|
||||
} catch (e) {
|
||||
} finally {
|
||||
setIsCheckingSoraSession(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant={
|
||||
soraSession === SoraSessionState.Valid && !isCheckingSoraSession
|
||||
? "destructive"
|
||||
: soraSession === SoraSessionState.NotSetUp
|
||||
? "primary"
|
||||
: "secondary"
|
||||
}
|
||||
className="h-[30px]"
|
||||
onClick={handleSoraButton}
|
||||
disabled={isCheckingSoraSession}
|
||||
>
|
||||
{isCheckingSoraSession ? (
|
||||
<FontAwesomeIcon
|
||||
icon={faSpinnerThird}
|
||||
className="animate-spin text-sm"
|
||||
/>
|
||||
) : soraSession === SoraSessionState.Valid ? (
|
||||
"Disconnect"
|
||||
) : (
|
||||
"Connect"
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
@@ -25,6 +25,7 @@ export * from "./lib/settings/GetAppPreferences.js";
|
||||
export * from "./lib/settings/UpdateAppPreference.js";
|
||||
export * from "./lib/sora/CheckSoraSession.js";
|
||||
export * from "./lib/sora/LogoutSoraSession.js";
|
||||
export * from "./lib/sora/SoraGetCredentialInfo.js";
|
||||
export * from "./lib/sora/SoraImageRemix.js";
|
||||
export * from "./lib/sora/useSoraLoginListener.js";
|
||||
export * from "./lib/sora/waitForSoraLogin.js";
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { CommandResult } from "../common/CommandStatus";
|
||||
|
||||
export interface SoraGetCredentialInfoPayload {
|
||||
maybe_email?: string;
|
||||
can_clear_state: boolean;
|
||||
}
|
||||
|
||||
export interface SoraGetCredentialInfoSuccess extends CommandResult {
|
||||
payload: SoraGetCredentialInfoPayload;
|
||||
}
|
||||
|
||||
export const SoraGetCredentialInfo = async (): Promise<SoraGetCredentialInfoSuccess> => {
|
||||
const result = await invoke("sora_get_credential_info_command");
|
||||
return result as SoraGetCredentialInfoSuccess;
|
||||
};
|
||||
Reference in new issue
Block a user