session endpoint

This commit is contained in:
Brandon Thomas committed 2025-05-30 09:21:43 -04:00
1 parent 855463f9d8
commit eb2969cfd8
8 files changed
+70 -37

No files matched your search

Generated
-1
View File
@@ -6847,7 +6847,6 @@ dependencies = [
"filesys",
"hex-literal",
"idempotency",
"jwt_light",
"log",
"once_cell",
"rand 0.9.1",
@@ -20,7 +20,6 @@ workspace-build-acceleration = { workspace = true }
crockford = { path = "../../data/crockford" }
errors = { path = "../../errors" }
idempotency = { path = "../../idempotency" }
jwt_light = { workspace = true }
subprocess_common = { path = "../../subprocess_common" }
# External
@@ -1,6 +1,4 @@
use crate::creds::jwt_bearer_token::JwtBearerToken;
use crate::creds::openart_cookies::OpenArtCookies;
use crate::error::api_error::ApiError;
#[derive(Clone)]
pub struct OpenArtCredentials {
@@ -1,10 +1,13 @@
use jwt_light::error::JwtError;
use reqwest::StatusCode;
use std::error::Error;
use std::fmt::{Display, Formatter};
#[derive(Debug)]
pub enum ApiError {
/// Session endpoint did not return a valid session id.
/// Specifically for calls to https://openart.ai/api/auth/session
InvalidSession,
/// An error that occurred as or after the request was sent.
ReqwestError(reqwest::Error),
@@ -18,7 +21,7 @@ pub enum ApiError {
impl Display for ApiError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ApiError::JwtError(err) => write!(f, "JwtError: {}", err),
ApiError::InvalidSession => write!(f, "Invalid session: no session id returned from the server"),
ApiError::ReqwestError(err) => write!(f, "ReqwestError: {}", err),
ApiError::UncategorizedBadResponse { status_code, message } => {
write!(f, "UncategorizedBadResponse: {:?} : {}", status_code, message)
@@ -28,9 +31,3 @@ impl Display for ApiError {
}
impl Error for ApiError {}
impl From<JwtError> for ApiError {
fn from(err: JwtError) -> Self {
ApiError::JwtError(err)
}
}
@@ -1,4 +1,5 @@
use crate::error::api_error::ApiError;
use crate::error::classify_http_error_status_code_and_body::classify_http_error_status_code_and_body;
use crate::error::openart_error::OpenArtError;
/// This assumes the request failed and returned a non-200.
@@ -10,7 +11,5 @@ pub async fn classify_http_error_response(response: reqwest::Response) -> OpenAr
Err(err) => return OpenArtError::Api(ApiError::ReqwestError(err)),
};
// TODO: Handle various error messages from the API.
OpenArtError::Api(ApiError::UncategorizedBadResponse { status_code: status, message })
classify_http_error_status_code_and_body(status, &message).await
}
@@ -0,0 +1,14 @@
use crate::error::api_error::ApiError;
use crate::error::openart_error::OpenArtError;
use reqwest::StatusCode;
/// This assumes the request failed and returned a non-200.
/// The caller should check.
pub async fn classify_http_error_status_code_and_body(status: StatusCode, body: &str) -> OpenArtError {
let message = body.to_string();
// TODO: Handle various error messages from the API.
OpenArtError::Api(ApiError::UncategorizedBadResponse { status_code: status, message })
}
@@ -1,4 +1,5 @@
pub mod api_error;
pub mod classify_http_error_response;
pub mod client_error;
pub mod openart_error;
pub mod openart_error;
pub mod classify_http_error_status_code_and_body;
@@ -16,16 +16,22 @@ curl 'https://openart.ai/api/auth/session' --compressed
-H 'Cache-Control: no-cache'
-H 'TE: trailers'
*/
use log::{error, info};
use crate::creds::openart_credentials::OpenArtCredentials;
use crate::error::openart_error::OpenArtError;
use reqwest::Client;
use crate::error::api_error::ApiError;
use crate::error::classify_http_error_status_code_and_body::classify_http_error_status_code_and_body;
use crate::error::client_error::ClientError;
use crate::error::openart_error::OpenArtError;
use log::{debug, error, info};
use reqwest::Client;
const SESSION_URL : &str = "https://openart.ai/api/auth/session";
pub async fn get_session_request(creds: &OpenArtCredentials) -> Result<String, OpenArtError> {
#[derive(Debug, Clone)]
pub struct SessionDetails {
pub session_id: String,
}
pub async fn get_session_request(creds: &OpenArtCredentials) -> Result<SessionDetails, OpenArtError> {
let cookies = match creds.cookies.as_ref() {
Some(cookies) => cookies,
@@ -34,7 +40,7 @@ pub async fn get_session_request(creds: &OpenArtCredentials) -> Result<String, O
return Err(ClientError::NoCookiesInCredentials.into());
}
};
let client = Client::builder()
.gzip(true)
.build()
@@ -43,7 +49,7 @@ pub async fn get_session_request(creds: &OpenArtCredentials) -> Result<String, O
OpenArtError::Client(ClientError::ReqwestError(err))
})?;
info!("Getting session info from cookies... (cookie payload length: {})", cookies.as_str().len());
info!("Getting session details from cookies... (cookie payload length: {})", cookies.as_str().len());
let mut http_request= client.get(SESSION_URL)
.header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:137.0) Gecko/20100101 Firefox/137.0")
@@ -64,25 +70,45 @@ pub async fn get_session_request(creds: &OpenArtCredentials) -> Result<String, O
let response_body = &response.text()
.await
.map_err(|err| {
error!("Error reading body while attempting to generate bearer token: {:?}", err);
error!("Error reading body while attempting to read session details: {:?}", err);
ApiError::ReqwestError(err)
})?;
if !status.is_success() {
error!("Failed to generate bearer token with session cookies: {} ; body = {}", status, response_body);
let error = classify_general_http_status_code_and_body(status, &response_body).await;
error!("Failed to get session details: {} ; body = {}", status, response_body);
let error = classify_http_error_status_code_and_body(status, &response_body).await;
return Err(error);
}
debug!("Bearer token generation response was 200.");
debug!("Auth Response: {}", response_body);
if response_body == "null" {
error!("Failed to generate bearer token. Response was the string `null`.");
return Err(SoraError::FailedToGenerateBearer)
}
let auth_response: SoraAuthResponse = serde_json::from_str(&response_body)?;
Ok(auth_response.access_token)
debug!("Session info response was 200. Body: {}", response_body);
if response_body.is_empty() || response_body == "{}" {
error!("Received empty response body when requesting session details.");
return Err(OpenArtError::Api(ApiError::InvalidSession));
}
Ok(SessionDetails {
session_id: response_body.to_string(),
})
}
#[cfg(test)]
mod tests {
use crate::creds::openart_cookies::OpenArtCookies;
use super::*;
use crate::creds::openart_credentials::OpenArtCredentials;
#[tokio::test]
#[ignore] // Do not run in CI. Run manully to test session retrieval.
async fn invalid_session() {
let creds = OpenArtCredentials {
cookies: Some(OpenArtCookies::new("".to_string()))
};
let result = get_session_request(&creds).await;
println!("Result: {:?}", result);
assert!(result.is_err());
}
}