2022-04-03 19:01:58 +00:00
|
|
|
use std::{collections::HashMap, io};
|
2022-01-22 21:02:51 +00:00
|
|
|
|
2022-04-03 19:01:58 +00:00
|
|
|
use anyhow::Error;
|
2022-01-25 18:47:08 +00:00
|
|
|
use reqwest::Method;
|
2022-01-22 21:02:51 +00:00
|
|
|
|
2022-04-03 19:01:58 +00:00
|
|
|
use super::{client::api_url, send_api_request, ImageInfo, ImgurClient};
|
2022-01-22 21:02:51 +00:00
|
|
|
|
2022-04-03 19:11:11 +00:00
|
|
|
pub async fn upload_image(client: &ImgurClient, image: String) -> Result<ImageInfo, Error> {
|
2022-04-03 19:01:58 +00:00
|
|
|
// create http form (hashmap)
|
|
|
|
let mut form = HashMap::new();
|
|
|
|
// insert image to form
|
|
|
|
form.insert("image", image);
|
2022-01-22 21:02:51 +00:00
|
|
|
|
2022-04-03 19:01:58 +00:00
|
|
|
// get imgur api url
|
2022-01-25 18:47:08 +00:00
|
|
|
let uri = api_url!("image");
|
2022-04-03 19:01:58 +00:00
|
|
|
|
|
|
|
// send request to imgur api
|
2022-04-03 19:11:11 +00:00
|
|
|
let res = send_api_request(client, Method::POST, uri, Some(form)).await?;
|
2022-01-22 21:02:51 +00:00
|
|
|
|
2022-04-03 19:01:58 +00:00
|
|
|
// get response http code
|
2022-01-22 21:02:51 +00:00
|
|
|
let status = res.status();
|
|
|
|
|
2022-04-03 19:01:58 +00:00
|
|
|
// check if an error has occurred
|
2022-01-22 21:02:51 +00:00
|
|
|
if status.is_client_error() || status.is_server_error() {
|
2022-04-03 19:01:58 +00:00
|
|
|
let mut body = res.text().await?;
|
2022-03-02 21:10:56 +00:00
|
|
|
|
2022-04-03 19:01:58 +00:00
|
|
|
if body.chars().count() > 200 {
|
|
|
|
body = "server returned too long".to_string()
|
2022-03-02 21:10:56 +00:00
|
|
|
}
|
|
|
|
|
2022-04-03 19:01:58 +00:00
|
|
|
let err = io::Error::new(
|
|
|
|
io::ErrorKind::Other,
|
2022-01-26 19:57:51 +00:00
|
|
|
format!("server returned non-successful status code = {status}, body = {body}"),
|
|
|
|
);
|
2022-01-25 18:47:08 +00:00
|
|
|
|
2022-04-03 19:11:11 +00:00
|
|
|
Err(err.into())
|
2022-01-22 21:02:51 +00:00
|
|
|
} else {
|
2022-04-03 19:01:58 +00:00
|
|
|
let content: ImageInfo = res.json().await?;
|
2022-01-22 21:02:51 +00:00
|
|
|
Ok(content)
|
|
|
|
}
|
|
|
|
}
|