1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
//! MusicBrainz rust is a utility crate for the the
//! [MusicBrainz API](https://musicbrainz.org/doc/Development/XML_Web_Service/Version_2).
//! It strives to provide a simple and easy to use API to query the Musicbrainz database.
//!
//! All query are performed via a builder pattern fashioned syntax on musicbrainz entities available
//! in the [`entity`] module.
//!
//! ## Example
//!
//! The most simple usage would be to lookup an entity, knowing its [Musicbrainz ID](https://musicbrainz.org/doc/MusicBrainz_Identifier).
//!
//!  ```rust
//! use musicbrainz_rs::entity::artist::Artist;
//! use musicbrainz_rs::prelude::*;
//!
//! fn main() -> Result<(), Error> {
//!
//!     let nirvana = Artist::fetch()
//!         .id("5b11f4ce-a62d-471e-81fc-a69a8278c7da")
//!         .execute();
//!
//!     assert_eq!(nirvana?.name, "Nirvana".to_string());
//!     Ok(())
//! }
//! ```
//!
//! Note that you need to either directly to bring the [`Fetch`] trait in scope or use the
//! [`prelude`] module to make the fetch method accessible.
//!
//! [musicbrainz::prelude]: musicbrainz_rs::prelude
//! [entity]: musicbrainz_rs::entity

extern crate reqwest;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate lazy_static;

use serde::de::DeserializeOwned;
use std::marker::PhantomData;

use crate::config::*;

/// Configure the HTTP client global state
pub mod config;
mod deserialization;
/// All Musicbrainz entities
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;

/// Type alias for [reqwest::Error]
pub type Error = reqwest::Error;

#[derive(Clone, Debug)]
struct Query<T> {
    path: String,
    include: Vec<Include>,
    phantom: PhantomData<T>,
}

/// perform a lookup of an entity when you have the MBID for that entity
///
/// # Lookups
///
/// You can perform a lookup of an entity when you have the MBID for that entity.
///
/// ## EXample
/// ```rust
/// # use musicbrainz_rs::prelude::*;
/// # fn main() -> Result<(), Error> {
/// # use musicbrainz_rs::entity::artist::Artist;
/// let nirvana = Artist::fetch()
///         .id("5b11f4ce-a62d-471e-81fc-a69a8278c7da")
///         .execute();
///
/// assert_eq!(nirvana?.name, "Nirvana".to_string());
/// #   Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct FetchQuery<T>(Query<T>);

/// perform a lookup of an entity's coverart when you have the MBID for that entity
///
/// # Lookups
///
/// You can perform a lookup of an entity's coverart when you have the MBID for that entity.
///
/// ## Example
/// ```rust
/// # use musicbrainz_rs::prelude::*;
/// # fn main() -> Result<(), Error> {
/// # use musicbrainz_rs::entity::release::Release;
/// let in_utero_coverart = Release::fetch_coverart()
///         .id("76df3287-6cda-33eb-8e9a-044b5e15ffdd")
///         .execute();
///
/// assert!(in_utero_coverart?.images[0].front, true);
/// #   Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct FetchCoverartQuery<T>(Query<T>);

/// Direct lookup of all the entities directly linked to another entity
///
/// # Browse
///
/// Browse requests are a direct lookup of all the entities directly linked to another entity
/// ("directly linked" here meaning it does not include entities linked by a relationship).
///
/// ## Example
/// ```rust
/// # use musicbrainz_rs::prelude::*;
/// # fn main() -> Result<(), Error> {
/// # use musicbrainz_rs::entity::artist::Artist;
/// # use musicbrainz_rs::entity::release::Release;
/// let ubiktune_releases = Release::browse()
///         .by_label("47e718e1-7ee4-460c-b1cc-1192a841c6e5")
///         .execute();
///
/// assert!(!ubiktune_releases?.entities.is_empty());
/// #   Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct BrowseQuery<T>(Query<T>);

/// Search requests provide a way to search for MusicBrainz entities based on different
/// sorts of queries.
///
///# Search
///
/// The MusicBrainz API search requests provide a way to search for MusicBrainz entities
/// based on different sorts of queries.
/// ## Example
///
/// ```rust
/// # use musicbrainz_rs::prelude::*;
/// # fn main() -> Result<(), Error> {
/// # use musicbrainz_rs::entity::artist::Artist;
/// let query = Artist::query_builder()
///         .name("Miles Davis")
///         .and()
///         .country("US")
///         .build();
///
///     let query_result = Artist::search(query).execute()?;
///     let query_result: Vec<String> = query_result
///         .entities
///         .iter()
///         .map(|artist| artist.name.clone())
///         .collect();
///
///     assert!(query_result.contains(&"Miles Davis".to_string()));
///     assert!(query_result.contains(&"Miles Davis Quintet".to_string()));
/// #   Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct SearchQuery<T>(Query<T>);

impl<'a, T> FetchQuery<T>
where
    T: Clone,
{
    pub fn id(&mut self, id: &str) -> &mut Self {
        self.0.path.push_str(&format!("/{}", id));
        self
    }

    pub fn execute(&mut self) -> Result<T, Error>
    where
        T: Fetch<'a> + DeserializeOwned,
    {
        self.0.path.push_str(FMT_JSON);
        self.include_to_path();
        HTTP_CLIENT.get(&self.0.path).send()?.json()
    }

    fn include_to_path(&mut self) {
        self.0.include_to_path()
    }
}

impl<'a, T> FetchCoverartQuery<T>
where
    T: Clone + FetchCoverart<'a>,
{
    pub fn id(&mut self, id: &str) -> &mut Self {
        self.0.path.push_str(&format!("/{}", id));
        self
    }

    pub fn execute(&mut self) -> Result<Coverart, Error> {
        HTTP_CLIENT.get(&self.0.path).send()?.json()
    }
}

impl<'a, T> BrowseQuery<T>
where
    T: Clone,
{
    pub fn execute(&mut self) -> Result<BrowseResult<T>, Error>
    where
        T: Fetch<'a> + DeserializeOwned + Browsable,
    {
        self.include_to_path();
        HTTP_CLIENT.get(&self.0.path).send()?.json()
    }

    fn include_to_path(&mut self) {
        self.0.include_to_path()
    }
}

impl<'a, T> SearchQuery<T>
where
    T: Search<'a> + Clone,
{
    pub fn execute(&mut self) -> Result<SearchResult<T>, Error>
    where
        T: Search<'a> + DeserializeOwned + Searchable,
    {
        self.include_to_path();
        HTTP_CLIENT.get(&self.0.path).send()?.json()
    }

    fn include_to_path(&mut self) {
        self.0.include_to_path()
    }
}

impl<'a, T> Query<T> {
    fn include(&mut self, include: Include) -> &mut Self {
        self.include.push(include);
        self
    }

    fn include_to_path(&mut self) {
        if !self.include.is_empty() {
            self.path.push_str(PARAM_INC);
        }

        for inc in self.include.iter() {
            if Some(inc) != self.include.last() {
                self.path.push_str(inc.as_str());
                self.path.push('+');
            } else {
                self.path.push_str(inc.as_str());
            }
        }
    }
}

/// Provide the entity HTTP api path, do not use this trait directly
pub trait Path<'a> {
    fn path() -> &'static str;
}

/// Implemented by all fetchable entities (see [`FetchQuery`])
pub trait Fetch<'a> {
    fn fetch() -> FetchQuery<Self>
    where
        Self: Sized + Path<'a>,
    {
        FetchQuery(Query {
            path: format!("{}/{}", BASE_URL, Self::path()),
            phantom: PhantomData,
            include: vec![],
        })
    }
}

/// Implemented by all fetchable coverart entities (see [`FetchCoverartQuery`])
pub trait FetchCoverart<'a> {
    fn fetch_coverart() -> FetchCoverartQuery<Self>
    where
        Self: Sized + Path<'a>,
    {
        FetchCoverartQuery(Query {
            path: format!("{}/{}", BASE_COVERART_URL, Self::path()),
            phantom: PhantomData,
            include: vec![],
        })
    }
}

/// Implemented by all browsable entities (see [`BrowseQuery`])
pub trait Browse<'a> {
    fn browse() -> BrowseQuery<Self>
    where
        Self: Sized + Path<'a>,
    {
        BrowseQuery(Query {
            path: format!("{}/{}", BASE_URL, Self::path()),
            phantom: PhantomData,
            include: vec![],
        })
    }
}

/// Implemented by all searchable entities (see [`SearchQuery`])
pub trait Search<'a> {
    fn search(query: String) -> SearchQuery<Self>
    where
        Self: Sized + Path<'a>,
    {
        SearchQuery(Query {
            path: format!("{}/{}{}&{}", BASE_URL, Self::path(), FMT_JSON, query),
            phantom: PhantomData,
            include: vec![],
        })
    }
}