Add get_album function

This commit is contained in:
Andre Julius 2022-07-11 22:48:14 +02:00
parent f26170bc12
commit ff3aaebdd4
9 changed files with 150 additions and 26 deletions

60
src/api/album_type.rs Normal file
View File

@ -0,0 +1,60 @@
use serde::{Deserialize, Serialize};
use crate::ImageInfoData;
/// Album Info Response
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct AlbumInfo {
/// Image Data
pub data: AlbumInfoData,
/// Request processed success or not.
pub success: bool,
/// HTTP status code from API request.
pub status: i32,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct AlbumInfoData {
pub id: String,
pub title: String,
pub description: Option<String>,
pub datetime: i64,
pub cover: String,
pub cover_edited: Option<String>,
pub cover_width: i64,
pub cover_height: i64,
pub account_url: Option<String>,
pub account_id: Option<String>,
pub privacy: String,
pub layout: String,
pub views: i64,
pub link: String,
pub favorite: bool,
pub nsfw: bool,
pub section: Option<String>,
pub images_count: i64,
pub in_gallery: bool,
pub is_ad: bool,
pub include_album_ads: bool,
pub is_album: bool,
pub images: Vec<ImageInfoData>,
pub ad_config: AdConfig,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct AdConfig {
#[serde(rename = "safeFlags")]
pub safe_flags: Vec<String>,
#[serde(rename = "highRiskFlags")]
pub high_risk_flags: Vec<String>,
#[serde(rename = "unsafeFlags")]
pub unsafe_flags: Vec<String>,
#[serde(rename = "wallUnsafeFlags")]
pub wall_unsafe_flags: Vec<String>,
#[serde(rename = "showsAds")]
pub shows_ads: bool,
#[serde(rename = "showAdLevel")]
pub show_ad_level: i64,
}

View File

@ -1,9 +1,11 @@
mod album_type;
mod client; mod client;
mod error; mod error;
mod image_type; mod image_type;
mod requests; mod requests;
mod send_api_request; mod send_api_request;
pub use album_type::*;
pub(crate) use client::api_url; pub(crate) use client::api_url;
pub use client::ImgurClient; pub use client::ImgurClient;
pub use error::*; pub use error::*;
@ -97,4 +99,19 @@ impl ImgurClient {
pub async fn image_info(&self, id: &str) -> Result<ImageInfo> { pub async fn image_info(&self, id: &str) -> Result<ImageInfo> {
requests::get_image(self, id).await requests::get_image(self, id).await
} }
/// Get album info from a Imgur
/// ```
/// use imgurs::ImgurClient;
///
/// #[tokio::main]
/// async fn main() {
/// let client = ImgurClient::new("3e3ce0d7ac14d56");
///
/// client.album_info("lFaGr1x").await.expect("delete album");
/// }
/// ```
pub async fn album_info(&self, id: &str) -> Result<AlbumInfo> {
requests::get_album(self, id).await
}
} }

View File

@ -0,0 +1,24 @@
use reqwest::Method;
use crate::{api_url, send_api_request, AlbumInfo, Error, ImgurClient, Result};
pub async fn get_album(client: &ImgurClient, album: &str) -> Result<AlbumInfo> {
// get imgur api url
let uri = api_url!(format!("album/{album}"));
// send request to imgur api
let res = send_api_request(client, Method::GET, uri, None).await?;
// get response http code
let status = res.status();
// check if an error has occurred
if status.is_client_error() || status.is_server_error() {
let body = res.text().await?;
return Err(Error::ApiError(status.as_u16(), body));
}
// return `ImageInfo`
Ok(res.json().await?)
}

View File

@ -1,9 +1,11 @@
mod delete_image; mod delete_image;
mod get_album;
mod get_image; mod get_image;
mod rate_limit; mod rate_limit;
mod upload_image; mod upload_image;
pub use delete_image::*; pub use delete_image::*;
pub use get_album::*;
pub use get_image::*; pub use get_image::*;
pub use rate_limit::*; pub use rate_limit::*;
pub use upload_image::*; pub use upload_image::*;

19
src/cli/album_info.rs Normal file
View File

@ -0,0 +1,19 @@
use imgurs::ImgurClient;
use super::print_image_info;
pub async fn album_info(client: ImgurClient, id: String) {
// get a image info from imgur
let info = client
.album_info(&id)
.await
.expect("send request to imgur api");
print!("got album: {:?}", info);
// print image information from imgur
for image in info.data.images {
print_image_info(&image);
println!("")
}
}

View File

@ -10,5 +10,5 @@ pub async fn image_info(client: ImgurClient, id: String) {
.expect("send request to imfur api"); .expect("send request to imfur api");
// print image information from imgur // print image information from imgur
print_image_info(&info); print_image_info(&info.data);
} }

View File

@ -1,5 +1,6 @@
mod parse; mod parse;
pub mod album_info;
pub mod clipboard; pub mod clipboard;
pub mod credits; pub mod credits;
pub mod delete_image; pub mod delete_image;
@ -10,19 +11,19 @@ pub use parse::*;
use chrono::{prelude::DateTime, Utc}; use chrono::{prelude::DateTime, Utc};
use colored::Colorize; use colored::Colorize;
use imgurs::ImageInfo; use imgurs::ImageInfoData;
use std::time::{Duration, UNIX_EPOCH}; use std::time::{Duration, UNIX_EPOCH};
// print image information from imgur // print image information from imgur
pub fn print_image_info(i: &ImageInfo) { pub fn print_image_info(i: &ImageInfoData) {
// format image upload date // format image upload date
let d = UNIX_EPOCH + Duration::from_secs(i.data.datetime.try_into().unwrap()); let d = UNIX_EPOCH + Duration::from_secs(i.datetime.try_into().unwrap());
let datetime = DateTime::<Utc>::from(d); let datetime = DateTime::<Utc>::from(d);
let timestamp_str = datetime.format("%Y-%m-%d %H:%M:%S").to_string(); let timestamp_str = datetime.format("%Y-%m-%d %H:%M:%S").to_string();
// image title // image title
if i.data.title != None { if i.title != None {
let title = i.data.title.clone(); let title = i.title.clone();
println!( println!(
"{} {}", "{} {}",
@ -32,8 +33,8 @@ pub fn print_image_info(i: &ImageInfo) {
} }
// image description // image description
if i.data.description != None { if i.description != None {
let desc = i.data.description.clone(); let desc = i.description.clone();
println!( println!(
"{} {}", "{} {}",
@ -43,8 +44,8 @@ pub fn print_image_info(i: &ImageInfo) {
} }
// image deletehas // image deletehas
if i.data.deletehash != None { if i.deletehash != None {
let delhash = i.data.deletehash.clone(); let delhash = i.deletehash.clone();
println!( println!(
"{} {}", "{} {}",
@ -53,31 +54,27 @@ pub fn print_image_info(i: &ImageInfo) {
); );
} }
println!("{} {}", "id".green(), i.data.id.magenta()); println!("{} {}", "id".green(), i.id.magenta());
println!( println!(
"{} {} {}", "{} {} {}",
"upload date".green(), "upload date".green(),
timestamp_str.magenta(), timestamp_str.magenta(),
"(UTC)".blue() "(UTC)".blue()
); );
println!("{} {}", "type".green(), i.data.img_type.magenta()); println!("{} {}", "type".green(), i.img_type.magenta());
println!("{} {}", "width".green(), i.data.width.to_string().magenta()); println!("{} {}", "width".green(), i.width.to_string().magenta());
println!( println!("{} {}", "height".green(), i.height.to_string().magenta());
"{} {}",
"height".green(),
i.data.height.to_string().magenta()
);
println!( println!(
"{} {} {}", "{} {} {}",
"size".green(), "size".green(),
(i.data.size / 1000).to_string().magenta(), (i.size / 1000).to_string().magenta(),
"KB".blue() "KB".blue()
); );
println!("{} {}", "views".green(), i.data.views.to_string().magenta()); println!("{} {}", "views".green(), i.views.to_string().magenta());
println!( println!(
"{} {}", "{} {}",
"bandwidth".green(), "bandwidth".green(),
i.data.bandwidth.to_string().magenta() i.bandwidth.to_string().magenta()
); );
println!("{} {}", "link".green(), i.data.link.magenta()); println!("{} {}", "link".green(), i.link.magenta());
} }

View File

@ -3,7 +3,7 @@ use clap_complete::{generate, Generator, Shell};
use imgurs::ImgurClient; use imgurs::ImgurClient;
use std::io::{self, stdout}; use std::io::{self, stdout};
use crate::cli::{credits::*, delete_image::*, info_image::*, upload_image::*}; use crate::cli::{album_info::*, credits::*, delete_image::*, info_image::*, upload_image::*};
// get version from Cargo.toml // get version from Cargo.toml
const VERSION: Option<&str> = option_env!("CARGO_PKG_VERSION"); const VERSION: Option<&str> = option_env!("CARGO_PKG_VERSION");
@ -33,13 +33,16 @@ enum Commands {
#[clap(about = "Print image info", display_order = 4)] #[clap(about = "Print image info", display_order = 4)]
Info { id: String }, Info { id: String },
#[clap(about = "Print album info", display_order = 5)]
AlbumInfo { id: String },
#[clap( #[clap(
about = "Generate completion file for a shell [bash, elvish, fish, powershell, zsh]", about = "Generate completion file for a shell [bash, elvish, fish, powershell, zsh]",
display_order = 5 display_order = 6
)] )]
Completions { shell: Shell }, Completions { shell: Shell },
#[clap(about = "Generate man page", display_order = 6)] #[clap(about = "Generate man page", display_order = 7)]
Manpage, Manpage,
} }
@ -60,6 +63,8 @@ pub async fn parse(client: ImgurClient) {
Commands::Info { id } => image_info(client, id.to_string()).await, Commands::Info { id } => image_info(client, id.to_string()).await,
Commands::AlbumInfo { id } => album_info(client, id.to_string()).await,
Commands::Completions { shell } => { Commands::Completions { shell } => {
let mut app = Cli::command(); let mut app = Cli::command();

View File

@ -35,7 +35,7 @@ pub async fn upload_image(client: ImgurClient, path: String) {
} }
// print image information from imgur // print image information from imgur
print_image_info(&i); print_image_info(&i.data);
// send notification that the image has been uploaded // send notification that the image has been uploaded
notify!(Notification::new() notify!(Notification::new()