session.rs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. use crypto::digest::Digest;
  2. use crypto::sha1::Sha1;
  3. use futures::sync::mpsc;
  4. use futures::{Future, Stream, BoxFuture, IntoFuture, Poll, Async};
  5. use std::io;
  6. use std::result::Result;
  7. use std::str::FromStr;
  8. use std::sync::{RwLock, Arc, Weak};
  9. use tokio_core::io::EasyBuf;
  10. use tokio_core::reactor::{Handle, Remote};
  11. use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
  12. use uuid::Uuid;
  13. use apresolve::apresolve_or_fallback;
  14. use authentication::Credentials;
  15. use cache::Cache;
  16. use component::Lazy;
  17. use connection;
  18. use version;
  19. use audio_key::AudioKeyManager;
  20. use channel::ChannelManager;
  21. use mercury::MercuryManager;
  22. use metadata::MetadataManager;
  23. use audio_file::AudioFileManager;
  24. #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)]
  25. pub enum Bitrate {
  26. Bitrate96,
  27. Bitrate160,
  28. Bitrate320,
  29. }
  30. impl FromStr for Bitrate {
  31. type Err = String;
  32. fn from_str(s: &str) -> Result<Self, Self::Err> {
  33. match s {
  34. "96" => Ok(Bitrate::Bitrate96),
  35. "160" => Ok(Bitrate::Bitrate160),
  36. "320" => Ok(Bitrate::Bitrate320),
  37. _ => Err(s.into()),
  38. }
  39. }
  40. }
  41. #[derive(Clone)]
  42. pub struct Config {
  43. pub user_agent: String,
  44. pub device_id: String,
  45. pub bitrate: Bitrate,
  46. pub onstart: Option<String>,
  47. pub onstop: Option<String>,
  48. }
  49. impl Default for Config {
  50. fn default() -> Config {
  51. let device_id = Uuid::new_v4().hyphenated().to_string();
  52. Config {
  53. user_agent: version::version_string(),
  54. device_id: device_id,
  55. bitrate: Bitrate::Bitrate160,
  56. onstart: None,
  57. onstop: None,
  58. }
  59. }
  60. }
  61. pub struct SessionData {
  62. country: String,
  63. canonical_username: String,
  64. }
  65. pub struct SessionInternal {
  66. config: Config,
  67. data: RwLock<SessionData>,
  68. tx_connection: mpsc::UnboundedSender<(u8, Vec<u8>)>,
  69. audio_key: Lazy<AudioKeyManager>,
  70. audio_file: Lazy<AudioFileManager>,
  71. channel: Lazy<ChannelManager>,
  72. mercury: Lazy<MercuryManager>,
  73. metadata: Lazy<MetadataManager>,
  74. cache: Option<Arc<Cache>>,
  75. handle: Remote,
  76. session_id: usize,
  77. }
  78. static SESSION_COUNTER : AtomicUsize = ATOMIC_USIZE_INIT;
  79. #[derive(Clone)]
  80. pub struct Session(pub Arc<SessionInternal>);
  81. pub fn device_id(name: &str) -> String {
  82. let mut h = Sha1::new();
  83. h.input_str(name);
  84. h.result_str()
  85. }
  86. impl Session {
  87. pub fn connect(config: Config, credentials: Credentials,
  88. cache: Option<Cache>, handle: Handle)
  89. -> Box<Future<Item=Session, Error=io::Error>>
  90. {
  91. let access_point = apresolve_or_fallback::<io::Error>(&handle);
  92. let handle_ = handle.clone();
  93. let connection = access_point.and_then(move |addr| {
  94. info!("Connecting to AP \"{}\"", addr);
  95. connection::connect::<&str>(&addr, &handle_)
  96. });
  97. let device_id = config.device_id.clone();
  98. let authentication = connection.and_then(move |connection| {
  99. connection::authenticate(connection, credentials, device_id)
  100. });
  101. let result = authentication.map(move |(transport, reusable_credentials)| {
  102. info!("Authenticated as \"{}\" !", reusable_credentials.username);
  103. if let Some(ref cache) = cache {
  104. cache.save_credentials(&reusable_credentials);
  105. }
  106. let (session, task) = Session::create(
  107. &handle, transport, config, cache, reusable_credentials.username.clone()
  108. );
  109. handle.spawn(task.map_err(|e| panic!(e)));
  110. session
  111. });
  112. Box::new(result)
  113. }
  114. fn create(handle: &Handle, transport: connection::Transport,
  115. config: Config, cache: Option<Cache>, username: String)
  116. -> (Session, BoxFuture<(), io::Error>)
  117. {
  118. let (sink, stream) = transport.split();
  119. let (sender_tx, sender_rx) = mpsc::unbounded();
  120. let session_id = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
  121. debug!("new Session[{}]", session_id);
  122. let session = Session(Arc::new(SessionInternal {
  123. config: config,
  124. data: RwLock::new(SessionData {
  125. country: String::new(),
  126. canonical_username: username,
  127. }),
  128. tx_connection: sender_tx,
  129. cache: cache.map(Arc::new),
  130. audio_key: Lazy::new(),
  131. audio_file: Lazy::new(),
  132. channel: Lazy::new(),
  133. mercury: Lazy::new(),
  134. metadata: Lazy::new(),
  135. handle: handle.remote().clone(),
  136. session_id: session_id,
  137. }));
  138. let sender_task = sender_rx
  139. .map_err(|e| -> io::Error { panic!(e) })
  140. .forward(sink).map(|_| ());
  141. let receiver_task = DispatchTask(stream, session.weak());
  142. let task = (receiver_task, sender_task).into_future()
  143. .map(|((), ())| ()).boxed();
  144. (session, task)
  145. }
  146. pub fn audio_key(&self) -> &AudioKeyManager {
  147. self.0.audio_key.get(|| AudioKeyManager::new(self.weak()))
  148. }
  149. pub fn audio_file(&self) -> &AudioFileManager {
  150. self.0.audio_file.get(|| AudioFileManager::new(self.weak()))
  151. }
  152. pub fn channel(&self) -> &ChannelManager {
  153. self.0.channel.get(|| ChannelManager::new(self.weak()))
  154. }
  155. pub fn mercury(&self) -> &MercuryManager {
  156. self.0.mercury.get(|| MercuryManager::new(self.weak()))
  157. }
  158. pub fn metadata(&self) -> &MetadataManager {
  159. self.0.metadata.get(|| MetadataManager::new(self.weak()))
  160. }
  161. pub fn spawn<F, R>(&self, f: F)
  162. where F: FnOnce(&Handle) -> R + Send + 'static,
  163. R: IntoFuture<Item=(), Error=()>,
  164. R::Future: 'static
  165. {
  166. self.0.handle.spawn(f)
  167. }
  168. fn debug_info(&self) {
  169. debug!("Session[{}] strong={} weak={}",
  170. self.0.session_id, Arc::strong_count(&self.0), Arc::weak_count(&self.0));
  171. }
  172. #[cfg_attr(feature = "cargo-clippy", allow(match_same_arms))]
  173. fn dispatch(&self, cmd: u8, data: EasyBuf) {
  174. match cmd {
  175. 0x4 => {
  176. self.debug_info();
  177. self.send_packet(0x49, data.as_ref().to_owned());
  178. },
  179. 0x4a => (),
  180. 0x1b => {
  181. let country = String::from_utf8(data.as_ref().to_owned()).unwrap();
  182. info!("Country: {:?}", country);
  183. self.0.data.write().unwrap().country = country;
  184. }
  185. 0x9 | 0xa => self.channel().dispatch(cmd, data),
  186. 0xd | 0xe => self.audio_key().dispatch(cmd, data),
  187. 0xb2...0xb6 => self.mercury().dispatch(cmd, data),
  188. _ => (),
  189. }
  190. }
  191. pub fn send_packet(&self, cmd: u8, data: Vec<u8>) {
  192. self.0.tx_connection.send((cmd, data)).unwrap();
  193. }
  194. pub fn cache(&self) -> Option<&Arc<Cache>> {
  195. self.0.cache.as_ref()
  196. }
  197. pub fn config(&self) -> &Config {
  198. &self.0.config
  199. }
  200. pub fn username(&self) -> String {
  201. self.0.data.read().unwrap().canonical_username.clone()
  202. }
  203. pub fn country(&self) -> String {
  204. self.0.data.read().unwrap().country.clone()
  205. }
  206. pub fn device_id(&self) -> &str {
  207. &self.config().device_id
  208. }
  209. pub fn weak(&self) -> SessionWeak {
  210. SessionWeak(Arc::downgrade(&self.0))
  211. }
  212. pub fn session_id(&self) -> usize {
  213. self.0.session_id
  214. }
  215. }
  216. #[derive(Clone)]
  217. pub struct SessionWeak(pub Weak<SessionInternal>);
  218. impl SessionWeak {
  219. pub fn try_upgrade(&self) -> Option<Session> {
  220. self.0.upgrade().map(Session)
  221. }
  222. pub fn upgrade(&self) -> Session {
  223. self.try_upgrade().expect("Session died")
  224. }
  225. }
  226. impl Drop for SessionInternal {
  227. fn drop(&mut self) {
  228. debug!("drop Session[{}]", self.session_id);
  229. }
  230. }
  231. struct DispatchTask<S>(S, SessionWeak)
  232. where S: Stream<Item = (u8, EasyBuf)>;
  233. impl <S> Future for DispatchTask<S>
  234. where S: Stream<Item = (u8, EasyBuf)>
  235. {
  236. type Item = ();
  237. type Error = S::Error;
  238. fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
  239. let session = match self.1.try_upgrade() {
  240. Some(session) => session,
  241. None => {
  242. return Ok(Async::Ready(()))
  243. },
  244. };
  245. loop {
  246. let (cmd, data) = try_ready!(self.0.poll()).expect("connection closed");
  247. session.dispatch(cmd, data);
  248. }
  249. }
  250. }
  251. impl <S> Drop for DispatchTask<S>
  252. where S: Stream<Item = (u8, EasyBuf)>
  253. {
  254. fn drop(&mut self) {
  255. debug!("drop Dispatch");
  256. }
  257. }