api: move reqwest to send_api_request function

This commit is contained in:
MedzikUser 2022-01-25 19:47:08 +01:00
parent b804e8faa2
commit e7fab7de2d
No known key found for this signature in database
GPG Key ID: A5FAC1E185C112DB
9 changed files with 93 additions and 62 deletions

View File

@ -30,7 +30,7 @@ jobs:
artifact_name: target/aarch64-unknown-linux-musl/release/imgurs
release_name: aarch64-unknown-linux-musl
cross: true
strip: true
strip: false
compress: true
cargo_flags: ""

View File

@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
#### Library
- change OpenSSL to RusTLS
- move api request to fn send_api_request
### Fixed
* api rate limit (error decoding response body: invalid value: integer \`200\`, expected i8 at line 1 column 140)

View File

@ -1,19 +1,18 @@
use super::send_api_request;
use crate::api::configuration::{api_url, ImgurHandle};
pub async fn delete_image(c: ImgurHandle, delete_hash: String) -> Result<String, String> {
const VERSION: Option<&str> = option_env!("CARGO_PKG_VERSION");
use log::error;
use reqwest::Method;
use std::process::exit;
let res = c
.client
.delete(api_url!(format!("image/{delete_hash}")))
.header("Authorization", format!("Client-ID {}", c.client_id))
.header(
"User-Agent",
format!("Imgur/{:?}", VERSION.unwrap_or("unknown")),
)
.send()
pub async fn delete_image(c: ImgurHandle, delete_hash: String) -> Result<String, String> {
let uri = api_url!(format!("image/{delete_hash}"));
let res = send_api_request(&c, Method::DELETE, uri, None)
.await
.map_err(|err| err.to_string())?;
.unwrap_or_else(|e| {
error!("send api request: {e}");
exit(1)
});
let status = res.status();

View File

@ -1,20 +1,19 @@
use super::send_api_request;
use crate::api::configuration::{api_url, ImgurHandle};
use crate::api::ImageInfo;
pub async fn get_image(c: ImgurHandle, image: &str) -> Result<ImageInfo, String> {
const VERSION: Option<&str> = option_env!("CARGO_PKG_VERSION");
use log::error;
use reqwest::Method;
use std::process::exit;
let res = c
.client
.get(api_url!(format!("image/{image}")))
.header("Authorization", format!("Client-ID {}", c.client_id))
.header(
"User-Agent",
format!("Imgurs/{:?}", VERSION.unwrap_or("unknown")),
)
.send()
pub async fn get_image(c: ImgurHandle, image: &str) -> Result<ImageInfo, String> {
let uri = api_url!(format!("image/{image}"));
let res = send_api_request(&c, Method::GET, uri, None)
.await
.map_err(|err| err.to_string())?;
.unwrap_or_else(|e| {
error!("send api request: {e}");
exit(1)
});
let status = res.status();
@ -23,7 +22,7 @@ pub async fn get_image(c: ImgurHandle, image: &str) -> Result<ImageInfo, String>
"server returned non-successful status code = {status}."
))
} else {
let content: ImageInfo = res.json().await.map_err(|err| err.to_string())?;
let content: ImageInfo = res.json().await.map_err(|e| e.to_string())?;
Ok(content)
}
}

View File

@ -1,4 +1,5 @@
mod image_type;
mod send_request;
pub mod configuration;
pub mod delete_image;
@ -8,3 +9,4 @@ pub mod upload_image;
pub use configuration::ImgurHandle;
pub use image_type::*;
pub use send_request::send_api_request;

View File

@ -1,6 +1,10 @@
use super::send_api_request;
use crate::api::configuration::{api_url, ImgurHandle};
use log::error;
use reqwest::Method;
use serde_derive::{Deserialize, Serialize};
use std::process::exit;
#[derive(Debug, Serialize, Deserialize)]
pub struct RateLimitInfo {
@ -24,29 +28,23 @@ pub struct RateLimitData {
}
pub async fn rate_limit(c: ImgurHandle) -> Result<RateLimitInfo, String> {
const VERSION: Option<&str> = option_env!("CARGO_PKG_VERSION");
let res = c
.client
.get(api_url!("credits"))
.header("Authorization", format!("Client-ID {}", c.client_id))
.header(
"User-Agent",
format!("Imgur/{:?}", VERSION.unwrap_or("unknown")),
)
.send()
let uri = api_url!("credits");
let res = send_api_request(&c, Method::GET, uri, None)
.await
.map_err(|err| err.to_string())?;
.unwrap_or_else(|e| {
error!("send api request: {e}");
exit(1)
});
let status = res.status();
if status.is_client_error() || status.is_server_error() {
let body = res.text().await.map_err(|err| err.to_string())?;
let body = res.text().await.map_err(|e| e.to_string())?;
Err(format!(
"server returned non-successful status code = {status}. body = {body}"
))
} else {
let content: RateLimitInfo = res.json().await.map_err(|err| err.to_string())?;
let content: RateLimitInfo = res.json().await.map_err(|e| e.to_string())?;
Ok(content)
}
}

32
src/api/send_request.rs Normal file
View File

@ -0,0 +1,32 @@
use reqwest::Method;
use super::ImgurHandle;
use std::collections::HashMap;
pub async fn send_api_request(
config: &ImgurHandle,
method: Method,
uri: String,
form: Option<HashMap<&str, String>>,
) -> Result<reqwest::Response, reqwest::Error> {
let client = &config.client;
let mut req = client.request(method, uri.as_str());
const VERSION: Option<&str> = option_env!("CARGO_PKG_VERSION");
req = req
.header("Authorization", format!("Client-ID {}", config.client_id))
.header(
"User-Agent",
format!("Imgur/{:?}", VERSION.unwrap_or("unknown")),
);
if form != None {
req = req.form(&form.unwrap())
}
let req = req.build()?;
client.execute(req).await
}

View File

@ -1,37 +1,37 @@
use crate::api::configuration::{api_url, ImgurHandle};
use crate::api::ImageInfo;
use super::send_api_request;
use crate::api::{
configuration::{api_url, ImgurHandle},
ImageInfo,
};
use std::collections::HashMap;
use log::error;
use reqwest::Method;
use std::{collections::HashMap, process::exit};
pub async fn upload_image(c: ImgurHandle, image: &str) -> Result<ImageInfo, String> {
const VERSION: Option<&str> = option_env!("CARGO_PKG_VERSION");
let mut form = HashMap::new();
form.insert("image", image.to_string());
let res = c
.client
.post(api_url!("image"))
.header("Authorization", format!("Client-ID {}", c.client_id))
.header(
"User-Agent",
format!("Imgurs/{:?}", VERSION.unwrap_or("unknown")),
)
.form(&form)
.send()
let uri = api_url!("image");
let res = send_api_request(&c, Method::POST, uri, Some(form))
.await
.map_err(|err| err.to_string())?;
.unwrap_or_else(|e| {
error!("send api request: {e}");
exit(1)
});
let status = res.status();
if status.is_client_error() || status.is_server_error() {
let body = res.text().await.map_err(|err| err.to_string())?;
let body = res.text().await.map_err(|e| e.to_string())?;
Err(format!(
"server returned non-successful status code = {status}. body = {body}"
))
} else {
let content: ImageInfo = res.json().await.map_err(|err| err.to_string())?;
let content: ImageInfo = res.json().await.map_err(|e| e.to_string())?;
Ok(content)
}
}

View File

@ -12,8 +12,8 @@ use std::{
};
pub fn parse() -> Config {
toml().unwrap_or_else(|error| {
warn!("Parse toml config: {}! Creating config file...", error);
toml().unwrap_or_else(|e| {
warn!("Parse toml config: {e}! Creating config file...");
let default_config = include_str!(concat!("../../config.toml"));
@ -30,8 +30,8 @@ pub fn parse() -> Config {
.write_all(default_config.as_bytes())
.expect("failed write default config to file");
toml().unwrap_or_else(|error| {
error!("parse toml config: {}", error);
toml().unwrap_or_else(|e| {
error!("parse toml config: {e}");
exit(2);
})
})