so://phie

verbal

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

blob: 5a2e34f9a9b9c4fc3112c1de078a04bc799c4324 (10207 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 station_status.is_restricted,

32 station_status.is_broken,

33 station_status.is_no_track_info,

34 station_status.is_hidden,

35 station_status.is_icon,

36 CASE

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

38 THEN false

39 ELSE true

40 END AS is_favorite

41 FROM station

42 LEFT JOIN favorite

43 ON station.id = favorite.station_id

44 LEFT JOIN station_status

45 ON station.id = station_status.station_id

46 {conditions}

47 AND station_status.is_hidden IS NOT true

48 OFFSET {offset}

49 LIMIT 10

50 "#,

51 account_id = account.id,

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

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

54 );

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

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

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

58 .await?;

59 Response::with(result)

60}

61

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

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

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

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

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

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

68 };

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

70 Ok(interval) => interval * 2,

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

72 };

73 let mut total = 0;

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

75 let mut buf = [0; 10000];

76 let mut title = None;

77 loop {

78 let len =

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

80 bytes.extend_from_slice(&buf);

81 if total + len > interval {

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

83 if let Some(cap) =

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

85 .captures_iter(&metadata)

86 .next()

87 {

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

89 }

90 break;

91 }

92 if total > interval * 2 {

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

94 break;

95 }

96 total += len;

97 }

98 Response::with(title)

99}

100

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

102 let account =

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

104 let sql = format!(

105 r#"

106 SELECT

107 station.*,

108 station_status.is_restricted,

109 station_status.is_broken,

110 station_status.is_no_track_info,

111 station_status.is_hidden,

112 station_status.is_icon,

113 true as is_favorite

114 FROM station

115 LEFT JOIN favorite

116 ON station.id = favorite.station_id

117 LEFT JOIN station_status

118 ON station.id = station_status.station_id

119 WHERE favorite.account_id = {account_id}

120 AND station_status.is_hidden IS NOT true

121 "#,

122 account_id = account.id,

123 );

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

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

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

127 .await?;

128 Response::with(result)

129}

130

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

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

133 let account =

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

135 let sql = format!(

136 r#"

137 INSERT INTO

138 favorite

139 (account_id, station_id)

140 VALUES

141 ({account_id}, {station_id})

142 "#,

143 account_id = account.id,

144 station_id = station_id,

145 );

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

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

148 Response::with(())

149}

150

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

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

153 let account =

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

155 let sql = format!(

156 r#"

157 DELETE FROM

158 favorite

159 WHERE account_id = {account_id}

160 AND station_id = {station_id}

161 "#,

162 account_id = account.id,

163 station_id = station_id,

164 );

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

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

167 Response::with(())

168}

169

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

171 let station_id = unwrap_result_or_throw!(req.param("id"), "no station id found!");

172 let account =

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

174 let sql = format!(

175 r#"

176 SELECT

177 station.*,

178 station_status.is_restricted,

179 station_status.is_broken,

180 station_status.is_no_track_info,

181 station_status.is_hidden,

182 station_status.is_icon,

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,

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 = r#"

208 SELECT

209 country

210 FROM station

211 WHERE country != ''

212 GROUP BY country

213 ORDER BY COUNT(*) DESC;

214 "#

215 .to_string();

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

217 let result = sqlx::query_as::<_, model::Value>(&sql)

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

219 .await?;

220 Response::with(result)

221}

222

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

224 let sql = r#"

225 SELECT

226 UNNEST(languages) AS language

227 FROM station

228 GROUP BY UNNEST(languages)

229 ORDER BY COUNT(*) DESC;

230 "#

231 .to_string();

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

233 let result = sqlx::query_as::<_, model::Value>(&sql)

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

235 .await?;

236 Response::with(result)

237}

238

239pub async fn get_tags(req: tide::Request<()>) -> tide::Result {

240 let sql = r#"

241 SELECT

242 UNNEST(tags) AS tag

243 FROM station

244 GROUP BY UNNEST(tags)

245 ORDER BY COUNT(*) DESC

246 LIMIT 100;

247 "#

248 .to_string();

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

250 let result = sqlx::query_as::<_, model::Value>(&sql)

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

252 .await?;

253 Response::with(result)

254}

255

256pub async fn get_devices(req: tide::Request<()>) -> tide::Result {

257 let account =

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

259 let sql = format!(

260 r#"

261 SELECT

262 device.*

263 FROM device

264 WHERE device.account_id = {account_id}

265 "#,

266 account_id = account.id,

267 );

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

269 let result = sqlx::query_as::<_, model::Device>(&sql)

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

271 .await?;

272 Response::with(result)

273}

274

275pub async fn update_account(mut req: tide::Request<()>) -> tide::Result {

276 let updated_account = req.body_json::<model::Account>().await?;

277 let account =

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

279 let sql = format!(

280 r#"

281 UPDATE

282 account

283 SET

284 name = '{name}',

285 language = '{language}'

286 WHERE account.id = {account_id}

287 RETURNING *

288 "#,

289 account_id = account.id,

290 name = updated_account.name.unwrap_or_default(),

291 language = updated_account.language,

292 );

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

294 let result = sqlx::query_as::<_, model::Account>(&sql)

295 .fetch_one(conn.acquire().await?)

296 .await?;

297 Response::with(result)

298}