A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
blob: 0154be8e36efa52f60b39a9f3731363d0ff72834 (2194 bytes)[doc][blame][raw]
1
use serde::Deserialize;2
use std::fmt;4
use crate::error::{Error, ErrorKind, Result};5
use crate::rest;7
const API_URLS: [&str; 3] = [8
"https://de1.api.radio-browser.info",9
"https://fr1.api.radio-browser.info",10
"https://nl1.api.radio-browser.info",11
];13
#[derive(Debug, Default, Deserialize)]14
pub struct Search {15
pub name: String,16
pub page: Option<i64>,17
}19
impl fmt::Display for Search {20
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {21
write!(22
f,23
"name={}&offset={}&limit=10&order=votes&reverse=true&hidebroken=true",24
&self.name,25
&self.page.unwrap_or(0) * 10,26
)27
}28
}30
pub struct RadioBrowserApi;32
impl RadioBrowserApi {33
pub async fn search(search: Search) -> Result<Vec<rest::Station>> {34
let uri = format!("/json/stations/search?{}", &search);35
let mut response = RadioBrowserApi::fetch(&uri).await?;36
match response.body_json::<Vec<rest::Station>>().await {37
Ok(data) => Ok(data),38
Err(err) => Err(Error::new(ErrorKind::Parse, &err.to_string())),39
}40
}42
pub async fn by_uuids(uuids: Vec<String>) -> Result<Vec<rest::Station>> {43
let uri = format!("/json/stations/byuuid?uuids={}", &uuids.join(","));44
let mut response = RadioBrowserApi::fetch(&uri).await?;45
match response.body_json::<Vec<rest::Station>>().await {46
Ok(data) => Ok(data),47
Err(err) => Err(Error::new(ErrorKind::Parse, &err.to_string())),48
}49
}51
async fn fetch(uri: &str) -> Result<surf::Response> {52
let mut successful_response = None;53
for api_url in API_URLS {54
let url = format!("{}{}", &api_url, &uri,);55
match surf::get(&url).await {56
Ok(response) => {57
successful_response = Some(response);58
break;59
}60
Err(err) => println!("{}", Error::new(ErrorKind::Fetch, &err.to_string())),61
}62
}63
match successful_response {64
Some(response) => Ok(response),65
None => Err(Error::new(ErrorKind::Fetch, "All request attempts failed!")),66
}67
}68
}