lib.rs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. extern crate byteorder;
  2. extern crate futures;
  3. extern crate linear_map;
  4. extern crate protobuf;
  5. extern crate librespot_core;
  6. extern crate librespot_protocol as protocol;
  7. pub mod cover;
  8. use futures::Future;
  9. use linear_map::LinearMap;
  10. use librespot_core::mercury::MercuryError;
  11. use librespot_core::session::Session;
  12. use librespot_core::spotify_id::{FileId, SpotifyId};
  13. pub use protocol::metadata::AudioFile_Format as FileFormat;
  14. fn countrylist_contains(list: &str, country: &str) -> bool {
  15. list.chunks(2).any(|cc| cc == country)
  16. }
  17. fn parse_restrictions<'s, I>(restrictions: I, country: &str, catalogue: &str) -> bool
  18. where
  19. I: IntoIterator<Item = &'s protocol::metadata::Restriction>,
  20. {
  21. let mut forbidden = "".to_string();
  22. let mut has_forbidden = false;
  23. let mut allowed = "".to_string();
  24. let mut has_allowed = false;
  25. let rs = restrictions
  26. .into_iter()
  27. .filter(|r| r.get_catalogue_str().contains(&catalogue.to_owned()));
  28. for r in rs {
  29. if r.has_countries_forbidden() {
  30. forbidden.push_str(r.get_countries_forbidden());
  31. has_forbidden = true;
  32. }
  33. if r.has_countries_allowed() {
  34. allowed.push_str(r.get_countries_allowed());
  35. has_allowed = true;
  36. }
  37. }
  38. (has_forbidden || has_allowed)
  39. && (!has_forbidden || !countrylist_contains(forbidden.as_str(), country))
  40. && (!has_allowed || countrylist_contains(allowed.as_str(), country))
  41. }
  42. pub trait Metadata: Send + Sized + 'static {
  43. type Message: protobuf::Message;
  44. fn base_url() -> &'static str;
  45. fn parse(msg: &Self::Message, session: &Session) -> Self;
  46. fn get(session: &Session, id: SpotifyId) -> Box<Future<Item = Self, Error = MercuryError>> {
  47. let uri = format!("{}/{}", Self::base_url(), id.to_base16());
  48. let request = session.mercury().get(uri);
  49. let session = session.clone();
  50. Box::new(request.and_then(move |response| {
  51. let data = response.payload.first().expect("Empty payload");
  52. let msg: Self::Message = protobuf::parse_from_bytes(data).unwrap();
  53. Ok(Self::parse(&msg, &session))
  54. }))
  55. }
  56. }
  57. #[derive(Debug, Clone)]
  58. pub struct Track {
  59. pub id: SpotifyId,
  60. pub name: String,
  61. pub duration: i32,
  62. pub album: SpotifyId,
  63. pub artists: Vec<SpotifyId>,
  64. pub files: LinearMap<FileFormat, FileId>,
  65. pub alternatives: Vec<SpotifyId>,
  66. pub available: bool,
  67. }
  68. #[derive(Debug, Clone)]
  69. pub struct Album {
  70. pub id: SpotifyId,
  71. pub name: String,
  72. pub artists: Vec<SpotifyId>,
  73. pub tracks: Vec<SpotifyId>,
  74. pub covers: Vec<FileId>,
  75. }
  76. #[derive(Debug, Clone)]
  77. pub struct Artist {
  78. pub id: SpotifyId,
  79. pub name: String,
  80. pub top_tracks: Vec<SpotifyId>,
  81. }
  82. impl Metadata for Track {
  83. type Message = protocol::metadata::Track;
  84. fn base_url() -> &'static str {
  85. "hm://metadata/3/track"
  86. }
  87. fn parse(msg: &Self::Message, session: &Session) -> Self {
  88. let country = session.country();
  89. let artists = msg
  90. .get_artist()
  91. .iter()
  92. .filter(|artist| artist.has_gid())
  93. .map(|artist| SpotifyId::from_raw(artist.get_gid()).unwrap())
  94. .collect::<Vec<_>>();
  95. let files = msg
  96. .get_file()
  97. .iter()
  98. .filter(|file| file.has_file_id())
  99. .map(|file| {
  100. let mut dst = [0u8; 20];
  101. dst.clone_from_slice(file.get_file_id());
  102. (file.get_format(), FileId(dst))
  103. })
  104. .collect();
  105. Track {
  106. id: SpotifyId::from_raw(msg.get_gid()).unwrap(),
  107. name: msg.get_name().to_owned(),
  108. duration: msg.get_duration(),
  109. album: SpotifyId::from_raw(msg.get_album().get_gid()).unwrap(),
  110. artists: artists,
  111. files: files,
  112. alternatives: msg
  113. .get_alternative()
  114. .iter()
  115. .map(|alt| SpotifyId::from_raw(alt.get_gid()).unwrap())
  116. .collect(),
  117. available: parse_restrictions(msg.get_restriction(), &country, "premium"),
  118. }
  119. }
  120. }
  121. impl Metadata for Album {
  122. type Message = protocol::metadata::Album;
  123. fn base_url() -> &'static str {
  124. "hm://metadata/3/album"
  125. }
  126. fn parse(msg: &Self::Message, _: &Session) -> Self {
  127. let artists = msg
  128. .get_artist()
  129. .iter()
  130. .filter(|artist| artist.has_gid())
  131. .map(|artist| SpotifyId::from_raw(artist.get_gid()).unwrap())
  132. .collect::<Vec<_>>();
  133. let tracks = msg
  134. .get_disc()
  135. .iter()
  136. .flat_map(|disc| disc.get_track())
  137. .filter(|track| track.has_gid())
  138. .map(|track| SpotifyId::from_raw(track.get_gid()).unwrap())
  139. .collect::<Vec<_>>();
  140. let covers = msg
  141. .get_cover_group()
  142. .get_image()
  143. .iter()
  144. .filter(|image| image.has_file_id())
  145. .map(|image| {
  146. let mut dst = [0u8; 20];
  147. dst.clone_from_slice(image.get_file_id());
  148. FileId(dst)
  149. })
  150. .collect::<Vec<_>>();
  151. Album {
  152. id: SpotifyId::from_raw(msg.get_gid()).unwrap(),
  153. name: msg.get_name().to_owned(),
  154. artists: artists,
  155. tracks: tracks,
  156. covers: covers,
  157. }
  158. }
  159. }
  160. impl Metadata for Artist {
  161. type Message = protocol::metadata::Artist;
  162. fn base_url() -> &'static str {
  163. "hm://metadata/3/artist"
  164. }
  165. fn parse(msg: &Self::Message, session: &Session) -> Self {
  166. let country = session.country();
  167. let top_tracks: Vec<SpotifyId> = match msg
  168. .get_top_track()
  169. .iter()
  170. .find(|tt| !tt.has_country() || countrylist_contains(tt.get_country(), &country))
  171. {
  172. Some(tracks) => tracks
  173. .get_track()
  174. .iter()
  175. .filter(|track| track.has_gid())
  176. .map(|track| SpotifyId::from_raw(track.get_gid()).unwrap())
  177. .collect::<Vec<_>>(),
  178. None => Vec::new(),
  179. };
  180. Artist {
  181. id: SpotifyId::from_raw(msg.get_gid()).unwrap(),
  182. name: msg.get_name().to_owned(),
  183. top_tracks: top_tracks,
  184. }
  185. }
  186. }
  187. struct StrChunks<'s>(&'s str, usize);
  188. trait StrChunksExt {
  189. fn chunks(&self, size: usize) -> StrChunks;
  190. }
  191. impl StrChunksExt for str {
  192. fn chunks(&self, size: usize) -> StrChunks {
  193. StrChunks(self, size)
  194. }
  195. }
  196. impl<'s> Iterator for StrChunks<'s> {
  197. type Item = &'s str;
  198. fn next(&mut self) -> Option<&'s str> {
  199. let &mut StrChunks(data, size) = self;
  200. if data.is_empty() {
  201. None
  202. } else {
  203. let ret = Some(&data[..size]);
  204. self.0 = &data[size..];
  205. ret
  206. }
  207. }
  208. }