so://phie

verbal

A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal

blob: 4dd404eaaf62c80e5de48e01154863f698355f4f (1871 bytes)[doc][blame][raw]

1use serde::{Deserialize, Serialize};

2use std::fmt;

3

4use crate::adapter::StationAdapter;

5use crate::error::{Error, ErrorKind, Result};

6use crate::models::Station;

7

8const API_URLS: [&str; 3] = [

9 "https://de1.api.radio-browser.info",

10 "https://fr1.api.radio-browser.info",

11 "https://nl1.api.radio-browser.info",

12];

13

14#[derive(Debug, Default, Deserialize, Serialize)]

15pub struct Search {

16 pub name: String,

17 pub page: Option<i64>,

18}

19

20impl fmt::Display for Search {

21 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {

22 write!(

23 f,

24 "name={}&offset={}&limit=10&order=votes&reverse=true&hidebroken=true",

25 &self.name,

26 &self.page.unwrap_or(0) * 10,

27 )

28 }

29}

30

31pub struct RadioBrowserApi;

32

33impl RadioBrowserApi {

34 pub async fn search(search: Search) -> Result<Vec<Station>> {

35 let mut successful_response = None;

36 for api_url in API_URLS {

37 let url = format!("{}/json/stations/search?{}", &api_url, &search,);

38 match surf::get(&url).await {

39 Ok(response) => {

40 successful_response = Some(response);

41 break;

42 }

43 Err(err) => println!("{}", Error::new(ErrorKind::Fetch, &err.to_string())),

44 }

45 }

46 let mut response = match successful_response {

47 Some(response) => response,

48 None => return Err(Error::new(ErrorKind::Fetch, "All request attempts failed!")),

49 };

50 let adapters = match response.body_json::<Vec<StationAdapter>>().await {

51 Ok(adapters) => adapters,

52 Err(err) => return Err(Error::new(ErrorKind::Parse, &err.to_string())),

53 };

54 let mut stations = vec![];

55 for adapter in adapters {

56 stations.push(adapter.into());

57 }

58 Ok(stations)

59 }

60}