so://phie

verbal

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

blob: 3471fb5eb966a6816f537d556de1455577e22c87 (5114 bytes)[doc][blame][raw]

1use async_std::io::ReadExt;

2use regex::Regex;

3use sqlx::Acquire;

4use sqlx::Postgres;

5use tide_sqlx::SQLxRequestExt;

6

7use crate::model;

8use crate::unwrap_option_or_throw;

9use crate::unwrap_result_or_throw;

10use crate::Response;

11use crate::ToSql;

12

13pub async fn do_prefetch(_: tide::Request<()>) -> tide::Result {

14 Ok(tide::Response::new(200))

15}

16

17pub async fn get_account(req: tide::Request<()>) -> tide::Result {

18 let account =

19 unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");

20 Response::with(account)

21}

22

23pub async fn do_search(req: tide::Request<()>) -> tide::Result {

24 let query = req.query::<model::Query>()?;

25 let account =

26 unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");

27 let sql = format!(

28 r#"

29 SELECT

30 station.*,

31 CASE

32 WHEN favorite.id IS NULL OR favorite.account_id != {account_id}

33 THEN false

34 ELSE true

35 END AS is_favorite

36 FROM station

37 LEFT JOIN favorite

38 ON station.id = favorite.station_id

39 {conditions}

40 OFFSET {offset}

41 LIMIT 10

42 "#,

43 account_id = account.id,

44 offset = query.page.unwrap_or_default() * 10,

45 conditions = unwrap_result_or_throw!(query.to_sql(), "cannot parse sql statement!"),

46 );

47 let mut conn = req.sqlx_conn::<Postgres>().await;

48 let result = sqlx::query_as::<_, model::Station>(&sql)

49 .fetch_all(conn.acquire().await?)

50 .await?;

51 Response::with(result)

52}

53

54pub async fn get_song(req: tide::Request<()>) -> tide::Result {

55 let station = req.query::<model::Station>()?;

56 let mut response = surf::get(&station.url).header("icy-metadata", "1").await?;

57 let meta_int = match response.header("icy-metaint") {

58 Some(header) => header.as_str(),

59 None => return Response::throw("no icy metadata header found!"),

60 };

61 let interval = match meta_int.parse::<usize>() {

62 Ok(interval) => interval * 2,

63 Err(_) => return Response::throw("icy metadata interval is not a number!"),

64 };

65 let mut total = 0;

66 let mut bytes = Vec::new();

67 let mut buf = [0; 10000];

68 let mut title = None;

69 loop {

70 let len =

71 unwrap_result_or_throw!(response.read(&mut buf).await, "cannot read stream data!");

72 bytes.extend_from_slice(&buf);

73 if total + len > interval {

74 let metadata = String::from_utf8_lossy(&bytes);

75 if let Some(cap) =

76 unwrap_result_or_throw!(Regex::new("StreamTitle='([^;]*)';"), "cannot parse regex!")

77 .captures_iter(&metadata)

78 .next()

79 {

80 title = Some(cap[1].to_string());

81 }

82 break;

83 }

84 if total > interval * 2 {

85 warn!("too many iterations while acquiring song title!");

86 break;

87 }

88 total += len;

89 }

90 Response::with(title)

91}

92

93pub async fn get_favorites(req: tide::Request<()>) -> tide::Result {

94 let account =

95 unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");

96 let sql = format!(

97 r#"

98 SELECT

99 station.*,

100 true as is_favorite

101 FROM station

102 LEFT JOIN favorite

103 ON station.id = favorite.station_id

104 WHERE favorite.account_id = {account_id}

105 "#,

106 account_id = account.id,

107 );

108 let mut conn = req.sqlx_conn::<Postgres>().await;

109 let result = sqlx::query_as::<_, model::Station>(&sql)

110 .fetch_all(conn.acquire().await?)

111 .await?;

112 Response::with(result)

113}

114

115pub async fn add_favorite(mut req: tide::Request<()>) -> tide::Result {

116 let station_id = req.body_json::<i32>().await?;

117 let account =

118 unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");

119 let sql = format!(

120 r#"

121 INSERT INTO

122 favorite

123 (account_id, station_id)

124 VALUES

125 ({account_id}, {station_id})

126 "#,

127 account_id = account.id,

128 station_id = station_id,

129 );

130 let mut conn = req.sqlx_conn::<Postgres>().await;

131 sqlx::query(&sql).execute(conn.acquire().await?).await?;

132 Response::with(())

133}

134

135pub async fn delete_favorite(mut req: tide::Request<()>) -> tide::Result {

136 let station_id = req.body_json::<i32>().await?;

137 let account =

138 unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");

139 let sql = format!(

140 r#"

141 DELETE FROM

142 favorite

143 WHERE account_id = {account_id}

144 AND station_id = {station_id}

145 "#,

146 account_id = account.id,

147 station_id = station_id,

148 );

149 let mut conn = req.sqlx_conn::<Postgres>().await;

150 sqlx::query(&sql).execute(conn.acquire().await?).await?;

151 Response::with(())

152}