lib.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. #[macro_use]
  2. extern crate log;
  3. extern crate byteorder;
  4. extern crate futures;
  5. extern crate linear_map;
  6. extern crate protobuf;
  7. extern crate librespot_core;
  8. extern crate librespot_protocol as protocol;
  9. pub mod cover;
  10. use futures::future;
  11. use futures::Future;
  12. use linear_map::LinearMap;
  13. use librespot_core::mercury::MercuryError;
  14. use librespot_core::session::Session;
  15. use librespot_core::spotify_id::{FileId, SpotifyAudioType, SpotifyId};
  16. pub use crate::protocol::metadata::AudioFile_Format as FileFormat;
  17. fn countrylist_contains(list: &str, country: &str) -> bool {
  18. list.chunks(2).any(|cc| cc == country)
  19. }
  20. fn parse_restrictions<'s, I>(restrictions: I, country: &str, catalogue: &str) -> bool
  21. where
  22. I: IntoIterator<Item = &'s protocol::metadata::Restriction>,
  23. {
  24. let mut forbidden = "".to_string();
  25. let mut has_forbidden = false;
  26. let mut allowed = "".to_string();
  27. let mut has_allowed = false;
  28. let rs = restrictions
  29. .into_iter()
  30. .filter(|r| r.get_catalogue_str().contains(&catalogue.to_owned()));
  31. for r in rs {
  32. if r.has_countries_forbidden() {
  33. forbidden.push_str(r.get_countries_forbidden());
  34. has_forbidden = true;
  35. }
  36. if r.has_countries_allowed() {
  37. allowed.push_str(r.get_countries_allowed());
  38. has_allowed = true;
  39. }
  40. }
  41. (has_forbidden || has_allowed)
  42. && (!has_forbidden || !countrylist_contains(forbidden.as_str(), country))
  43. && (!has_allowed || countrylist_contains(allowed.as_str(), country))
  44. }
  45. // A wrapper with fields the player needs
  46. #[derive(Debug, Clone)]
  47. pub struct AudioItem {
  48. pub id: SpotifyId,
  49. pub uri: String,
  50. pub files: LinearMap<FileFormat, FileId>,
  51. pub name: String,
  52. pub available: bool,
  53. pub alternatives: Option<Vec<SpotifyId>>,
  54. }
  55. impl AudioItem {
  56. pub fn get_audio_item(
  57. session: &Session,
  58. id: SpotifyId,
  59. ) -> Box<dyn Future<Item = AudioItem, Error = MercuryError>> {
  60. match id.audio_type {
  61. SpotifyAudioType::Track => Track::get_audio_item(session, id),
  62. SpotifyAudioType::Podcast => Episode::get_audio_item(session, id),
  63. SpotifyAudioType::NonPlayable => {
  64. Box::new(future::err::<AudioItem, MercuryError>(MercuryError))
  65. }
  66. }
  67. }
  68. }
  69. trait AudioFiles {
  70. fn get_audio_item(
  71. session: &Session,
  72. id: SpotifyId,
  73. ) -> Box<dyn Future<Item = AudioItem, Error = MercuryError>>;
  74. }
  75. impl AudioFiles for Track {
  76. fn get_audio_item(
  77. session: &Session,
  78. id: SpotifyId,
  79. ) -> Box<dyn Future<Item = AudioItem, Error = MercuryError>> {
  80. Box::new(Self::get(session, id).and_then(move |item| {
  81. Ok(AudioItem {
  82. id: id,
  83. uri: format!("spotify:track:{}", id.to_base62()),
  84. files: item.files,
  85. name: item.name,
  86. available: item.available,
  87. alternatives: Some(item.alternatives),
  88. })
  89. }))
  90. }
  91. }
  92. impl AudioFiles for Episode {
  93. fn get_audio_item(
  94. session: &Session,
  95. id: SpotifyId,
  96. ) -> Box<dyn Future<Item = AudioItem, Error = MercuryError>> {
  97. Box::new(Self::get(session, id).and_then(move |item| {
  98. Ok(AudioItem {
  99. id: id,
  100. uri: format!("spotify:episode:{}", id.to_base62()),
  101. files: item.files,
  102. name: item.name,
  103. available: item.available,
  104. alternatives: None,
  105. })
  106. }))
  107. }
  108. }
  109. pub trait Metadata: Send + Sized + 'static {
  110. type Message: protobuf::Message;
  111. fn request_url(id: SpotifyId) -> String;
  112. fn parse(msg: &Self::Message, session: &Session) -> Self;
  113. fn get(session: &Session, id: SpotifyId) -> Box<dyn Future<Item = Self, Error = MercuryError>> {
  114. let uri = Self::request_url(id);
  115. let request = session.mercury().get(uri);
  116. let session = session.clone();
  117. Box::new(request.and_then(move |response| {
  118. let data = response.payload.first().expect("Empty payload");
  119. let msg: Self::Message = protobuf::parse_from_bytes(data).unwrap();
  120. Ok(Self::parse(&msg, &session))
  121. }))
  122. }
  123. }
  124. #[derive(Debug, Clone)]
  125. pub struct Track {
  126. pub id: SpotifyId,
  127. pub name: String,
  128. pub duration: i32,
  129. pub album: SpotifyId,
  130. pub artists: Vec<SpotifyId>,
  131. pub files: LinearMap<FileFormat, FileId>,
  132. pub alternatives: Vec<SpotifyId>,
  133. pub available: bool,
  134. }
  135. #[derive(Debug, Clone)]
  136. pub struct Album {
  137. pub id: SpotifyId,
  138. pub name: String,
  139. pub artists: Vec<SpotifyId>,
  140. pub tracks: Vec<SpotifyId>,
  141. pub covers: Vec<FileId>,
  142. }
  143. #[derive(Debug, Clone)]
  144. pub struct Episode {
  145. pub id: SpotifyId,
  146. pub name: String,
  147. pub external_url: String,
  148. pub duration: i32,
  149. pub language: String,
  150. pub show: SpotifyId,
  151. pub files: LinearMap<FileFormat, FileId>,
  152. pub covers: Vec<FileId>,
  153. pub available: bool,
  154. pub explicit: bool,
  155. }
  156. #[derive(Debug, Clone)]
  157. pub struct Show {
  158. pub id: SpotifyId,
  159. pub name: String,
  160. pub publisher: String,
  161. pub episodes: Vec<SpotifyId>,
  162. pub covers: Vec<FileId>,
  163. }
  164. #[derive(Debug, Clone)]
  165. pub struct Playlist {
  166. pub revision: Vec<u8>,
  167. pub user: String,
  168. pub name: String,
  169. pub tracks: Vec<SpotifyId>,
  170. }
  171. #[derive(Debug, Clone)]
  172. pub struct Artist {
  173. pub id: SpotifyId,
  174. pub name: String,
  175. pub top_tracks: Vec<SpotifyId>,
  176. }
  177. impl Metadata for Track {
  178. type Message = protocol::metadata::Track;
  179. fn request_url(id: SpotifyId) -> String {
  180. format!("hm://metadata/3/track/{}", id.to_base16())
  181. }
  182. fn parse(msg: &Self::Message, session: &Session) -> Self {
  183. let country = session.country();
  184. let artists = msg
  185. .get_artist()
  186. .iter()
  187. .filter(|artist| artist.has_gid())
  188. .map(|artist| SpotifyId::from_raw(artist.get_gid()).unwrap())
  189. .collect::<Vec<_>>();
  190. let files = msg
  191. .get_file()
  192. .iter()
  193. .filter(|file| file.has_file_id())
  194. .map(|file| {
  195. let mut dst = [0u8; 20];
  196. dst.clone_from_slice(file.get_file_id());
  197. (file.get_format(), FileId(dst))
  198. })
  199. .collect();
  200. Track {
  201. id: SpotifyId::from_raw(msg.get_gid()).unwrap(),
  202. name: msg.get_name().to_owned(),
  203. duration: msg.get_duration(),
  204. album: SpotifyId::from_raw(msg.get_album().get_gid()).unwrap(),
  205. artists: artists,
  206. files: files,
  207. alternatives: msg
  208. .get_alternative()
  209. .iter()
  210. .map(|alt| SpotifyId::from_raw(alt.get_gid()).unwrap())
  211. .collect(),
  212. available: parse_restrictions(msg.get_restriction(), &country, "premium"),
  213. }
  214. }
  215. }
  216. impl Metadata for Album {
  217. type Message = protocol::metadata::Album;
  218. fn request_url(id: SpotifyId) -> String {
  219. format!("hm://metadata/3/album/{}", id.to_base16())
  220. }
  221. fn parse(msg: &Self::Message, _: &Session) -> Self {
  222. let artists = msg
  223. .get_artist()
  224. .iter()
  225. .filter(|artist| artist.has_gid())
  226. .map(|artist| SpotifyId::from_raw(artist.get_gid()).unwrap())
  227. .collect::<Vec<_>>();
  228. let tracks = msg
  229. .get_disc()
  230. .iter()
  231. .flat_map(|disc| disc.get_track())
  232. .filter(|track| track.has_gid())
  233. .map(|track| SpotifyId::from_raw(track.get_gid()).unwrap())
  234. .collect::<Vec<_>>();
  235. let covers = msg
  236. .get_cover_group()
  237. .get_image()
  238. .iter()
  239. .filter(|image| image.has_file_id())
  240. .map(|image| {
  241. let mut dst = [0u8; 20];
  242. dst.clone_from_slice(image.get_file_id());
  243. FileId(dst)
  244. })
  245. .collect::<Vec<_>>();
  246. Album {
  247. id: SpotifyId::from_raw(msg.get_gid()).unwrap(),
  248. name: msg.get_name().to_owned(),
  249. artists: artists,
  250. tracks: tracks,
  251. covers: covers,
  252. }
  253. }
  254. }
  255. impl Metadata for Playlist {
  256. type Message = protocol::playlist4changes::SelectedListContent;
  257. fn request_url(id: SpotifyId) -> String {
  258. format!("hm://playlist/v2/playlist/{}", id.to_base62())
  259. }
  260. fn parse(msg: &Self::Message, _: &Session) -> Self {
  261. let tracks = msg
  262. .get_contents()
  263. .get_items()
  264. .iter()
  265. .map(|item| {
  266. let uri_split = item.get_uri().split(":");
  267. let uri_parts: Vec<&str> = uri_split.collect();
  268. SpotifyId::from_base62(uri_parts[2]).unwrap()
  269. })
  270. .collect::<Vec<_>>();
  271. if tracks.len() != msg.get_length() as usize {
  272. warn!("Got {} tracks, but the playlist should contain {} tracks.", tracks.len(), msg.get_length());
  273. }
  274. Playlist {
  275. revision: msg.get_revision().to_vec(),
  276. name: msg.get_attributes().get_name().to_owned(),
  277. tracks: tracks,
  278. user: msg.get_owner_username().to_string(),
  279. }
  280. }
  281. }
  282. impl Metadata for Artist {
  283. type Message = protocol::metadata::Artist;
  284. fn request_url(id: SpotifyId) -> String {
  285. format!("hm://metadata/3/artist/{}", id.to_base16())
  286. }
  287. fn parse(msg: &Self::Message, session: &Session) -> Self {
  288. let country = session.country();
  289. let top_tracks: Vec<SpotifyId> = match msg
  290. .get_top_track()
  291. .iter()
  292. .find(|tt| !tt.has_country() || countrylist_contains(tt.get_country(), &country))
  293. {
  294. Some(tracks) => tracks
  295. .get_track()
  296. .iter()
  297. .filter(|track| track.has_gid())
  298. .map(|track| SpotifyId::from_raw(track.get_gid()).unwrap())
  299. .collect::<Vec<_>>(),
  300. None => Vec::new(),
  301. };
  302. Artist {
  303. id: SpotifyId::from_raw(msg.get_gid()).unwrap(),
  304. name: msg.get_name().to_owned(),
  305. top_tracks: top_tracks,
  306. }
  307. }
  308. }
  309. // Podcast
  310. impl Metadata for Episode {
  311. type Message = protocol::metadata::Episode;
  312. fn request_url(id: SpotifyId) -> String {
  313. format!("hm://metadata/3/episode/{}", id.to_base16())
  314. }
  315. fn parse(msg: &Self::Message, session: &Session) -> Self {
  316. let country = session.country();
  317. let files = msg
  318. .get_file()
  319. .iter()
  320. .filter(|file| file.has_file_id())
  321. .map(|file| {
  322. let mut dst = [0u8; 20];
  323. dst.clone_from_slice(file.get_file_id());
  324. (file.get_format(), FileId(dst))
  325. })
  326. .collect();
  327. let covers = msg
  328. .get_covers()
  329. .get_image()
  330. .iter()
  331. .filter(|image| image.has_file_id())
  332. .map(|image| {
  333. let mut dst = [0u8; 20];
  334. dst.clone_from_slice(image.get_file_id());
  335. FileId(dst)
  336. })
  337. .collect::<Vec<_>>();
  338. Episode {
  339. id: SpotifyId::from_raw(msg.get_gid()).unwrap(),
  340. name: msg.get_name().to_owned(),
  341. external_url: msg.get_external_url().to_owned(),
  342. duration: msg.get_duration().to_owned(),
  343. language: msg.get_language().to_owned(),
  344. show: SpotifyId::from_raw(msg.get_show().get_gid()).unwrap(),
  345. covers: covers,
  346. files: files,
  347. available: parse_restrictions(msg.get_restriction(), &country, "premium"),
  348. explicit: msg.get_explicit().to_owned(),
  349. }
  350. }
  351. }
  352. impl Metadata for Show {
  353. type Message = protocol::metadata::Show;
  354. fn request_url(id: SpotifyId) -> String {
  355. format!("hm://metadata/3/show/{}", id.to_base16())
  356. }
  357. fn parse(msg: &Self::Message, _: &Session) -> Self {
  358. let episodes = msg
  359. .get_episode()
  360. .iter()
  361. .filter(|episode| episode.has_gid())
  362. .map(|episode| SpotifyId::from_raw(episode.get_gid()).unwrap())
  363. .collect::<Vec<_>>();
  364. let covers = msg
  365. .get_covers()
  366. .get_image()
  367. .iter()
  368. .filter(|image| image.has_file_id())
  369. .map(|image| {
  370. let mut dst = [0u8; 20];
  371. dst.clone_from_slice(image.get_file_id());
  372. FileId(dst)
  373. })
  374. .collect::<Vec<_>>();
  375. Show {
  376. id: SpotifyId::from_raw(msg.get_gid()).unwrap(),
  377. name: msg.get_name().to_owned(),
  378. publisher: msg.get_publisher().to_owned(),
  379. episodes: episodes,
  380. covers: covers,
  381. }
  382. }
  383. }
  384. struct StrChunks<'s>(&'s str, usize);
  385. trait StrChunksExt {
  386. fn chunks(&self, size: usize) -> StrChunks;
  387. }
  388. impl StrChunksExt for str {
  389. fn chunks(&self, size: usize) -> StrChunks {
  390. StrChunks(self, size)
  391. }
  392. }
  393. impl<'s> Iterator for StrChunks<'s> {
  394. type Item = &'s str;
  395. fn next(&mut self) -> Option<&'s str> {
  396. let &mut StrChunks(data, size) = self;
  397. if data.is_empty() {
  398. None
  399. } else {
  400. let ret = Some(&data[..size]);
  401. self.0 = &data[size..];
  402. ret
  403. }
  404. }
  405. }