so://phie

verbal

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

blob: 87de61a00509aa993a60f89dd7d16e7c8f697c3b (8210 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::model::StationCountry;

9use crate::model::StationId;

10use crate::model::StationLanguage;

11use crate::unwrap_option_or_throw;

12use crate::unwrap_result_or_throw;

13use crate::Response;

14use crate::ToSql;

15

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

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

18}

19

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

21 let account =

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

23 Response::with(account)

24}

25

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

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

28 let account =

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

30 let sql = format!(

31 r#"

32 SELECT

33 station.*,

34 station_status.is_restricted,

35 station_status.is_broken,

36 station_status.is_no_track_info,

37 station_status.is_hidden,

38 CASE

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

40 THEN false

41 ELSE true

42 END AS is_favorite

43 FROM station

44 LEFT JOIN favorite

45 ON station.id = favorite.station_id

46 LEFT JOIN station_status

47 ON station.id = station_status.station_id

48 {conditions}

49 AND station_status.is_hidden IS NOT true

50 OFFSET {offset}

51 LIMIT 10

52 "#,

53 account_id = account.id,

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

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

56 );

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

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

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

60 .await?;

61 Response::with(result)

62}

63

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

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

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

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

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

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

70 };

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

72 Ok(interval) => interval * 2,

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

74 };

75 let mut total = 0;

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

77 let mut buf = [0; 10000];

78 let mut title = None;

79 loop {

80 let len =

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

82 bytes.extend_from_slice(&buf);

83 if total + len > interval {

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

85 if let Some(cap) =

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

87 .captures_iter(&metadata)

88 .next()

89 {

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

91 }

92 break;

93 }

94 if total > interval * 2 {

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

96 break;

97 }

98 total += len;

99 }

100 Response::with(title)

101}

102

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

104 let account =

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

106 let sql = format!(

107 r#"

108 SELECT

109 station.*,

110 station_status.is_restricted,

111 station_status.is_broken,

112 station_status.is_no_track_info,

113 station_status.is_hidden,

114 true as is_favorite

115 FROM station

116 LEFT JOIN favorite

117 ON station.id = favorite.station_id

118 LEFT JOIN station_status

119 ON station.id = station_status.station_id

120 WHERE favorite.account_id = {account_id}

121 AND station_status.is_hidden IS NOT true

122 "#,

123 account_id = account.id,

124 );

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

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

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

128 .await?;

129 Response::with(result)

130}

131

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

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

134 let account =

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

136 let sql = format!(

137 r#"

138 INSERT INTO

139 favorite

140 (account_id, station_id)

141 VALUES

142 ({account_id}, {station_id})

143 "#,

144 account_id = account.id,

145 station_id = station_id,

146 );

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

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

149 Response::with(())

150}

151

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

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

154 let account =

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

156 let sql = format!(

157 r#"

158 DELETE FROM

159 favorite

160 WHERE account_id = {account_id}

161 AND station_id = {station_id}

162 "#,

163 account_id = account.id,

164 station_id = station_id,

165 );

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

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

168 Response::with(())

169}

170

171pub async fn get_station(req: tide::Request<()>) -> tide::Result {

172 let station_id = req.query::<StationId>()?;

173 let account =

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

175 let sql = format!(

176 r#"

177 SELECT

178 station.*,

179 station_status.is_restricted,

180 station_status.is_broken,

181 station_status.is_no_track_info,

182 station_status.is_hidden,

183 CASE

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

185 THEN false

186 ELSE true

187 END AS is_favorite

188 FROM station

189 LEFT JOIN favorite

190 ON station.id = favorite.station_id

191 LEFT JOIN station_status

192 ON station.id = station_status.station_id

193 WHERE station.id = {station_id}

194 AND station_status.is_hidden IS NOT true

195 "#,

196 account_id = account.id,

197 station_id = station_id.id,

198 );

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

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

201 .fetch_optional(conn.acquire().await?)

202 .await?;

203 Response::with(result)

204}

205

206pub async fn get_countries(req: tide::Request<()>) -> tide::Result {

207 let sql = format!(

208 r#"

209 SELECT

210 country

211 FROM station

212 WHERE country != ''

213 GROUP BY country

214 ORDER BY COUNT(*) DESC;

215 "#,

216 );

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

218 let result = sqlx::query_as::<_, StationCountry>(&sql)

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

220 .await?;

221 Response::with(result)

222}

223

224pub async fn get_languages(req: tide::Request<()>) -> tide::Result {

225 let sql = format!(

226 r#"

227 SELECT

228 UNNEST(languages) AS language

229 FROM station

230 GROUP BY UNNEST(languages)

231 ORDER BY COUNT(*) DESC;

232 "#,

233 );

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

235 let result = sqlx::query_as::<_, StationLanguage>(&sql)

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

237 .await?;

238 Response::with(result)

239}