lib.rs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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 request_url(id: SpotifyId) -> String;
  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 = Self::request_url(id);
  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 Playlist {
  78. pub user: String,
  79. pub length: i32,
  80. pub name: String,
  81. pub tracks: Vec<SpotifyId>,
  82. }
  83. #[derive(Debug, Clone)]
  84. pub struct Artist {
  85. pub id: SpotifyId,
  86. pub name: String,
  87. pub top_tracks: Vec<SpotifyId>,
  88. }
  89. impl Metadata for Track {
  90. type Message = protocol::metadata::Track;
  91. fn request_url(id: SpotifyId) -> String {
  92. format!("hm://metadata/3/track/{}", id.to_base16())
  93. }
  94. fn parse(msg: &Self::Message, session: &Session) -> Self {
  95. let country = session.country();
  96. let artists = msg
  97. .get_artist()
  98. .iter()
  99. .filter(|artist| artist.has_gid())
  100. .map(|artist| SpotifyId::from_raw(artist.get_gid()).unwrap())
  101. .collect::<Vec<_>>();
  102. let files = msg
  103. .get_file()
  104. .iter()
  105. .filter(|file| file.has_file_id())
  106. .map(|file| {
  107. let mut dst = [0u8; 20];
  108. dst.clone_from_slice(file.get_file_id());
  109. (file.get_format(), FileId(dst))
  110. })
  111. .collect();
  112. Track {
  113. id: SpotifyId::from_raw(msg.get_gid()).unwrap(),
  114. name: msg.get_name().to_owned(),
  115. duration: msg.get_duration(),
  116. album: SpotifyId::from_raw(msg.get_album().get_gid()).unwrap(),
  117. artists: artists,
  118. files: files,
  119. alternatives: msg
  120. .get_alternative()
  121. .iter()
  122. .map(|alt| SpotifyId::from_raw(alt.get_gid()).unwrap())
  123. .collect(),
  124. available: parse_restrictions(msg.get_restriction(), &country, "premium"),
  125. }
  126. }
  127. }
  128. impl Metadata for Album {
  129. type Message = protocol::metadata::Album;
  130. fn request_url(id: SpotifyId) -> String {
  131. format!("hm://metadata/3/album/{}", id.to_base16())
  132. }
  133. fn parse(msg: &Self::Message, _: &Session) -> Self {
  134. let artists = msg
  135. .get_artist()
  136. .iter()
  137. .filter(|artist| artist.has_gid())
  138. .map(|artist| SpotifyId::from_raw(artist.get_gid()).unwrap())
  139. .collect::<Vec<_>>();
  140. let tracks = msg
  141. .get_disc()
  142. .iter()
  143. .flat_map(|disc| disc.get_track())
  144. .filter(|track| track.has_gid())
  145. .map(|track| SpotifyId::from_raw(track.get_gid()).unwrap())
  146. .collect::<Vec<_>>();
  147. let covers = msg
  148. .get_cover_group()
  149. .get_image()
  150. .iter()
  151. .filter(|image| image.has_file_id())
  152. .map(|image| {
  153. let mut dst = [0u8; 20];
  154. dst.clone_from_slice(image.get_file_id());
  155. FileId(dst)
  156. })
  157. .collect::<Vec<_>>();
  158. Album {
  159. id: SpotifyId::from_raw(msg.get_gid()).unwrap(),
  160. name: msg.get_name().to_owned(),
  161. artists: artists,
  162. tracks: tracks,
  163. covers: covers,
  164. }
  165. }
  166. }
  167. impl Metadata for Playlist {
  168. type Message = protocol::playlist4changes::SelectedListContent;
  169. fn request_url(id: SpotifyId) -> String {
  170. format!("hm://playlist/v2/playlist/{}", id.to_base62())
  171. }
  172. fn parse(msg: &Self::Message, _: &Session) -> Self {
  173. let tracks = msg
  174. .get_contents()
  175. .get_items()
  176. .iter()
  177. .map(|item| {
  178. let uri_split = item.get_uri().split(":");
  179. let uri_parts: Vec<&str> = uri_split.collect();
  180. SpotifyId::from_base62(uri_parts[2]).unwrap()
  181. })
  182. .collect::<Vec<_>>();
  183. Playlist {
  184. name: msg.get_attributes().get_name().to_owned(),
  185. length: msg.get_length(),
  186. tracks: tracks,
  187. user: msg.get_owner_username().to_string(),
  188. }
  189. }
  190. }
  191. impl Metadata for Artist {
  192. type Message = protocol::metadata::Artist;
  193. fn request_url(id: SpotifyId) -> String {
  194. format!("hm://metadata/3/artist/{}", id.to_base16())
  195. }
  196. fn parse(msg: &Self::Message, session: &Session) -> Self {
  197. let country = session.country();
  198. let top_tracks: Vec<SpotifyId> = match msg
  199. .get_top_track()
  200. .iter()
  201. .find(|tt| !tt.has_country() || countrylist_contains(tt.get_country(), &country))
  202. {
  203. Some(tracks) => tracks
  204. .get_track()
  205. .iter()
  206. .filter(|track| track.has_gid())
  207. .map(|track| SpotifyId::from_raw(track.get_gid()).unwrap())
  208. .collect::<Vec<_>>(),
  209. None => Vec::new(),
  210. };
  211. Artist {
  212. id: SpotifyId::from_raw(msg.get_gid()).unwrap(),
  213. name: msg.get_name().to_owned(),
  214. top_tracks: top_tracks,
  215. }
  216. }
  217. }
  218. struct StrChunks<'s>(&'s str, usize);
  219. trait StrChunksExt {
  220. fn chunks(&self, size: usize) -> StrChunks;
  221. }
  222. impl StrChunksExt for str {
  223. fn chunks(&self, size: usize) -> StrChunks {
  224. StrChunks(self, size)
  225. }
  226. }
  227. impl<'s> Iterator for StrChunks<'s> {
  228. type Item = &'s str;
  229. fn next(&mut self) -> Option<&'s str> {
  230. let &mut StrChunks(data, size) = self;
  231. if data.is_empty() {
  232. None
  233. } else {
  234. let ret = Some(&data[..size]);
  235. self.0 = &data[size..];
  236. ret
  237. }
  238. }
  239. }