so://phie

verbal

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

blob: 39a2ce2565d8aa8067c77b1ee14952a2bdbb05ea (2393 bytes)[doc][blame][raw]

1use serde::Deserialize;

2use std::fmt;

3

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

5use crate::rest;

6

7const 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];

12

13#[derive(Debug, Default, Deserialize)]

14pub struct Search {

15 pub name: String,

16 pub page: Option<i64>,

17}

18

19impl 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}

29

30pub struct RadioBrowserApi;

31

32impl RadioBrowserApi {

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

34 let uri = format!("/json/stations/search?{}", &search);

35 let mut response = match RadioBrowserApi::fetch(&uri).await {

36 Ok(response) => response,

37 Err(err) => return Err(err),

38 };

39 match response.body_json::<Vec<rest::Station>>().await {

40 Ok(data) => Ok(data),

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

42 }

43 }

44

45 pub async fn by_uuids(uuids: Vec<String>) -> Result<Vec<rest::Station>> {

46 let uri = format!("/json/stations/byuuid?uuids={}", &uuids.join(","));

47 let mut response = match RadioBrowserApi::fetch(&uri).await {

48 Ok(response) => response,

49 Err(err) => return Err(err),

50 };

51 match response.body_json::<Vec<rest::Station>>().await {

52 Ok(data) => Ok(data),

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

54 }

55 }

56

57 async fn fetch(uri: &str) -> Result<surf::Response> {

58 let mut successful_response = None;

59 for api_url in API_URLS {

60 let url = format!("{}{}", &api_url, &uri,);

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

62 Ok(response) => {

63 successful_response = Some(response);

64 break;

65 }

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

67 }

68 }

69 match successful_response {

70 Some(response) => Ok(response),

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

72 }

73 }

74}