Skip to content

Commit

Permalink
Add attempt specific fields to AutoDiscoveryUniffiResult
Browse files Browse the repository at this point in the history
  • Loading branch information
oguzkocer committed Dec 9, 2024
1 parent 9d37bfd commit 0d0f0b4
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 27 deletions.
4 changes: 2 additions & 2 deletions wp_api/src/api_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ pub enum WpErrorCode {
CustomError(String),
}

#[derive(Debug, PartialEq, Eq, thiserror::Error, uniffi::Error)]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)]
pub enum RequestExecutionError {
#[error(
"Request execution failed!\nStatus Code: '{:?}'.\nResponse: '{}'",
Expand All @@ -322,7 +322,7 @@ pub enum RequestExecutionError {
},
}

#[derive(Debug, PartialEq, Eq, thiserror::Error, uniffi::Error)]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)]
pub enum MediaUploadRequestExecutionError {
#[error(
"Request execution failed!\nStatus Code: '{:?}'.\nResponse: '{}'",
Expand Down
2 changes: 1 addition & 1 deletion wp_api/src/login/login_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ impl WpLoginClient {
return Err(AutoDiscoveryAttemptFailure::ParseApiDetails {
parsed_site_url,
api_root_url,
error,
parsing_error_message: error.to_string(),
})
}
};
Expand Down
74 changes: 57 additions & 17 deletions wp_api/src/login/url_discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,28 @@ impl AutoDiscoveryAttempt {

#[derive(Debug, uniffi::Record)]
pub struct AutoDiscoveryUniffiResult {
pub attempts: HashMap<AutoDiscoveryAttemptType, Arc<AutoDiscoveryAttemptResult>>,
pub user_input_attempt: Arc<AutoDiscoveryAttemptResult>,
pub successful_attempt: Option<Arc<AutoDiscoveryAttemptResult>>,
pub auto_https_attempt: Option<Arc<AutoDiscoveryAttemptResult>>,
pub auto_dot_php_extension_for_wp_admin_attempt: Option<Arc<AutoDiscoveryAttemptResult>>,
pub is_successful: bool,
}

impl From<AutoDiscoveryResult> for AutoDiscoveryUniffiResult {
fn from(value: AutoDiscoveryResult) -> Self {
let get_attempt_result = |attempt_type| {
value
.get_attempt(&attempt_type)
.map(|a| Arc::new(a.clone()))
};
Self {
attempts: value
.attempts
.into_iter()
.map(|(k, v)| (k, Arc::new(v)))
.collect(),
user_input_attempt: Arc::new(value.user_input_attempt().clone()),
successful_attempt: value.find_successful().map(|a| Arc::new(a.clone())),
auto_https_attempt: get_attempt_result(AutoDiscoveryAttemptType::AutoHttps),
auto_dot_php_extension_for_wp_admin_attempt: get_attempt_result(
AutoDiscoveryAttemptType::AutoDotPhpExtensionForWpAdmin,
),
is_successful: value.is_successful(),
}
}
}
Expand All @@ -42,15 +53,41 @@ pub struct AutoDiscoveryResult {
}

impl AutoDiscoveryResult {
pub fn find_successful(self) -> Option<AutoDiscoveryAttemptResult> {
pub fn is_successful(&self) -> bool {
self.attempts
.into_iter()
.find(|(attempt_type, result)| result.result.is_ok())
.map(|(attempt_type, result)| result)
.iter()
.any(|(_, result)| result.is_successful())
}

pub fn find_successful(&self) -> Option<&AutoDiscoveryAttemptResult> {
// If the user attempt is successful, prefer it over other attempts
let user_input_attempt = self.user_input_attempt();
if user_input_attempt.is_successful() {
return Some(user_input_attempt);
}
self.attempts.iter().find_map(|(_, result)| {
if result.is_successful() {
Some(result)
} else {
None
}
})
}

pub fn user_input_attempt(&self) -> &AutoDiscoveryAttemptResult {
self.get_attempt(&AutoDiscoveryAttemptType::UserInput)
.expect("User input url is always attempted")
}

pub fn get_attempt(
&self,
attempt_type: &AutoDiscoveryAttemptType,
) -> Option<&AutoDiscoveryAttemptResult> {
self.attempts.get(attempt_type)
}
}

#[derive(Debug, uniffi::Object)]
#[derive(Debug, Clone, uniffi::Object)]
pub struct AutoDiscoveryAttemptResult {
pub attempt_type: AutoDiscoveryAttemptType,
pub attempt_site_url: String,
Expand Down Expand Up @@ -128,14 +165,14 @@ impl AutoDiscoveryAttemptResult {
}
}

#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct AutoDiscoveryAttemptSuccess {
pub parsed_site_url: ParsedUrl,
pub api_root_url: ParsedUrl,
pub api_details: WpApiDetails,
}

#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum AutoDiscoveryAttemptFailure {
ParseSiteUrl {
error: ParseUrlError,
Expand All @@ -156,7 +193,7 @@ pub enum AutoDiscoveryAttemptFailure {
ParseApiDetails {
parsed_site_url: ParsedUrl,
api_root_url: ParsedUrl,
error: serde_json::Error,
parsing_error_message: String,
},
}

Expand All @@ -179,8 +216,11 @@ impl AutoDiscoveryAttemptFailure {
AutoDiscoveryAttemptFailure::FetchApiRootUrl { error, .. } => error.to_string(),
AutoDiscoveryAttemptFailure::ParseApiRootUrl { error, .. } => error.to_string(),
AutoDiscoveryAttemptFailure::FetchApiDetails { error, .. } => error.to_string(),
AutoDiscoveryAttemptFailure::ParseApiDetails { error, .. } => {
format!("Failed to parse api details: {:#?}", error)
AutoDiscoveryAttemptFailure::ParseApiDetails {
parsing_error_message,
..
} => {
format!("Failed to parse api details: {:#?}", parsing_error_message)
}
}
}
Expand Down Expand Up @@ -297,7 +337,7 @@ pub(crate) fn construct_attempts(input_site_url: String) -> Vec<AutoDiscoveryAtt
attempts
}

#[derive(Debug, thiserror::Error, uniffi::Error)]
#[derive(Debug, Clone, thiserror::Error, uniffi::Error)]
pub enum ParseApiRootUrlError {
#[error(
"Api root link header not found!\nStatus Code: '{:#?}'\nHeader Map: '{:#?}'",
Expand Down
2 changes: 1 addition & 1 deletion wp_api/src/parsed_url.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl ParsedUrl {
}
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, thiserror::Error, uniffi::Error)]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, thiserror::Error, uniffi::Error)]
pub enum ParseUrlError {
#[error("Error while parsing url: {}", reason)]
Generic { reason: String },
Expand Down
16 changes: 10 additions & 6 deletions wp_api_integration_tests/tests/test_login_immut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,18 @@ const VANILLA_WP_SITE_URL: &str = "https://vanilla.wpmt.co/wp-admin/authorize-ap
async fn test_login_flow(#[case] site_url: &str, #[case] expected_auth_url: &str) {
let client = WpLoginClient::new(Arc::new(AsyncWpNetworking::default()));
let result = client.api_discovery(site_url.to_string()).await;
let failure_message = format!("Auto discovery failed: {:#?}", result);
let successful_attempt = result.find_successful();
assert!(successful_attempt.is_some(), "{}", failure_message);
assert!(
result.is_successful(),
"Auto discovery failed: {:#?}",
result
);
assert_eq!(
successful_attempt
.unwrap()
result
.find_successful()
.expect("Already verified that auto discovery is successful")
.result
.unwrap()
.clone()
.expect("Already verified that auto discovery is successful")
.api_details
.find_application_passwords_authentication_url(),
Some(expected_auth_url.to_string())
Expand Down

0 comments on commit 0d0f0b4

Please sign in to comment.