so://phie

verbal

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

blob: 3224677406dbe3f80f0e3f48b4b4bc0e9bfe01f4 (18165 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::Category;

12use crate::Response;

13use crate::ToSql;

14

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

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

17}

18

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

20 let account =

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

22 Response::with(account)

23}

24

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

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

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

28 }

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

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

31 let sql = format!(

32 r#"

33 INSERT INTO

34 account

35 (name, language)

36 VALUES

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

38 RETURNING

39 account.*,

40 (

41 SELECT

42 sum(playtime)

43 FROM get_playtime(account.id)

44 )

45 AS playtime

46 "#,

47 name = add_account.name,

48 language = add_account.language,

49 );

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

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

52 .await?;

53 let sql = format!(

54 r#"

55 INSERT INTO

56 device

57 (uid, account_id)

58 VALUES

59 (uuid_generate_v4(), {account_id})

60 RETURNING device.*

61 "#,

62 account_id = account.id,

63 );

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

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

66 .await?;

67 Response::with(device)

68}

69

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

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

72 let account =

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

74 let sql = format!(

75 r#"

76 SELECT

77 station.*,

78 station_status.is_restricted,

79 station_status.is_broken,

80 station_status.is_no_track_info,

81 station_status.is_hidden,

82 station_status.is_icon,

83 station_stats.playtime,

84 CASE

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

86 THEN false

87 ELSE true

88 END AS is_favorite

89 FROM station

90 LEFT JOIN favorite

91 ON station.id = favorite.station_id

92 AND favorite.account_id = {account_id}

93 LEFT JOIN station_status

94 ON station.id = station_status.station_id

95 LEFT JOIN station_stats

96 ON station.id = station_stats.station_id

97 AND station_stats.account_id = {account_id}

98 {conditions}

99 AND station_status.is_hidden IS NOT true

100 OFFSET {offset}

101 LIMIT 10

102 "#,

103 account_id = account.id,

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

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

106 );

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

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

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

110 .await?;

111 Response::with(result)

112}

113

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

115 let account =

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

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

118 let sql = format!(

119 r#"

120 INSERT INTO

121 station_stats

122 (account_id, station_id, playtime)

123 VALUES

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

125 ON CONFLICT (account_id, station_id)

126 DO UPDATE

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

128 latest_at = now();

129 "#,

130 account_id = account.id,

131 station_id = station.id,

132 );

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

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

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

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

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

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

139 };

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

141 Ok(interval) => interval * 2,

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

143 };

144 let mut total = 0;

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

146 let mut buf = [0; 10000];

147 let mut title = None;

148 loop {

149 let len =

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

151 bytes.extend_from_slice(&buf);

152 if total + len > interval {

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

154 if let Some(cap) =

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

156 .captures_iter(&metadata)

157 .next()

158 {

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

160 }

161 break;

162 }

163 if total > interval * 2 {

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

165 break;

166 }

167 total += len;

168 }

169 Response::with(title)

170}

171

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

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 station_status.is_icon,

184 station_stats.playtime,

185 true as is_favorite

186 FROM station

187 LEFT JOIN favorite

188 ON station.id = favorite.station_id

189 AND favorite.account_id = {account_id}

190 LEFT JOIN station_status

191 ON station.id = station_status.station_id

192 LEFT JOIN station_stats

193 ON station.id = station_stats.station_id

194 AND station_stats.account_id = {account_id}

195 WHERE favorite.account_id = {account_id}

196 AND station_status.is_hidden IS NOT true

197 "#,

198 account_id = account.id,

199 );

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

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

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

203 .await?;

204 Response::with(result)

205}

206

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

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

209 let account =

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

211 let sql = format!(

212 r#"

213 INSERT INTO

214 favorite

215 (account_id, station_id)

216 VALUES

217 ({account_id}, {station_id})

218 "#,

219 account_id = account.id,

220 station_id = station_id,

221 );

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

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

224 Response::ok()

225}

226

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

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

229 let account =

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

231 let sql = format!(

232 r#"

233 DELETE FROM

234 favorite

235 WHERE account_id = {account_id}

236 AND station_id = {station_id}

237 "#,

238 account_id = account.id,

239 station_id = station_id,

240 );

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

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

243 Response::ok()

244}

245

246pub async fn get_account_by_id(req: tide::Request<()>) -> tide::Result {

247 let account_id = unwrap_result_or_throw!(req.param("id"), "no account id found!");

248 let sql = format!(

249 r#"

250 SELECT

251 account.*,

252 (

253 SELECT

254 sum(playtime)

255 FROM get_playtime(account.id)

256 )

257 AS playtime

258 FROM account

259 WHERE account.id = {account_id}

260 "#,

261 account_id = account_id,

262 );

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

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

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

266 .await?;

267 Response::with(result)

268}

269

270pub async fn get_station_by_id(req: tide::Request<()>) -> tide::Result {

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

272 let account =

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

274 let sql = format!(

275 r#"

276 SELECT

277 station.*,

278 station_status.is_restricted,

279 station_status.is_broken,

280 station_status.is_no_track_info,

281 station_status.is_hidden,

282 station_status.is_icon,

283 station_stats.playtime,

284 CASE

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

286 THEN false

287 ELSE true

288 END

289 AS is_favorite,

290 (

291 SELECT

292 count(*)

293 FROM favorite

294 WHERE favorite.station_id = {station_id}

295 )

296 AS likes

297 FROM station

298 LEFT JOIN favorite

299 ON station.id = favorite.station_id

300 AND favorite.account_id = {account_id}

301 LEFT JOIN station_status

302 ON station.id = station_status.station_id

303 LEFT JOIN station_stats

304 ON station.id = station_stats.station_id

305 AND station_stats.account_id = {account_id}

306 WHERE station.id = {station_id}

307 AND station_status.is_hidden IS NOT true

308 "#,

309 account_id = account.id,

310 station_id = station_id,

311 );

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

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

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

315 .await?;

316 Response::with(result)

317}

318

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

320 let group_id = unwrap_result_or_throw!(req.param("id"), "no group id was provided!");

321 let account =

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

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

324 let sql = format!(

325 r#"

326 SELECT

327 station_group.*

328 FROM station_group

329 WHERE station_group.id = {group_id}

330 "#,

331 group_id = group_id,

332 );

333 let group = unwrap_option_or_throw!(

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

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

336 .await?,

337 "no group with id found!"

338 );

339 let sql = format!(

340 r#"

341 SELECT

342 station.*,

343 station_status.is_restricted,

344 station_status.is_broken,

345 station_status.is_no_track_info,

346 station_status.is_hidden,

347 station_status.is_icon,

348 station_stats.playtime,

349 CASE

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

351 THEN false

352 ELSE true

353 END AS is_favorite

354 FROM station

355 LEFT JOIN favorite

356 ON station.id = favorite.station_id

357 AND favorite.account_id = {account_id}

358 LEFT JOIN station_status

359 ON station.id = station_status.station_id

360 LEFT JOIN station_stats

361 ON station.id = station_stats.station_id

362 AND station_stats.account_id = {account_id}

363 WHERE station.group_id = {group_id}

364 AND station_status.is_hidden IS NOT true

365 "#,

366 account_id = account.id,

367 group_id = group_id,

368 );

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

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

371 .await?;

372 #[derive(Serialize)]

373 struct Result {

374 group: model::StationGroup,

375 stations: Vec<model::Station>,

376 }

377 let result = Result { group, stations };

378 Response::with(result)

379}

380

381pub async fn get_category(req: tide::Request<()>) -> tide::Result {

382 let kind = unwrap_result_or_throw!(req.param("kind"), "no kind was provided!");

383 let account =

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

385 let category = unwrap_result_or_throw!(Category::from(kind), "invalid category provided!");

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

387 let sql = format!(

388 r#"

389 SELECT

390 station.*,

391 station_status.is_icon,

392 CASE

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

394 THEN false

395 ELSE true

396 END AS is_favorite

397 FROM station

398 LEFT JOIN favorite

399 ON station.id = favorite.station_id

400 AND favorite.account_id = {account_id}

401 LEFT JOIN station_status

402 ON station.id = station_status.station_id

403 LEFT JOIN station_stats

404 ON station.id = station_stats.station_id

405 AND station_stats.account_id = {account_id}

406 WHERE station_status.is_hidden IS NOT true

407 {category}

408 LIMIT 10

409 "#,

410 account_id = account.id,

411 category = unwrap_result_or_throw!(category.to_sql(), "cannot parse sql statement!"),

412 );

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

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

415 .await?;

416 Response::with(result)

417}

418

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

420 let sql = r#"

421 SELECT

422 country

423 FROM station

424 WHERE country != ''

425 GROUP BY country

426 ORDER BY COUNT(*) DESC;

427 "#

428 .to_string();

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

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

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

432 .await?;

433 Response::with(result)

434}

435

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

437 let sql = r#"

438 SELECT

439 UNNEST(languages) AS language

440 FROM station

441 GROUP BY UNNEST(languages)

442 ORDER BY COUNT(*) DESC;

443 "#

444 .to_string();

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

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

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

448 .await?;

449 Response::with(result)

450}

451

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

453 let sql = r#"

454 SELECT

455 UNNEST(tags) AS tag

456 FROM station

457 GROUP BY UNNEST(tags)

458 ORDER BY COUNT(*) DESC

459 LIMIT 100;

460 "#

461 .to_string();

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

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

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

465 .await?;

466 Response::with(result)

467}

468

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

470 let account =

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

472 let sql = format!(

473 r#"

474 SELECT

475 device.*

476 FROM device

477 WHERE device.account_id = {account_id}

478 "#,

479 account_id = account.id,

480 );

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

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

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

484 .await?;

485 Response::with(result)

486}

487

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

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

490 let account =

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

492 let sql = format!(

493 r#"

494 UPDATE

495 account

496 SET

497 name = '{name}',

498 language = '{language}'

499 WHERE account.id = {account_id}

500 RETURNING

501 account.*,

502 (

503 SELECT

504 sum(playtime)

505 FROM get_playtime(account.id)

506 )

507 AS playtime

508 "#,

509 account_id = account.id,

510 name = updated_account.name.unwrap_or_default(),

511 language = updated_account.language,

512 );

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

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

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

516 .await?;

517 Response::with(result)

518}