Skip to content

Commit

Permalink
feat: validate url as a Lemmy instance before making API requests (#30)
Browse files Browse the repository at this point in the history
* feat: make Api creation fallible

* feat: check if instance url is a lemmy instance during initalization

* feat: make Api creation async

* feat: better error message for non-lemmy instance url

* style: use unwrap, we're not dealing with user input here

* style: format blocks in main.rs
  • Loading branch information
aidandenlinger committed Aug 10, 2023
1 parent 1965893 commit b10fed8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
13 changes: 10 additions & 3 deletions src/lemmy/api.rs
Expand Up @@ -17,15 +17,22 @@ pub struct Api {
}

impl Api {
pub fn new(instance: Url) -> Api {
pub async fn new(instance: Url) -> Result<Api, Error> {
let mut client_builder = ClientBuilder::new();
client_builder = client_builder.user_agent("LASIM - https://github.com/CMahaff/lasim");
let new_client = client_builder.build().unwrap();

return Api {
// Check if instance is an actual Lemmy url by checking getSite
new_client
.get(instance.join("/api/v3/site").unwrap())
.send()
.await?
.error_for_status()?;

return Ok(Api {
client: new_client,
instance,
}
});
}

pub async fn login(&self, username: &str, password: &str, two_factor_token: Option<String>) -> Result<String, Error> {
Expand Down
20 changes: 18 additions & 2 deletions src/main.rs
Expand Up @@ -182,7 +182,15 @@ async fn process_download(processing_instruction: ProcessingInstruction, mut log
}
let instance_url = instance_url_result.unwrap();

let api = lemmy::api::Api::new(instance_url);
let api = match lemmy::api::Api::new(instance_url).await {
Ok(api) => api,
Err(e) => {
logger(format!(
"ERROR: Invalid Instance URL (or instance is down) - {e}"
));
return;
}
};

// Login
logger(format!("Logging in as {}", username));
Expand Down Expand Up @@ -370,7 +378,15 @@ async fn process_upload(processing_instruction: ProcessingInstruction, mut logge
}
let instance_url = instance_url_result.unwrap();

let api = lemmy::api::Api::new(instance_url);
let api = match lemmy::api::Api::new(instance_url).await {
Ok(api) => api,
Err(e) => {
logger(format!(
"ERROR: Invalid Instance URL (or instance is down) - {e}"
));
return;
}
};

// Login
logger(format!("Logging in as {}", username));
Expand Down

0 comments on commit b10fed8

Please sign in to comment.