2022-01-25 18:47:08 +00:00
|
|
|
use crate::api::{
|
|
|
|
configuration::{api_url, ImgurHandle},
|
|
|
|
ImageInfo,
|
|
|
|
};
|
2022-01-22 21:02:51 +00:00
|
|
|
|
2022-01-26 18:55:08 +00:00
|
|
|
use super::send_api_request;
|
|
|
|
|
2022-01-25 18:47:08 +00:00
|
|
|
use log::error;
|
|
|
|
use reqwest::Method;
|
|
|
|
use std::{collections::HashMap, process::exit};
|
2022-01-22 21:02:51 +00:00
|
|
|
|
|
|
|
pub async fn upload_image(c: ImgurHandle, image: &str) -> Result<ImageInfo, String> {
|
|
|
|
let mut form = HashMap::new();
|
|
|
|
|
|
|
|
form.insert("image", image.to_string());
|
|
|
|
|
2022-01-25 18:47:08 +00:00
|
|
|
let uri = api_url!("image");
|
|
|
|
let res = send_api_request(&c, Method::POST, uri, Some(form))
|
2022-01-22 21:02:51 +00:00
|
|
|
.await
|
2022-01-25 18:47:08 +00:00
|
|
|
.unwrap_or_else(|e| {
|
|
|
|
error!("send api request: {e}");
|
|
|
|
exit(1)
|
|
|
|
});
|
2022-01-22 21:02:51 +00:00
|
|
|
|
|
|
|
let status = res.status();
|
|
|
|
|
|
|
|
if status.is_client_error() || status.is_server_error() {
|
2022-01-25 18:47:08 +00:00
|
|
|
let body = res.text().await.map_err(|e| e.to_string())?;
|
|
|
|
|
2022-01-22 21:14:26 +00:00
|
|
|
Err(format!(
|
|
|
|
"server returned non-successful status code = {status}. body = {body}"
|
|
|
|
))
|
2022-01-22 21:02:51 +00:00
|
|
|
} else {
|
2022-01-25 18:47:08 +00:00
|
|
|
let content: ImageInfo = res.json().await.map_err(|e| e.to_string())?;
|
|
|
|
|
2022-01-22 21:02:51 +00:00
|
|
|
Ok(content)
|
|
|
|
}
|
|
|
|
}
|