Skip to content

Commit

Permalink
feat(coverart): coverart builder to make specific queries
Browse files Browse the repository at this point in the history
  • Loading branch information
ritiek committed Jun 21, 2021
1 parent cb1a309 commit 19dbdfa
Show file tree
Hide file tree
Showing 4 changed files with 154 additions and 13 deletions.
20 changes: 18 additions & 2 deletions examples/fetch_release_coverart.rs
@@ -1,6 +1,7 @@
extern crate musicbrainz_rs;

use musicbrainz_rs::entity::release::*;
use musicbrainz_rs::entity::CoverartResponse;
use musicbrainz_rs::FetchCoverart;

fn main() {
Expand All @@ -9,6 +10,21 @@ fn main() {
.execute()
.expect("Unable to get cover art");

assert_eq!(in_utero_coverart.images[0].front, true);
assert_eq!(in_utero_coverart.images[0].back, false);
if let CoverartResponse::Json(json) = in_utero_coverart {
println!("{}", json.images[0].back);
println!("{}", json.images[0].image);
}

println!("");

let in_utero_500px_front_coverart = Release::fetch_coverart()
.id("76df3287-6cda-33eb-8e9a-044b5e15ffdd")
.res_500()
.back()
.execute()
.expect("Unable to get cover art");

if let CoverartResponse::Url(url) = in_utero_500px_front_coverart {
println!("{}", url);
}
}
45 changes: 45 additions & 0 deletions src/entity/mod.rs
@@ -1,5 +1,6 @@
use crate::entity::area::Area;
use crate::entity::artist::Artist;
use crate::entity::coverart::Coverart;
use crate::entity::event::Event;
use crate::entity::instrument::*;
use crate::entity::label::Label;
Expand Down Expand Up @@ -347,3 +348,47 @@ impl Browsable for Instrument {
const OFFSET_FIELD: &'static str = "instrument-offset";
const ENTITIES_FIELD: &'static str = "instruments";
}

#[derive(Clone, Debug)]
pub struct CoverartTarget {
pub img_type: Option<CoverartType>,
pub img_res: Option<CoverartResolution>,
}

#[derive(Clone, Debug)]
pub enum CoverartResponse {
Json(Coverart),
Url(String),
}

#[derive(Clone, Debug)]
pub enum CoverartType {
Front,
Back,
}

impl CoverartType {
pub fn as_str(&self) -> &'static str {
match self {
CoverartType::Front => "front",
CoverartType::Back => "back",
}
}
}

#[derive(Clone, Debug)]
pub enum CoverartResolution {
Res250,
Res500,
Res1200,
}

impl CoverartResolution {
pub fn as_str(&self) -> &'static str {
match self {
CoverartResolution::Res250 => "250",
CoverartResolution::Res500 => "500",
CoverartResolution::Res1200 => "1200",
}
}
}
93 changes: 84 additions & 9 deletions src/lib.rs
Expand Up @@ -50,12 +50,12 @@ pub mod entity;
/// Brings trait and type needed to perform any API query in scope
pub mod prelude;

use crate::entity::coverart::Coverart;
use crate::entity::search::{SearchResult, Searchable};
use deserialization::date_format;
use entity::Browsable;
use entity::BrowseResult;
use entity::Include;
use entity::{CoverartResolution, CoverartResponse, CoverartTarget, CoverartType};

/// Type alias for [reqwest::Error]
pub type Error = reqwest::Error;
Expand Down Expand Up @@ -100,16 +100,28 @@ pub struct FetchQuery<T>(Query<T>);
/// # use musicbrainz_rs::prelude::*;
/// # fn main() -> Result<(), Error> {
/// # use musicbrainz_rs::entity::release::Release;
/// # use musicbrainz_rs::entity::CoverartResponse;
/// let in_utero_coverart = Release::fetch_coverart()
/// .id("76df3287-6cda-33eb-8e9a-044b5e15ffdd")
/// .execute();
///
/// assert!(in_utero_coverart?.images[0].front, true);
/// .execute()?;
/// if let CoverartResponse::Json(coverart) = in_utero_coverart {
/// assert_eq!(coverart.images[0].front, true);
/// assert_eq!(coverart.images[0].back, false);
/// } else {
/// assert!(false);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct FetchCoverartQuery<T>(Query<T>);
struct CoverartQuery<T> {
path: String,
target: CoverartTarget,
phantom: PhantomData<T>,
}

#[derive(Clone, Debug)]
pub struct FetchCoverartQuery<T>(CoverartQuery<T>);

/// Direct lookup of all the entities directly linked to another entity
///
Expand Down Expand Up @@ -201,8 +213,68 @@ where
self
}

pub fn execute(&mut self) -> Result<Coverart, Error> {
HTTP_CLIENT.get(&self.0.path).send()?.json()
pub fn front(&mut self) -> &mut Self {
if self.0.target.img_type.is_some() {
panic!("coverart type is already set");
}
self.0.target.img_type = Some(CoverartType::Front);
self
}

pub fn back(&mut self) -> &mut Self {
if self.0.target.img_type.is_some() {
panic!("coverart type is already set");
}
self.0.target.img_type = Some(CoverartType::Back);
self
}

pub fn res_250(&mut self) -> &mut Self {
if self.0.target.img_res.is_some() {
panic!("coverart resolution is already set");
}
self.0.target.img_res = Some(CoverartResolution::Res250);
self
}

pub fn res_500(&mut self) -> &mut Self {
if self.0.target.img_res.is_some() {
panic!("coverart resolution is already set");
}
self.0.target.img_res = Some(CoverartResolution::Res500);
self
}

pub fn res_1200(&mut self) -> &mut Self {
if self.0.target.img_res.is_some() {
panic!("coverart resolution is already set");
}
self.0.target.img_res = Some(CoverartResolution::Res1200);
self
}

pub fn validate(&mut self) {
if let Some(img_type) = &self.0.target.img_type {
self.0.path.push_str(&format!("/{}", img_type.as_str()));
if let Some(img_res) = &self.0.target.img_res {
self.0.path.push_str(&format!("-{}", img_res.as_str()));
}
} else if self.0.target.img_res.is_some() {
panic!("cannot set image resolution without setting image type");
}
}

pub fn execute(&mut self) -> Result<CoverartResponse, Error> {
let coverart_response: CoverartResponse;
self.validate();
let mut response = HTTP_CLIENT.get(&self.0.path).send()?;
if self.0.target.img_type.is_some() {
let url = response.url().clone();
coverart_response = CoverartResponse::Url(url.to_string());
} else {
coverart_response = CoverartResponse::Json(response.json().unwrap());
}
Ok(coverart_response)
}
}

Expand Down Expand Up @@ -285,10 +357,13 @@ pub trait FetchCoverart<'a> {
where
Self: Sized + Path<'a>,
{
FetchCoverartQuery(Query {
FetchCoverartQuery(CoverartQuery {
path: format!("{}/{}", BASE_COVERART_URL, Self::path()),
target: CoverartTarget {
img_type: None,
img_res: None,
},
phantom: PhantomData,
include: vec![],
})
}
}
Expand Down
9 changes: 7 additions & 2 deletions tests/release/release_coverart.rs
@@ -1,6 +1,7 @@
extern crate musicbrainz_rs;

use musicbrainz_rs::entity::release::*;
use musicbrainz_rs::entity::CoverartResponse;
use musicbrainz_rs::FetchCoverart;
use std::{thread, time};

Expand All @@ -11,8 +12,12 @@ fn should_get_release_coverart() {
.execute()
.expect("Unable to get cover art");

assert_eq!(in_utero_coverart.images[0].front, true);
assert_eq!(in_utero_coverart.images[0].back, false);
if let CoverartResponse::Json(coverart) = in_utero_coverart {
assert_eq!(coverart.images[0].front, true);
assert_eq!(coverart.images[0].back, false);
} else {
assert!(false);
}

thread::sleep(time::Duration::from_secs(1));
}

0 comments on commit 19dbdfa

Please sign in to comment.