librespot/core/src/apresolve.rs

62 lines
1.7 KiB
Rust
Raw Normal View History

const AP_FALLBACK: &'static str = "ap.spotify.com:443";
const APRESOLVE_ENDPOINT: &'static str = "http://apresolve.spotify.com:80";
use hyper::{Body, Client, Method, Request, Uri};
2021-01-21 20:49:39 +00:00
use std::error::Error;
use url::Url;
use crate::proxytunnel::ProxyTunnel;
2016-07-06 01:29:38 +00:00
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct APResolveData {
2018-02-11 11:37:08 +00:00
ap_list: Vec<String>,
}
2021-01-21 20:49:39 +00:00
async fn apresolve(proxy: &Option<Url>, ap_port: &Option<u16>) -> Result<String, Box<dyn Error>> {
let port = ap_port.unwrap_or(443);
let req = Request::builder()
2021-01-21 20:49:39 +00:00
.method(Method::GET)
.uri(
APRESOLVE_ENDPOINT
.parse::<Uri>()
.expect("invalid AP resolve URL"),
)
.body(Body::empty())?;
2021-01-25 19:55:49 +00:00
let response = if let Some(url) = proxy {
Client::builder()
.build(ProxyTunnel::new(url)?)
.request(req)
.await?
2021-01-21 20:49:39 +00:00
} else {
2021-01-25 19:55:49 +00:00
Client::new().request(req).await?
2021-01-21 20:49:39 +00:00
};
2021-01-21 20:49:39 +00:00
let body = hyper::body::to_bytes(response.into_body()).await?;
let data: APResolveData = serde_json::from_slice(body.as_ref())?;
2021-01-21 20:49:39 +00:00
let ap = if ap_port.is_some() || proxy.is_some() {
data.ap_list.into_iter().find_map(|ap| {
if ap.parse::<Uri>().ok()?.port()? == port {
Some(ap)
2018-03-23 15:52:24 +00:00
} else {
2021-01-21 20:49:39 +00:00
None
2018-03-23 15:52:24 +00:00
}
2021-01-21 20:49:39 +00:00
})
} else {
data.ap_list.into_iter().next()
}
.ok_or("empty AP List")?;
2021-01-25 19:55:49 +00:00
2021-01-21 20:49:39 +00:00
Ok(ap)
}
2016-12-31 13:30:01 +00:00
2021-01-21 20:49:39 +00:00
pub async fn apresolve_or_fallback(proxy: &Option<Url>, ap_port: &Option<u16>) -> String {
apresolve(proxy, ap_port).await.unwrap_or_else(|e| {
warn!("Failed to resolve Access Point: {}", e);
2018-03-23 15:52:24 +00:00
warn!("Using fallback \"{}\"", AP_FALLBACK);
2021-01-21 20:49:39 +00:00
AP_FALLBACK.into()
})
}