so://phie

verbal

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

blob: fc06c9a346219d1b4c587f2799ac392baac8e247 (14890 bytes)[doc][blame][raw]

1use async_std::io::ReadExt;

2use regex::Regex;

3use serde::Serialize;

4use sqlx::Acquire;

5use sqlx::Postgres;

6use tide_sqlx::SQLxRequestExt;

7

8use crate::model;

9use crate::unwrap_option_or_throw;

10use crate::unwrap_result_or_throw;

11use crate::Response;

12use crate::ToSql;

13

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

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

16}

17

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

19 let account =

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

21 Response::with(account)

22}

23

24pub async fn add_account(mut req: tide::Request<()>) -> tide::Result {

25 if req.ext::<model::Account>().is_some() {

26 return Response::throw("already logged in with another account!");

27 }

28 let add_account = req.body_json::<model::AddAccount>().await?;

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

30 let sql = format!(

31 r#"

32 INSERT INTO

33 account

34 (name, language)

35 VALUES

36 ('{name}', '{language}')

37 RETURNING account.*

38 "#,

39 name = add_account.name,

40 language = add_account.language,

41 );

42 let account = sqlx::query_as::<_, model::Account>(&sql)

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

44 .await?;

45 let sql = format!(

46 r#"

47 INSERT INTO

48 device

49 (uid, account_id)

50 VALUES

51 (uuid_generate_v4(), {account_id})

52 RETURNING device.*

53 "#,

54 account_id = account.id,

55 );

56 let device = sqlx::query_as::<_, model::Device>(&sql)

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

58 .await?;

59 Response::with(device)

60}

61

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

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

64 let account =

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

66 let sql = format!(

67 r#"

68 SELECT

69 station.*,

70 station_status.is_restricted,

71 station_status.is_broken,

72 station_status.is_no_track_info,

73 station_status.is_hidden,

74 station_status.is_icon,

75 station_stats.playtime,

76 CASE

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

78 THEN false

79 ELSE true

80 END AS is_favorite

81 FROM station

82 LEFT JOIN favorite

83 ON station.id = favorite.station_id

84 LEFT JOIN station_status

85 ON station.id = station_status.station_id

86 LEFT JOIN station_stats

87 ON station.id = station_stats.station_id

88 AND station_stats.account_id = {account_id}

89 {conditions}

90 AND station_status.is_hidden IS NOT true

91 OFFSET {offset}

92 LIMIT 10

93 "#,

94 account_id = account.id,

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

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

97 );

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

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

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

101 .await?;

102 Response::with(result)

103}

104

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

106 let account =

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

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

109 let sql = format!(

110 r#"

111 INSERT INTO

112 station_stats

113 (account_id, station_id, playtime)

114 VALUES

115 ({account_id}, {station_id}, 1)

116 ON CONFLICT (account_id, station_id)

117 DO UPDATE

118 SET playtime = station_stats.playtime + EXCLUDED.playtime,

119 latest_at = now();

120 "#,

121 account_id = account.id,

122 station_id = station.id,

123 );

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

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

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

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

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

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

130 };

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

132 Ok(interval) => interval * 2,

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

134 };

135 let mut total = 0;

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

137 let mut buf = [0; 10000];

138 let mut title = None;

139 loop {

140 let len =

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

142 bytes.extend_from_slice(&buf);

143 if total + len > interval {

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

145 if let Some(cap) =

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

147 .captures_iter(&metadata)

148 .next()

149 {

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

151 }

152 break;

153 }

154 if total > interval * 2 {

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

156 break;

157 }

158 total += len;

159 }

160 Response::with(title)

161}

162

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

164 let account =

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

166 let sql = format!(

167 r#"

168 SELECT

169 station.*,

170 station_status.is_restricted,

171 station_status.is_broken,

172 station_status.is_no_track_info,

173 station_status.is_hidden,

174 station_status.is_icon,

175 station_stats.playtime,

176 true as is_favorite

177 FROM station

178 LEFT JOIN favorite

179 ON station.id = favorite.station_id

180 LEFT JOIN station_status

181 ON station.id = station_status.station_id

182 LEFT JOIN station_stats

183 ON station.id = station_stats.station_id

184 AND station_stats.account_id = {account_id}

185 WHERE favorite.account_id = {account_id}

186 AND station_status.is_hidden IS NOT true

187 "#,

188 account_id = account.id,

189 );

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

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

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

193 .await?;

194 Response::with(result)

195}

196

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

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

199 let account =

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

201 let sql = format!(

202 r#"

203 INSERT INTO

204 favorite

205 (account_id, station_id)

206 VALUES

207 ({account_id}, {station_id})

208 "#,

209 account_id = account.id,

210 station_id = station_id,

211 );

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

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

214 Response::with(())

215}

216

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

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

219 let account =

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

221 let sql = format!(

222 r#"

223 DELETE FROM

224 favorite

225 WHERE account_id = {account_id}

226 AND station_id = {station_id}

227 "#,

228 account_id = account.id,

229 station_id = station_id,

230 );

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

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

233 Response::with(())

234}

235

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

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

238 let account =

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

240 let sql = format!(

241 r#"

242 SELECT

243 station.*,

244 station_status.is_restricted,

245 station_status.is_broken,

246 station_status.is_no_track_info,

247 station_status.is_hidden,

248 station_status.is_icon,

249 station_stats.playtime,

250 CASE

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

252 THEN false

253 ELSE true

254 END AS is_favorite

255 FROM station

256 LEFT JOIN favorite

257 ON station.id = favorite.station_id

258 LEFT JOIN station_status

259 ON station.id = station_status.station_id

260 LEFT JOIN station_stats

261 ON station.id = station_stats.station_id

262 AND station_stats.account_id = {account_id}

263 WHERE station.id = {station_id}

264 AND station_status.is_hidden IS NOT true

265 "#,

266 account_id = account.id,

267 station_id = station_id,

268 );

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

270 let result = sqlx::query_as::<_, model::StationDetail>(&sql)

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

272 .await?;

273 Response::with(result)

274}

275

276pub async fn get_group(req: tide::Request<()>) -> tide::Result {

277 let group_id = unwrap_result_or_throw!(req.param("id"), "no group id found!");

278 let account =

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

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

281 let sql = format!(

282 r#"

283 SELECT

284 station_group.*

285 FROM station_group

286 WHERE station_group.id = {group_id}

287 "#,

288 group_id = group_id,

289 );

290 let group = unwrap_option_or_throw!(

291 sqlx::query_as::<_, model::StationGroup>(&sql)

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

293 .await?,

294 "no group with id found!"

295 );

296 let sql = format!(

297 r#"

298 SELECT

299 station.*,

300 station_status.is_restricted,

301 station_status.is_broken,

302 station_status.is_no_track_info,

303 station_status.is_hidden,

304 station_status.is_icon,

305 station_stats.playtime,

306 CASE

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

308 THEN false

309 ELSE true

310 END AS is_favorite

311 FROM station

312 LEFT JOIN favorite

313 ON station.id = favorite.station_id

314 LEFT JOIN station_status

315 ON station.id = station_status.station_id

316 LEFT JOIN station_stats

317 ON station.id = station_stats.station_id

318 AND station_stats.account_id = {account_id}

319 WHERE station.group_id = {group_id}

320 AND station_status.is_hidden IS NOT true

321 "#,

322 account_id = account.id,

323 group_id = group_id,

324 );

325 let stations = sqlx::query_as::<_, model::Station>(&sql)

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

327 .await?;

328 #[derive(Serialize)]

329 struct Result {

330 group: model::StationGroup,

331 stations: Vec<model::Station>,

332 }

333 let result = Result { group, stations };

334 Response::with(result)

335}

336

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

338 let sql = r#"

339 SELECT

340 country

341 FROM station

342 WHERE country != ''

343 GROUP BY country

344 ORDER BY COUNT(*) DESC;

345 "#

346 .to_string();

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

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

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

350 .await?;

351 Response::with(result)

352}

353

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

355 let sql = r#"

356 SELECT

357 UNNEST(languages) AS language

358 FROM station

359 GROUP BY UNNEST(languages)

360 ORDER BY COUNT(*) DESC;

361 "#

362 .to_string();

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

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

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

366 .await?;

367 Response::with(result)

368}

369

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

371 let sql = r#"

372 SELECT

373 UNNEST(tags) AS tag

374 FROM station

375 GROUP BY UNNEST(tags)

376 ORDER BY COUNT(*) DESC

377 LIMIT 100;

378 "#

379 .to_string();

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

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

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

383 .await?;

384 Response::with(result)

385}

386

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

388 let account =

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

390 let sql = format!(

391 r#"

392 SELECT

393 device.*

394 FROM device

395 WHERE device.account_id = {account_id}

396 "#,

397 account_id = account.id,

398 );

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

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

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

402 .await?;

403 Response::with(result)

404}

405

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

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

408 let account =

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

410 let sql = format!(

411 r#"

412 UPDATE

413 account

414 SET

415 name = '{name}',

416 language = '{language}'

417 WHERE account.id = {account_id}

418 RETURNING *

419 "#,

420 account_id = account.id,

421 name = updated_account.name.unwrap_or_default(),

422 language = updated_account.language,

423 );

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

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

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

427 .await?;

428 Response::with(result)

429}