spirc.rs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  1. use std;
  2. use std::time::{SystemTime, UNIX_EPOCH};
  3. use futures::future;
  4. use futures::sync::mpsc;
  5. use futures::{Async, Future, Poll, Sink, Stream};
  6. use protobuf::{self, Message};
  7. use rand;
  8. use rand::seq::SliceRandom;
  9. use serde_json;
  10. use crate::context::StationContext;
  11. use crate::playback::mixer::Mixer;
  12. use crate::playback::player::{Player, PlayerEvent, PlayerEventChannel};
  13. use crate::protocol;
  14. use crate::protocol::spirc::{DeviceState, Frame, MessageType, PlayStatus, State, TrackRef};
  15. use librespot_core::config::{ConnectConfig, VolumeCtrl};
  16. use librespot_core::mercury::MercuryError;
  17. use librespot_core::session::Session;
  18. use librespot_core::spotify_id::{SpotifyAudioType, SpotifyId, SpotifyIdError};
  19. use librespot_core::util::url_encode;
  20. use librespot_core::util::SeqGenerator;
  21. use librespot_core::version;
  22. use librespot_core::volume::Volume;
  23. enum SpircPlayStatus {
  24. Stopped,
  25. LoadingPlay {
  26. position_ms: u32,
  27. },
  28. LoadingPause {
  29. position_ms: u32,
  30. },
  31. Playing {
  32. nominal_start_time: i64,
  33. preloading_of_next_track_triggered: bool,
  34. },
  35. Paused {
  36. position_ms: u32,
  37. preloading_of_next_track_triggered: bool,
  38. },
  39. }
  40. pub struct SpircTask {
  41. player: Player,
  42. mixer: Box<dyn Mixer>,
  43. config: SpircTaskConfig,
  44. sequence: SeqGenerator<u32>,
  45. ident: String,
  46. device: DeviceState,
  47. state: State,
  48. play_request_id: Option<u64>,
  49. mixer_started: bool,
  50. play_status: SpircPlayStatus,
  51. subscription: Box<dyn Stream<Item = Frame, Error = MercuryError>>,
  52. sender: Box<dyn Sink<SinkItem = Frame, SinkError = MercuryError>>,
  53. commands: mpsc::UnboundedReceiver<SpircCommand>,
  54. player_events: PlayerEventChannel,
  55. shutdown: bool,
  56. session: Session,
  57. context_fut: Box<dyn Future<Item = serde_json::Value, Error = MercuryError>>,
  58. autoplay_fut: Box<dyn Future<Item = String, Error = MercuryError>>,
  59. context: Option<StationContext>,
  60. }
  61. pub enum SpircCommand {
  62. Play,
  63. PlayPause,
  64. Pause,
  65. Prev,
  66. Next,
  67. VolumeUp,
  68. VolumeDown,
  69. Shutdown,
  70. }
  71. struct SpircTaskConfig {
  72. volume_ctrl: VolumeCtrl,
  73. autoplay: bool,
  74. }
  75. const CONTEXT_TRACKS_HISTORY: usize = 10;
  76. const CONTEXT_FETCH_THRESHOLD: u32 = 5;
  77. pub struct Spirc {
  78. commands: mpsc::UnboundedSender<SpircCommand>,
  79. }
  80. fn initial_state() -> State {
  81. let mut frame = protocol::spirc::State::new();
  82. frame.set_repeat(false);
  83. frame.set_shuffle(false);
  84. frame.set_status(PlayStatus::kPlayStatusStop);
  85. frame.set_position_ms(0);
  86. frame.set_position_measured_at(0);
  87. frame
  88. }
  89. fn initial_device_state(config: ConnectConfig) -> DeviceState {
  90. {
  91. let mut msg = DeviceState::new();
  92. msg.set_sw_version(version::version_string());
  93. msg.set_is_active(false);
  94. msg.set_can_play(true);
  95. msg.set_volume(0);
  96. msg.set_name(config.name);
  97. {
  98. let repeated = msg.mut_capabilities();
  99. {
  100. let msg = repeated.push_default();
  101. msg.set_typ(protocol::spirc::CapabilityType::kCanBePlayer);
  102. {
  103. let repeated = msg.mut_intValue();
  104. repeated.push(1)
  105. };
  106. msg
  107. };
  108. {
  109. let msg = repeated.push_default();
  110. msg.set_typ(protocol::spirc::CapabilityType::kDeviceType);
  111. {
  112. let repeated = msg.mut_intValue();
  113. repeated.push(config.device_type as i64)
  114. };
  115. msg
  116. };
  117. {
  118. let msg = repeated.push_default();
  119. msg.set_typ(protocol::spirc::CapabilityType::kGaiaEqConnectId);
  120. {
  121. let repeated = msg.mut_intValue();
  122. repeated.push(1)
  123. };
  124. msg
  125. };
  126. {
  127. let msg = repeated.push_default();
  128. msg.set_typ(protocol::spirc::CapabilityType::kSupportsLogout);
  129. {
  130. let repeated = msg.mut_intValue();
  131. repeated.push(0)
  132. };
  133. msg
  134. };
  135. {
  136. let msg = repeated.push_default();
  137. msg.set_typ(protocol::spirc::CapabilityType::kIsObservable);
  138. {
  139. let repeated = msg.mut_intValue();
  140. repeated.push(1)
  141. };
  142. msg
  143. };
  144. {
  145. let msg = repeated.push_default();
  146. msg.set_typ(protocol::spirc::CapabilityType::kVolumeSteps);
  147. {
  148. let repeated = msg.mut_intValue();
  149. if let VolumeCtrl::Fixed = config.volume_ctrl {
  150. repeated.push(0)
  151. } else {
  152. repeated.push(64)
  153. }
  154. };
  155. msg
  156. };
  157. {
  158. let msg = repeated.push_default();
  159. msg.set_typ(protocol::spirc::CapabilityType::kSupportsPlaylistV2);
  160. {
  161. let repeated = msg.mut_intValue();
  162. repeated.push(1)
  163. };
  164. msg
  165. };
  166. {
  167. let msg = repeated.push_default();
  168. msg.set_typ(protocol::spirc::CapabilityType::kSupportedContexts);
  169. {
  170. let repeated = msg.mut_stringValue();
  171. repeated.push(::std::convert::Into::into("album"));
  172. repeated.push(::std::convert::Into::into("playlist"));
  173. repeated.push(::std::convert::Into::into("search"));
  174. repeated.push(::std::convert::Into::into("inbox"));
  175. repeated.push(::std::convert::Into::into("toplist"));
  176. repeated.push(::std::convert::Into::into("starred"));
  177. repeated.push(::std::convert::Into::into("publishedstarred"));
  178. repeated.push(::std::convert::Into::into("track"))
  179. };
  180. msg
  181. };
  182. {
  183. let msg = repeated.push_default();
  184. msg.set_typ(protocol::spirc::CapabilityType::kSupportedTypes);
  185. {
  186. let repeated = msg.mut_stringValue();
  187. repeated.push(::std::convert::Into::into("audio/local"));
  188. repeated.push(::std::convert::Into::into("audio/track"));
  189. repeated.push(::std::convert::Into::into("audio/episode"));
  190. repeated.push(::std::convert::Into::into("local"));
  191. repeated.push(::std::convert::Into::into("track"))
  192. };
  193. msg
  194. };
  195. };
  196. msg
  197. }
  198. }
  199. fn calc_logarithmic_volume(volume: u16) -> u16 {
  200. // Volume conversion taken from https://www.dr-lex.be/info-stuff/volumecontrols.html#ideal2
  201. // Convert the given volume [0..0xffff] to a dB gain
  202. // We assume a dB range of 60dB.
  203. // Use the equation: a * exp(b * x)
  204. // in which a = IDEAL_FACTOR, b = 1/1000
  205. const IDEAL_FACTOR: f64 = 6.908;
  206. let normalized_volume = volume as f64 / std::u16::MAX as f64; // To get a value between 0 and 1
  207. let mut val = std::u16::MAX;
  208. // Prevent val > std::u16::MAX due to rounding errors
  209. if normalized_volume < 0.999 {
  210. let new_volume = (normalized_volume * IDEAL_FACTOR).exp() / 1000.0;
  211. val = (new_volume * std::u16::MAX as f64) as u16;
  212. }
  213. debug!("input volume:{} to mixer: {}", volume, val);
  214. // return the scale factor (0..0xffff) (equivalent to a voltage multiplier).
  215. val
  216. }
  217. fn volume_to_mixer(volume: u16, volume_ctrl: &VolumeCtrl) -> u16 {
  218. match volume_ctrl {
  219. VolumeCtrl::Linear => volume,
  220. VolumeCtrl::Log => calc_logarithmic_volume(volume),
  221. VolumeCtrl::Fixed => volume,
  222. }
  223. }
  224. impl Spirc {
  225. pub fn new(
  226. config: ConnectConfig,
  227. session: Session,
  228. player: Player,
  229. mixer: Box<dyn Mixer>,
  230. ) -> (Spirc, SpircTask) {
  231. debug!("new Spirc[{}]", session.session_id());
  232. let ident = session.device_id().to_owned();
  233. // Uri updated in response to issue #288
  234. debug!("canonical_username: {}", url_encode(&session.username()));
  235. let uri = format!("hm://remote/user/{}/", url_encode(&session.username()));
  236. let subscription = session.mercury().subscribe(&uri as &str);
  237. let subscription = subscription
  238. .map(|stream| stream.map_err(|_| MercuryError))
  239. .flatten_stream();
  240. let subscription = Box::new(subscription.map(|response| -> Frame {
  241. let data = response.payload.first().unwrap();
  242. protobuf::parse_from_bytes(data).unwrap()
  243. }));
  244. let sender = Box::new(
  245. session
  246. .mercury()
  247. .sender(uri)
  248. .with(|frame: Frame| Ok(frame.write_to_bytes().unwrap())),
  249. );
  250. let (cmd_tx, cmd_rx) = mpsc::unbounded();
  251. let volume = config.volume;
  252. let task_config = SpircTaskConfig {
  253. volume_ctrl: config.volume_ctrl.to_owned(),
  254. autoplay: config.autoplay,
  255. };
  256. let device = initial_device_state(config);
  257. let player_events = player.get_player_event_channel();
  258. let mut task = SpircTask {
  259. player: player,
  260. mixer: mixer,
  261. config: task_config,
  262. sequence: SeqGenerator::new(1),
  263. ident: ident,
  264. device: device,
  265. state: initial_state(),
  266. play_request_id: None,
  267. mixer_started: false,
  268. play_status: SpircPlayStatus::Stopped,
  269. subscription: subscription,
  270. sender: sender,
  271. commands: cmd_rx,
  272. player_events: player_events,
  273. shutdown: false,
  274. session: session.clone(),
  275. context_fut: Box::new(future::empty()),
  276. autoplay_fut: Box::new(future::empty()),
  277. context: None,
  278. };
  279. task.set_volume(volume);
  280. let spirc = Spirc { commands: cmd_tx };
  281. task.hello();
  282. (spirc, task)
  283. }
  284. pub fn play(&self) {
  285. let _ = self.commands.unbounded_send(SpircCommand::Play);
  286. }
  287. pub fn play_pause(&self) {
  288. let _ = self.commands.unbounded_send(SpircCommand::PlayPause);
  289. }
  290. pub fn pause(&self) {
  291. let _ = self.commands.unbounded_send(SpircCommand::Pause);
  292. }
  293. pub fn prev(&self) {
  294. let _ = self.commands.unbounded_send(SpircCommand::Prev);
  295. }
  296. pub fn next(&self) {
  297. let _ = self.commands.unbounded_send(SpircCommand::Next);
  298. }
  299. pub fn volume_up(&self) {
  300. let _ = self.commands.unbounded_send(SpircCommand::VolumeUp);
  301. }
  302. pub fn volume_down(&self) {
  303. let _ = self.commands.unbounded_send(SpircCommand::VolumeDown);
  304. }
  305. pub fn shutdown(&self) {
  306. let _ = self.commands.unbounded_send(SpircCommand::Shutdown);
  307. }
  308. }
  309. impl Future for SpircTask {
  310. type Item = ();
  311. type Error = ();
  312. fn poll(&mut self) -> Poll<(), ()> {
  313. loop {
  314. let mut progress = false;
  315. if self.session.is_invalid() {
  316. return Ok(Async::Ready(()));
  317. }
  318. if !self.shutdown {
  319. match self.subscription.poll().unwrap() {
  320. Async::Ready(Some(frame)) => {
  321. progress = true;
  322. self.handle_frame(frame);
  323. }
  324. Async::Ready(None) => {
  325. error!("subscription terminated");
  326. self.shutdown = true;
  327. self.commands.close();
  328. }
  329. Async::NotReady => (),
  330. }
  331. match self.commands.poll().unwrap() {
  332. Async::Ready(Some(command)) => {
  333. progress = true;
  334. self.handle_command(command);
  335. }
  336. Async::Ready(None) => (),
  337. Async::NotReady => (),
  338. }
  339. match self.player_events.poll() {
  340. Ok(Async::NotReady) => (),
  341. Ok(Async::Ready(None)) => (),
  342. Err(_) => (),
  343. Ok(Async::Ready(Some(event))) => {
  344. progress = true;
  345. self.handle_player_event(event);
  346. }
  347. }
  348. // TODO: Refactor
  349. match self.context_fut.poll() {
  350. Ok(Async::Ready(value)) => {
  351. let r_context = serde_json::from_value::<StationContext>(value.clone());
  352. self.context = match r_context {
  353. Ok(context) => {
  354. info!(
  355. "Resolved {:?} tracks from <{:?}>",
  356. context.tracks.len(),
  357. self.state.get_context_uri(),
  358. );
  359. Some(context)
  360. }
  361. Err(e) => {
  362. error!("Unable to parse JSONContext {:?}\n{:?}", e, value);
  363. None
  364. }
  365. };
  366. // It needn't be so verbose - can be as simple as
  367. // if let Some(ref context) = r_context {
  368. // info!("Got {:?} tracks from <{}>", context.tracks.len(), context.uri);
  369. // }
  370. // self.context = r_context;
  371. progress = true;
  372. self.context_fut = Box::new(future::empty());
  373. }
  374. Ok(Async::NotReady) => (),
  375. Err(err) => {
  376. self.context_fut = Box::new(future::empty());
  377. error!("ContextError: {:?}", err)
  378. }
  379. }
  380. match self.autoplay_fut.poll() {
  381. Ok(Async::Ready(autoplay_station_uri)) => {
  382. info!("Autoplay uri resolved to <{:?}>", autoplay_station_uri);
  383. self.context_fut = self.resolve_station(&autoplay_station_uri);
  384. progress = true;
  385. self.autoplay_fut = Box::new(future::empty());
  386. }
  387. Ok(Async::NotReady) => (),
  388. Err(err) => {
  389. self.autoplay_fut = Box::new(future::empty());
  390. error!("AutoplayError: {:?}", err)
  391. }
  392. }
  393. }
  394. let poll_sender = self.sender.poll_complete().unwrap();
  395. // Only shutdown once we've flushed out all our messages
  396. if self.shutdown && poll_sender.is_ready() {
  397. return Ok(Async::Ready(()));
  398. }
  399. if !progress {
  400. return Ok(Async::NotReady);
  401. }
  402. }
  403. }
  404. }
  405. impl SpircTask {
  406. fn now_ms(&mut self) -> i64 {
  407. let dur = match SystemTime::now().duration_since(UNIX_EPOCH) {
  408. Ok(dur) => dur,
  409. Err(err) => err.duration(),
  410. };
  411. (dur.as_secs() as i64 + self.session.time_delta()) * 1000
  412. + (dur.subsec_nanos() / 1000_000) as i64
  413. }
  414. fn ensure_mixer_started(&mut self) {
  415. if !self.mixer_started {
  416. self.mixer.start();
  417. self.mixer_started = true;
  418. }
  419. }
  420. fn ensure_mixer_stopped(&mut self) {
  421. if self.mixer_started {
  422. self.mixer.stop();
  423. self.mixer_started = false;
  424. }
  425. }
  426. fn update_state_position(&mut self, position_ms: u32) {
  427. let now = self.now_ms();
  428. self.state.set_position_measured_at(now as u64);
  429. self.state.set_position_ms(position_ms);
  430. }
  431. fn handle_command(&mut self, cmd: SpircCommand) {
  432. let active = self.device.get_is_active();
  433. match cmd {
  434. SpircCommand::Play => {
  435. if active {
  436. self.handle_play();
  437. self.notify(None, true);
  438. } else {
  439. CommandSender::new(self, MessageType::kMessageTypePlay).send();
  440. }
  441. }
  442. SpircCommand::PlayPause => {
  443. if active {
  444. self.handle_play_pause();
  445. self.notify(None, true);
  446. } else {
  447. CommandSender::new(self, MessageType::kMessageTypePlayPause).send();
  448. }
  449. }
  450. SpircCommand::Pause => {
  451. if active {
  452. self.handle_pause();
  453. self.notify(None, true);
  454. } else {
  455. CommandSender::new(self, MessageType::kMessageTypePause).send();
  456. }
  457. }
  458. SpircCommand::Prev => {
  459. if active {
  460. self.handle_prev();
  461. self.notify(None, true);
  462. } else {
  463. CommandSender::new(self, MessageType::kMessageTypePrev).send();
  464. }
  465. }
  466. SpircCommand::Next => {
  467. if active {
  468. self.handle_next();
  469. self.notify(None, true);
  470. } else {
  471. CommandSender::new(self, MessageType::kMessageTypeNext).send();
  472. }
  473. }
  474. SpircCommand::VolumeUp => {
  475. if active {
  476. self.handle_volume_up();
  477. self.notify(None, true);
  478. } else {
  479. CommandSender::new(self, MessageType::kMessageTypeVolumeUp).send();
  480. }
  481. }
  482. SpircCommand::VolumeDown => {
  483. if active {
  484. self.handle_volume_down();
  485. self.notify(None, true);
  486. } else {
  487. CommandSender::new(self, MessageType::kMessageTypeVolumeDown).send();
  488. }
  489. }
  490. SpircCommand::Shutdown => {
  491. CommandSender::new(self, MessageType::kMessageTypeGoodbye).send();
  492. self.shutdown = true;
  493. self.commands.close();
  494. }
  495. }
  496. }
  497. fn handle_player_event(&mut self, event: PlayerEvent) {
  498. // we only process events if the play_request_id matches. If it doesn't, it is
  499. // an event that belongs to a previous track and only arrives now due to a race
  500. // condition. In this case we have updated the state already and don't want to
  501. // mess with it.
  502. if let Some(play_request_id) = event.get_play_request_id() {
  503. if Some(play_request_id) == self.play_request_id {
  504. match event {
  505. PlayerEvent::EndOfTrack { .. } => self.handle_end_of_track(),
  506. PlayerEvent::Loading { .. } => self.notify(None, false),
  507. PlayerEvent::Playing { position_ms, .. } => {
  508. let new_nominal_start_time = self.now_ms() - position_ms as i64;
  509. match self.play_status {
  510. SpircPlayStatus::Playing {
  511. ref mut nominal_start_time,
  512. ..
  513. } => {
  514. if (*nominal_start_time - new_nominal_start_time).abs() > 100 {
  515. *nominal_start_time = new_nominal_start_time;
  516. self.update_state_position(position_ms);
  517. self.notify(None, true);
  518. }
  519. }
  520. SpircPlayStatus::LoadingPlay { .. }
  521. | SpircPlayStatus::LoadingPause { .. } => {
  522. self.state.set_status(PlayStatus::kPlayStatusPlay);
  523. self.update_state_position(position_ms);
  524. self.notify(None, true);
  525. self.play_status = SpircPlayStatus::Playing {
  526. nominal_start_time: new_nominal_start_time,
  527. preloading_of_next_track_triggered: false,
  528. };
  529. }
  530. _ => (),
  531. };
  532. trace!("==> kPlayStatusPlay");
  533. }
  534. PlayerEvent::Paused {
  535. position_ms: new_position_ms,
  536. ..
  537. } => {
  538. match self.play_status {
  539. SpircPlayStatus::Paused {
  540. ref mut position_ms,
  541. ..
  542. } => {
  543. if *position_ms != new_position_ms {
  544. *position_ms = new_position_ms;
  545. self.update_state_position(new_position_ms);
  546. self.notify(None, true);
  547. }
  548. }
  549. SpircPlayStatus::LoadingPlay { .. }
  550. | SpircPlayStatus::LoadingPause { .. } => {
  551. self.state.set_status(PlayStatus::kPlayStatusPause);
  552. self.update_state_position(new_position_ms);
  553. self.notify(None, true);
  554. self.play_status = SpircPlayStatus::Paused {
  555. position_ms: new_position_ms,
  556. preloading_of_next_track_triggered: false,
  557. };
  558. }
  559. _ => (),
  560. }
  561. trace!("==> kPlayStatusPause");
  562. }
  563. PlayerEvent::Stopped { .. } => match self.play_status {
  564. SpircPlayStatus::Stopped => (),
  565. _ => {
  566. warn!("The player has stopped unexpectedly.");
  567. self.state.set_status(PlayStatus::kPlayStatusStop);
  568. self.ensure_mixer_stopped();
  569. self.notify(None, true);
  570. self.play_status = SpircPlayStatus::Stopped;
  571. }
  572. },
  573. PlayerEvent::TimeToPreloadNextTrack { .. } => self.handle_preload_next_track(),
  574. PlayerEvent::Unavailable { track_id, .. } => self.handle_unavailable(track_id),
  575. _ => (),
  576. }
  577. }
  578. }
  579. }
  580. fn handle_frame(&mut self, frame: Frame) {
  581. let state_string = match frame.get_state().get_status() {
  582. PlayStatus::kPlayStatusLoading => "kPlayStatusLoading",
  583. PlayStatus::kPlayStatusPause => "kPlayStatusPause",
  584. PlayStatus::kPlayStatusStop => "kPlayStatusStop",
  585. PlayStatus::kPlayStatusPlay => "kPlayStatusPlay",
  586. };
  587. debug!(
  588. "{:?} {:?} {} {} {} {}",
  589. frame.get_typ(),
  590. frame.get_device_state().get_name(),
  591. frame.get_ident(),
  592. frame.get_seq_nr(),
  593. frame.get_state_update_id(),
  594. state_string,
  595. );
  596. if frame.get_ident() == self.ident
  597. || (frame.get_recipient().len() > 0 && !frame.get_recipient().contains(&self.ident))
  598. {
  599. return;
  600. }
  601. match frame.get_typ() {
  602. MessageType::kMessageTypeHello => {
  603. self.notify(Some(frame.get_ident()), true);
  604. }
  605. MessageType::kMessageTypeLoad => {
  606. if !self.device.get_is_active() {
  607. let now = self.now_ms();
  608. self.device.set_is_active(true);
  609. self.device.set_became_active_at(now);
  610. }
  611. self.update_tracks(&frame);
  612. if self.state.get_track().len() > 0 {
  613. let start_playing =
  614. frame.get_state().get_status() == PlayStatus::kPlayStatusPlay;
  615. self.load_track(start_playing, frame.get_state().get_position_ms());
  616. } else {
  617. info!("No more tracks left in queue");
  618. self.state.set_status(PlayStatus::kPlayStatusStop);
  619. self.player.stop();
  620. self.mixer.stop();
  621. self.play_status = SpircPlayStatus::Stopped;
  622. }
  623. self.notify(None, true);
  624. }
  625. MessageType::kMessageTypePlay => {
  626. self.handle_play();
  627. self.notify(None, true);
  628. }
  629. MessageType::kMessageTypePlayPause => {
  630. self.handle_play_pause();
  631. self.notify(None, true);
  632. }
  633. MessageType::kMessageTypePause => {
  634. self.handle_pause();
  635. self.notify(None, true);
  636. }
  637. MessageType::kMessageTypeNext => {
  638. self.handle_next();
  639. self.notify(None, true);
  640. }
  641. MessageType::kMessageTypePrev => {
  642. self.handle_prev();
  643. self.notify(None, true);
  644. }
  645. MessageType::kMessageTypeVolumeUp => {
  646. self.handle_volume_up();
  647. self.notify(None, true);
  648. }
  649. MessageType::kMessageTypeVolumeDown => {
  650. self.handle_volume_down();
  651. self.notify(None, true);
  652. }
  653. MessageType::kMessageTypeRepeat => {
  654. self.state.set_repeat(frame.get_state().get_repeat());
  655. self.notify(None, true);
  656. }
  657. MessageType::kMessageTypeShuffle => {
  658. self.state.set_shuffle(frame.get_state().get_shuffle());
  659. if self.state.get_shuffle() {
  660. let current_index = self.state.get_playing_track_index();
  661. {
  662. let tracks = self.state.mut_track();
  663. tracks.swap(0, current_index as usize);
  664. if let Some((_, rest)) = tracks.split_first_mut() {
  665. let mut rng = rand::thread_rng();
  666. rest.shuffle(&mut rng);
  667. }
  668. }
  669. self.state.set_playing_track_index(0);
  670. } else {
  671. let context = self.state.get_context_uri();
  672. debug!("{:?}", context);
  673. }
  674. self.notify(None, true);
  675. }
  676. MessageType::kMessageTypeSeek => {
  677. self.handle_seek(frame.get_position());
  678. self.notify(None, true);
  679. }
  680. MessageType::kMessageTypeReplace => {
  681. self.update_tracks(&frame);
  682. self.notify(None, true);
  683. if let SpircPlayStatus::Playing {
  684. preloading_of_next_track_triggered,
  685. ..
  686. }
  687. | SpircPlayStatus::Paused {
  688. preloading_of_next_track_triggered,
  689. ..
  690. } = self.play_status
  691. {
  692. if preloading_of_next_track_triggered {
  693. // Get the next track_id in the playlist
  694. if let Some(track_id) = self.preview_next_track() {
  695. self.player.preload(track_id);
  696. }
  697. }
  698. }
  699. }
  700. MessageType::kMessageTypeVolume => {
  701. self.set_volume(frame.get_volume() as u16);
  702. self.notify(None, true);
  703. }
  704. MessageType::kMessageTypeNotify => {
  705. if self.device.get_is_active()
  706. && frame.get_device_state().get_is_active()
  707. && self.device.get_became_active_at()
  708. <= frame.get_device_state().get_became_active_at()
  709. {
  710. self.device.set_is_active(false);
  711. self.state.set_status(PlayStatus::kPlayStatusStop);
  712. self.player.stop();
  713. self.ensure_mixer_stopped();
  714. self.play_status = SpircPlayStatus::Stopped;
  715. }
  716. }
  717. _ => (),
  718. }
  719. }
  720. fn handle_play(&mut self) {
  721. match self.play_status {
  722. SpircPlayStatus::Paused {
  723. position_ms,
  724. preloading_of_next_track_triggered,
  725. } => {
  726. self.ensure_mixer_started();
  727. self.player.play();
  728. self.state.set_status(PlayStatus::kPlayStatusPlay);
  729. self.update_state_position(position_ms);
  730. self.play_status = SpircPlayStatus::Playing {
  731. nominal_start_time: self.now_ms() as i64 - position_ms as i64,
  732. preloading_of_next_track_triggered,
  733. };
  734. }
  735. SpircPlayStatus::LoadingPause { position_ms } => {
  736. self.ensure_mixer_started();
  737. self.player.play();
  738. self.play_status = SpircPlayStatus::LoadingPlay { position_ms };
  739. }
  740. _ => (),
  741. }
  742. }
  743. fn handle_play_pause(&mut self) {
  744. match self.play_status {
  745. SpircPlayStatus::Paused { .. } | SpircPlayStatus::LoadingPause { .. } => {
  746. self.handle_play()
  747. }
  748. SpircPlayStatus::Playing { .. } | SpircPlayStatus::LoadingPlay { .. } => {
  749. self.handle_play()
  750. }
  751. _ => (),
  752. }
  753. }
  754. fn handle_pause(&mut self) {
  755. match self.play_status {
  756. SpircPlayStatus::Playing {
  757. nominal_start_time,
  758. preloading_of_next_track_triggered,
  759. } => {
  760. self.player.pause();
  761. self.state.set_status(PlayStatus::kPlayStatusPause);
  762. let position_ms = (self.now_ms() - nominal_start_time) as u32;
  763. self.update_state_position(position_ms);
  764. self.play_status = SpircPlayStatus::Paused {
  765. position_ms,
  766. preloading_of_next_track_triggered,
  767. };
  768. }
  769. SpircPlayStatus::LoadingPlay { position_ms } => {
  770. self.player.pause();
  771. self.play_status = SpircPlayStatus::LoadingPause { position_ms };
  772. }
  773. _ => (),
  774. }
  775. }
  776. fn handle_seek(&mut self, position_ms: u32) {
  777. self.update_state_position(position_ms);
  778. self.player.seek(position_ms);
  779. let now = self.now_ms();
  780. match self.play_status {
  781. SpircPlayStatus::Stopped => (),
  782. SpircPlayStatus::LoadingPause {
  783. position_ms: ref mut position,
  784. }
  785. | SpircPlayStatus::LoadingPlay {
  786. position_ms: ref mut position,
  787. }
  788. | SpircPlayStatus::Paused {
  789. position_ms: ref mut position,
  790. ..
  791. } => *position = position_ms,
  792. SpircPlayStatus::Playing {
  793. ref mut nominal_start_time,
  794. ..
  795. } => *nominal_start_time = now - position_ms as i64,
  796. };
  797. }
  798. fn consume_queued_track(&mut self) -> usize {
  799. // Removes current track if it is queued
  800. // Returns the index of the next track
  801. let current_index = self.state.get_playing_track_index() as usize;
  802. if (current_index < self.state.get_track().len())
  803. && self.state.get_track()[current_index].get_queued()
  804. {
  805. self.state.mut_track().remove(current_index);
  806. current_index
  807. } else {
  808. current_index + 1
  809. }
  810. }
  811. fn preview_next_track(&mut self) -> Option<SpotifyId> {
  812. self.get_track_id_to_play_from_playlist(self.state.get_playing_track_index() + 1)
  813. .and_then(|(track_id, _)| Some(track_id))
  814. }
  815. fn handle_preload_next_track(&mut self) {
  816. // Requests the player thread to preload the next track
  817. match self.play_status {
  818. SpircPlayStatus::Paused {
  819. ref mut preloading_of_next_track_triggered,
  820. ..
  821. }
  822. | SpircPlayStatus::Playing {
  823. ref mut preloading_of_next_track_triggered,
  824. ..
  825. } => {
  826. *preloading_of_next_track_triggered = true;
  827. if let Some(track_id) = self.preview_next_track() {
  828. self.player.preload(track_id);
  829. }
  830. }
  831. SpircPlayStatus::LoadingPause { .. }
  832. | SpircPlayStatus::LoadingPlay { .. }
  833. | SpircPlayStatus::Stopped => (),
  834. }
  835. }
  836. // Mark unavailable tracks so we can skip them later
  837. fn handle_unavailable(&mut self, track_id: SpotifyId) {
  838. let unavailables = self.get_track_index_for_spotify_id(&track_id, 0);
  839. for &index in unavailables.iter() {
  840. debug_assert_eq!(self.state.get_track()[index].get_gid(), track_id.to_raw());
  841. let mut unplayable_track_ref = TrackRef::new();
  842. unplayable_track_ref.set_gid(self.state.get_track()[index].get_gid().to_vec());
  843. // Misuse context field to flag the track
  844. unplayable_track_ref.set_context(String::from("NonPlayable"));
  845. std::mem::swap(
  846. &mut self.state.mut_track()[index],
  847. &mut unplayable_track_ref,
  848. );
  849. debug!(
  850. "Marked <{:?}> at {:?} as NonPlayable",
  851. self.state.get_track()[index],
  852. index,
  853. );
  854. }
  855. self.handle_preload_next_track();
  856. }
  857. fn handle_next(&mut self) {
  858. let mut new_index = self.consume_queued_track() as u32;
  859. let mut continue_playing = true;
  860. let tracks_len = self.state.get_track().len() as u32;
  861. debug!(
  862. "At track {:?} of {:?} <{:?}> update [{}]",
  863. new_index,
  864. self.state.get_track().len(),
  865. self.state.get_context_uri(),
  866. tracks_len - new_index < CONTEXT_FETCH_THRESHOLD
  867. );
  868. let context_uri = self.state.get_context_uri().to_owned();
  869. if (context_uri.starts_with("spotify:station:")
  870. || context_uri.starts_with("spotify:dailymix:")
  871. // spotify:user:xxx:collection
  872. || context_uri.starts_with(&format!("spotify:user:{}:collection",url_encode(&self.session.username()))))
  873. && ((self.state.get_track().len() as u32) - new_index) < CONTEXT_FETCH_THRESHOLD
  874. {
  875. self.context_fut = self.resolve_station(&context_uri);
  876. self.update_tracks_from_context();
  877. }
  878. if self.config.autoplay && new_index == tracks_len - 1 {
  879. // Extend the playlist
  880. // Note: This doesn't seem to reflect in the UI
  881. // the additional tracks in the frame don't show up as with station view
  882. debug!("Extending playlist <{}>", context_uri);
  883. self.update_tracks_from_context();
  884. }
  885. if new_index >= tracks_len {
  886. new_index = 0; // Loop around back to start
  887. continue_playing = self.state.get_repeat();
  888. }
  889. if tracks_len > 0 {
  890. self.state.set_playing_track_index(new_index);
  891. self.load_track(continue_playing, 0);
  892. } else {
  893. info!("Not playing next track because there are no more tracks left in queue.");
  894. self.state.set_playing_track_index(0);
  895. self.state.set_status(PlayStatus::kPlayStatusStop);
  896. self.player.stop();
  897. self.ensure_mixer_stopped();
  898. self.play_status = SpircPlayStatus::Stopped;
  899. }
  900. }
  901. fn handle_prev(&mut self) {
  902. // Previous behaves differently based on the position
  903. // Under 3s it goes to the previous song (starts playing)
  904. // Over 3s it seeks to zero (retains previous play status)
  905. if self.position() < 3000 {
  906. // Queued tracks always follow the currently playing track.
  907. // They should not be considered when calculating the previous
  908. // track so extract them beforehand and reinsert them after it.
  909. let mut queue_tracks = Vec::new();
  910. {
  911. let queue_index = self.consume_queued_track();
  912. let tracks = self.state.mut_track();
  913. while queue_index < tracks.len() && tracks[queue_index].get_queued() {
  914. queue_tracks.push(tracks.remove(queue_index));
  915. }
  916. }
  917. let current_index = self.state.get_playing_track_index();
  918. let new_index = if current_index > 0 {
  919. current_index - 1
  920. } else if self.state.get_repeat() {
  921. self.state.get_track().len() as u32 - 1
  922. } else {
  923. 0
  924. };
  925. // Reinsert queued tracks after the new playing track.
  926. let mut pos = (new_index + 1) as usize;
  927. for track in queue_tracks.into_iter() {
  928. self.state.mut_track().insert(pos, track);
  929. pos += 1;
  930. }
  931. self.state.set_playing_track_index(new_index);
  932. self.load_track(true, 0);
  933. } else {
  934. self.handle_seek(0);
  935. }
  936. }
  937. fn handle_volume_up(&mut self) {
  938. let mut volume: u32 = self.device.get_volume() as u32 + 4096;
  939. if volume > 0xFFFF {
  940. volume = 0xFFFF;
  941. }
  942. self.set_volume(volume as u16);
  943. }
  944. fn handle_volume_down(&mut self) {
  945. let mut volume: i32 = self.device.get_volume() as i32 - 4096;
  946. if volume < 0 {
  947. volume = 0;
  948. }
  949. self.set_volume(volume as u16);
  950. }
  951. fn handle_end_of_track(&mut self) {
  952. self.handle_next();
  953. self.notify(None, true);
  954. }
  955. fn position(&mut self) -> u32 {
  956. match self.play_status {
  957. SpircPlayStatus::Stopped => 0,
  958. SpircPlayStatus::LoadingPlay { position_ms }
  959. | SpircPlayStatus::LoadingPause { position_ms }
  960. | SpircPlayStatus::Paused { position_ms, .. } => position_ms,
  961. SpircPlayStatus::Playing {
  962. nominal_start_time, ..
  963. } => (self.now_ms() - nominal_start_time) as u32,
  964. }
  965. }
  966. fn resolve_station(
  967. &self,
  968. uri: &str,
  969. ) -> Box<dyn Future<Item = serde_json::Value, Error = MercuryError>> {
  970. let radio_uri = format!("hm://radio-apollo/v3/stations/{}", uri);
  971. self.resolve_uri(&radio_uri)
  972. }
  973. fn resolve_autoplay_uri(
  974. &self,
  975. uri: &str,
  976. ) -> Box<dyn Future<Item = String, Error = MercuryError>> {
  977. let query_uri = format!("hm://autoplay-enabled/query?uri={}", uri);
  978. let request = self.session.mercury().get(query_uri);
  979. Box::new(request.and_then(move |response| {
  980. if response.status_code == 200 {
  981. let data = response
  982. .payload
  983. .first()
  984. .expect("Empty autoplay uri")
  985. .to_vec();
  986. let autoplay_uri = String::from_utf8(data).unwrap();
  987. Ok(autoplay_uri)
  988. } else {
  989. warn!("No autoplay_uri found");
  990. Err(MercuryError)
  991. }
  992. }))
  993. }
  994. fn resolve_uri(
  995. &self,
  996. uri: &str,
  997. ) -> Box<dyn Future<Item = serde_json::Value, Error = MercuryError>> {
  998. let request = self.session.mercury().get(uri);
  999. Box::new(request.and_then(move |response| {
  1000. let data = response
  1001. .payload
  1002. .first()
  1003. .expect("Empty payload on context uri");
  1004. let response: serde_json::Value = serde_json::from_slice(&data).unwrap();
  1005. Ok(response)
  1006. }))
  1007. }
  1008. fn update_tracks_from_context(&mut self) {
  1009. if let Some(ref context) = self.context {
  1010. self.context_fut = self.resolve_uri(&context.next_page_url);
  1011. let new_tracks = &context.tracks;
  1012. debug!("Adding {:?} tracks from context to frame", new_tracks.len());
  1013. let mut track_vec = self.state.take_track().into_vec();
  1014. if let Some(head) = track_vec.len().checked_sub(CONTEXT_TRACKS_HISTORY) {
  1015. track_vec.drain(0..head);
  1016. }
  1017. track_vec.extend_from_slice(&new_tracks);
  1018. self.state
  1019. .set_track(protobuf::RepeatedField::from_vec(track_vec));
  1020. // Update playing index
  1021. if let Some(new_index) = self
  1022. .state
  1023. .get_playing_track_index()
  1024. .checked_sub(CONTEXT_TRACKS_HISTORY as u32)
  1025. {
  1026. self.state.set_playing_track_index(new_index);
  1027. }
  1028. } else {
  1029. warn!("No context to update from!");
  1030. }
  1031. }
  1032. fn update_tracks(&mut self, frame: &protocol::spirc::Frame) {
  1033. debug!("State: {:?}", frame.get_state());
  1034. let index = frame.get_state().get_playing_track_index();
  1035. let context_uri = frame.get_state().get_context_uri().to_owned();
  1036. let tracks = frame.get_state().get_track();
  1037. debug!("Frame has {:?} tracks", tracks.len());
  1038. if context_uri.starts_with("spotify:station:")
  1039. || context_uri.starts_with("spotify:dailymix:")
  1040. {
  1041. self.context_fut = self.resolve_station(&context_uri);
  1042. } else if self.config.autoplay {
  1043. info!("Fetching autoplay context uri");
  1044. // Get autoplay_station_uri for regular playlists
  1045. self.autoplay_fut = self.resolve_autoplay_uri(&context_uri);
  1046. }
  1047. self.state.set_playing_track_index(index);
  1048. self.state.set_track(tracks.into_iter().cloned().collect());
  1049. self.state.set_context_uri(context_uri);
  1050. // has_shuffle/repeat seem to always be true in these replace msgs,
  1051. // but to replicate the behaviour of the Android client we have to
  1052. // ignore false values.
  1053. let state = frame.get_state();
  1054. if state.get_repeat() {
  1055. self.state.set_repeat(true);
  1056. }
  1057. if state.get_shuffle() {
  1058. self.state.set_shuffle(true);
  1059. }
  1060. }
  1061. // should this be a method of SpotifyId directly?
  1062. fn get_spotify_id_for_track(&self, track_ref: &TrackRef) -> Result<SpotifyId, SpotifyIdError> {
  1063. SpotifyId::from_raw(track_ref.get_gid()).or_else(|_| {
  1064. let uri = track_ref.get_uri();
  1065. debug!("Malformed or no gid, attempting to parse URI <{}>", uri);
  1066. SpotifyId::from_uri(uri)
  1067. })
  1068. }
  1069. // Helper to find corresponding index(s) for track_id
  1070. fn get_track_index_for_spotify_id(
  1071. &self,
  1072. track_id: &SpotifyId,
  1073. start_index: usize,
  1074. ) -> Vec<usize> {
  1075. let index: Vec<usize> = self.state.get_track()[start_index..]
  1076. .iter()
  1077. .enumerate()
  1078. .filter(|&(_, track_ref)| track_ref.get_gid() == track_id.to_raw())
  1079. .map(|(idx, _)| start_index + idx)
  1080. .collect();
  1081. // Sanity check
  1082. debug_assert!(!index.is_empty());
  1083. index
  1084. }
  1085. // Broken out here so we can refactor this later when we move to SpotifyObjectID or similar
  1086. fn track_ref_is_unavailable(&self, track_ref: &TrackRef) -> bool {
  1087. track_ref.get_context() == "NonPlayable"
  1088. }
  1089. fn get_track_id_to_play_from_playlist(&self, index: u32) -> Option<(SpotifyId, u32)> {
  1090. let tracks_len = self.state.get_track().len();
  1091. let mut new_playlist_index = index as usize;
  1092. if new_playlist_index >= tracks_len {
  1093. new_playlist_index = 0;
  1094. }
  1095. let start_index = new_playlist_index;
  1096. // Cycle through all tracks, break if we don't find any playable tracks
  1097. // tracks in each frame either have a gid or uri (that may or may not be a valid track)
  1098. // E.g - context based frames sometimes contain tracks with <spotify:meta:page:>
  1099. let mut track_ref = self.state.get_track()[new_playlist_index].clone();
  1100. let mut track_id = self.get_spotify_id_for_track(&track_ref);
  1101. while self.track_ref_is_unavailable(&track_ref)
  1102. || track_id.is_err()
  1103. || track_id.unwrap().audio_type == SpotifyAudioType::NonPlayable
  1104. {
  1105. warn!(
  1106. "Skipping track <{:?}> at position [{}] of {}",
  1107. track_ref, new_playlist_index, tracks_len
  1108. );
  1109. new_playlist_index += 1;
  1110. if new_playlist_index >= tracks_len {
  1111. new_playlist_index = 0;
  1112. }
  1113. if new_playlist_index == start_index {
  1114. warn!("No playable track found in state: {:?}", self.state);
  1115. return None;
  1116. }
  1117. track_ref = self.state.get_track()[new_playlist_index].clone();
  1118. track_id = self.get_spotify_id_for_track(&track_ref);
  1119. }
  1120. match track_id {
  1121. Ok(track_id) => Some((track_id, new_playlist_index as u32)),
  1122. Err(_) => None,
  1123. }
  1124. }
  1125. fn load_track(&mut self, start_playing: bool, position_ms: u32) {
  1126. let index = self.state.get_playing_track_index();
  1127. match self.get_track_id_to_play_from_playlist(index) {
  1128. Some((track, index)) => {
  1129. self.state.set_playing_track_index(index);
  1130. self.play_request_id = Some(self.player.load(track, start_playing, position_ms));
  1131. self.update_state_position(position_ms);
  1132. if start_playing {
  1133. self.state.set_status(PlayStatus::kPlayStatusPlay);
  1134. self.play_status = SpircPlayStatus::LoadingPlay { position_ms };
  1135. } else {
  1136. self.state.set_status(PlayStatus::kPlayStatusPause);
  1137. self.play_status = SpircPlayStatus::LoadingPause { position_ms };
  1138. }
  1139. }
  1140. None => {
  1141. self.state.set_status(PlayStatus::kPlayStatusStop);
  1142. self.player.stop();
  1143. self.ensure_mixer_stopped();
  1144. self.play_status = SpircPlayStatus::Stopped;
  1145. }
  1146. }
  1147. }
  1148. fn hello(&mut self) {
  1149. CommandSender::new(self, MessageType::kMessageTypeHello).send();
  1150. }
  1151. fn notify(&mut self, recipient: Option<&str>, suppress_loading_status: bool) {
  1152. if suppress_loading_status && (self.state.get_status() == PlayStatus::kPlayStatusLoading) {
  1153. return;
  1154. };
  1155. let status_string = match self.state.get_status() {
  1156. PlayStatus::kPlayStatusLoading => "kPlayStatusLoading",
  1157. PlayStatus::kPlayStatusPause => "kPlayStatusPause",
  1158. PlayStatus::kPlayStatusStop => "kPlayStatusStop",
  1159. PlayStatus::kPlayStatusPlay => "kPlayStatusPlay",
  1160. };
  1161. trace!("Sending status to server: [{}]", status_string);
  1162. let mut cs = CommandSender::new(self, MessageType::kMessageTypeNotify);
  1163. if let Some(s) = recipient {
  1164. cs = cs.recipient(&s);
  1165. }
  1166. cs.send();
  1167. }
  1168. fn set_volume(&mut self, volume: u16) {
  1169. self.device.set_volume(volume as u32);
  1170. self.mixer
  1171. .set_volume(volume_to_mixer(volume, &self.config.volume_ctrl));
  1172. if let Some(cache) = self.session.cache() {
  1173. cache.save_volume(Volume { volume })
  1174. }
  1175. self.player.emit_volume_set_event(volume);
  1176. }
  1177. }
  1178. impl Drop for SpircTask {
  1179. fn drop(&mut self) {
  1180. debug!("drop Spirc[{}]", self.session.session_id());
  1181. }
  1182. }
  1183. struct CommandSender<'a> {
  1184. spirc: &'a mut SpircTask,
  1185. frame: protocol::spirc::Frame,
  1186. }
  1187. impl<'a> CommandSender<'a> {
  1188. fn new(spirc: &'a mut SpircTask, cmd: MessageType) -> CommandSender {
  1189. let mut frame = protocol::spirc::Frame::new();
  1190. frame.set_version(1);
  1191. frame.set_protocol_version(::std::convert::Into::into("2.0.0"));
  1192. frame.set_ident(spirc.ident.clone());
  1193. frame.set_seq_nr(spirc.sequence.get());
  1194. frame.set_typ(cmd);
  1195. frame.set_device_state(spirc.device.clone());
  1196. frame.set_state_update_id(spirc.now_ms());
  1197. CommandSender {
  1198. spirc: spirc,
  1199. frame: frame,
  1200. }
  1201. }
  1202. fn recipient(mut self, recipient: &'a str) -> CommandSender {
  1203. self.frame.mut_recipient().push(recipient.to_owned());
  1204. self
  1205. }
  1206. #[allow(dead_code)]
  1207. fn state(mut self, state: protocol::spirc::State) -> CommandSender<'a> {
  1208. self.frame.set_state(state);
  1209. self
  1210. }
  1211. fn send(mut self) {
  1212. if !self.frame.has_state() && self.spirc.device.get_is_active() {
  1213. self.frame.set_state(self.spirc.state.clone());
  1214. }
  1215. let send = self.spirc.sender.start_send(self.frame).unwrap();
  1216. assert!(send.is_ready());
  1217. }
  1218. }