From c273d51a1df00d73935538c3952ef016216fc131 Mon Sep 17 00:00:00 2001 From: ashthespy Date: Sat, 23 Jan 2021 22:21:42 +0000 Subject: [PATCH] [AudioKeyManager] Convert to async --- core/Cargo.toml | 1 + core/src/audio_key.rs | 41 +++++++++++++++-------------------------- 2 files changed, 16 insertions(+), 26 deletions(-) diff --git a/core/Cargo.toml b/core/Cargo.toml index a76b45ab..077efe0a 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -14,6 +14,7 @@ version = "0.1.3" [dependencies] base64 = "0.13" +thiserror = "1.0" byteorder = "1.3" bytes = "0.5" error-chain = { version = "0.12", default_features = false } diff --git a/core/src/audio_key.rs b/core/src/audio_key.rs index 39eef721..976361d0 100644 --- a/core/src/audio_key.rs +++ b/core/src/audio_key.rs @@ -1,13 +1,9 @@ use byteorder::{BigEndian, ByteOrder, WriteBytesExt}; use bytes::Bytes; +use futures::channel::oneshot; use std::collections::HashMap; use std::io::Write; - -use futures::{channel::oneshot, Future}; -use std::{ - pin::Pin, - task::{Context, Poll}, -}; +use thiserror::Error; use crate::spotify_id::{FileId, SpotifyId}; use crate::util::SeqGenerator; @@ -15,8 +11,13 @@ use crate::util::SeqGenerator; #[derive(Debug, Hash, PartialEq, Eq, Copy, Clone)] pub struct AudioKey(pub [u8; 16]); -#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone)] -pub struct AudioKeyError; +#[derive(Error, Debug)] +pub enum AudioKeyError { + #[error("AudioKey sender disconnected")] + Cancelled(#[from] oneshot::Canceled), + #[error("Unknown server response: `{0:?}`")] + UnknownResponse(Vec), +} component! { AudioKeyManager : AudioKeyManagerInner { @@ -44,14 +45,16 @@ impl AudioKeyManager { data.as_ref()[0], data.as_ref()[1] ); - let _ = sender.send(Err(AudioKeyError)); + let _ = sender.send(Err(AudioKeyError::UnknownResponse( + data.as_ref()[..1].to_vec(), + ))); } - _ => (), + _ => warn!("Unexpected audioKey response: 0x{:x?} {:?}", cmd, data), } } } - pub fn request(&self, track: SpotifyId, file: FileId) -> AudioKeyFuture { + pub async fn request(&self, track: SpotifyId, file: FileId) -> Result { let (tx, rx) = oneshot::channel(); let seq = self.lock(move |inner| { @@ -61,7 +64,7 @@ impl AudioKeyManager { }); self.send_key_request(seq, track, file); - AudioKeyFuture(rx) + rx.await? } fn send_key_request(&self, seq: u32, track: SpotifyId, file: FileId) { @@ -74,17 +77,3 @@ impl AudioKeyManager { self.session().send_packet(0xc, data) } } - -pub struct AudioKeyFuture(oneshot::Receiver>); -impl Future for AudioKeyFuture { - type Output = Result; - - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { - match self.0.poll() { - Poll::Ready(Ok(Ok(value))) => Poll::Ready(Ok(value)), - Poll::Ready(Ok(Err(err))) => Err(err), - Poll::Pending => Poll::Pending, - Err(oneshot::Canceled) => Err(AudioKeyError), - } - } -}