so://phie

verbal

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

blob: 26121df2d75e5ebdee85c69d46cbd26fbdb0d2a8 (16982 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 account.*

39 "#,

40 name = add_account.name,

41 language = add_account.language,

42 );

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

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

45 .await?;

46 let sql = format!(

47 r#"

48 INSERT INTO

49 device

50 (uid, account_id)

51 VALUES

52 (uuid_generate_v4(), {account_id})

53 RETURNING device.*

54 "#,

55 account_id = account.id,

56 );

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

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

59 .await?;

60 Response::with(device)

61}

62

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

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

65 let account =

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

67 let sql = format!(

68 r#"

69 SELECT

70 station.*,

71 station_status.is_restricted,

72 station_status.is_broken,

73 station_status.is_no_track_info,

74 station_status.is_hidden,

75 station_status.is_icon,

76 station_stats.playtime,

77 CASE

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

79 THEN false

80 ELSE true

81 END AS is_favorite

82 FROM station

83 LEFT JOIN favorite

84 ON station.id = favorite.station_id

85 AND favorite.account_id = {account_id}

86 LEFT JOIN station_status

87 ON station.id = station_status.station_id

88 LEFT JOIN station_stats

89 ON station.id = station_stats.station_id

90 AND station_stats.account_id = {account_id}

91 {conditions}

92 AND station_status.is_hidden IS NOT true

93 OFFSET {offset}

94 LIMIT 10

95 "#,

96 account_id = account.id,

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

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

99 );

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

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

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

103 .await?;

104 Response::with(result)

105}

106

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

108 let account =

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

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

111 let sql = format!(

112 r#"

113 INSERT INTO

114 station_stats

115 (account_id, station_id, playtime)

116 VALUES

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

118 ON CONFLICT (account_id, station_id)

119 DO UPDATE

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

121 latest_at = now();

122 "#,

123 account_id = account.id,

124 station_id = station.id,

125 );

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

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

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

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

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

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

132 };

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

134 Ok(interval) => interval * 2,

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

136 };

137 let mut total = 0;

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

139 let mut buf = [0; 10000];

140 let mut title = None;

141 loop {

142 let len =

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

144 bytes.extend_from_slice(&buf);

145 if total + len > interval {

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

147 if let Some(cap) =

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

149 .captures_iter(&metadata)

150 .next()

151 {

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

153 }

154 break;

155 }

156 if total > interval * 2 {

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

158 break;

159 }

160 total += len;

161 }

162 Response::with(title)

163}

164

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

166 let account =

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

168 let sql = format!(

169 r#"

170 SELECT

171 station.*,

172 station_status.is_restricted,

173 station_status.is_broken,

174 station_status.is_no_track_info,

175 station_status.is_hidden,

176 station_status.is_icon,

177 station_stats.playtime,

178 true as is_favorite

179 FROM station

180 LEFT JOIN favorite

181 ON station.id = favorite.station_id

182 AND favorite.account_id = {account_id}

183 LEFT JOIN station_status

184 ON station.id = station_status.station_id

185 LEFT JOIN station_stats

186 ON station.id = station_stats.station_id

187 AND station_stats.account_id = {account_id}

188 WHERE favorite.account_id = {account_id}

189 AND station_status.is_hidden IS NOT true

190 "#,

191 account_id = account.id,

192 );

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

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

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

196 .await?;

197 Response::with(result)

198}

199

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

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

202 let account =

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

204 let sql = format!(

205 r#"

206 INSERT INTO

207 favorite

208 (account_id, station_id)

209 VALUES

210 ({account_id}, {station_id})

211 "#,

212 account_id = account.id,

213 station_id = station_id,

214 );

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

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

217 Response::with(())

218}

219

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

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

222 let account =

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

224 let sql = format!(

225 r#"

226 DELETE FROM

227 favorite

228 WHERE account_id = {account_id}

229 AND station_id = {station_id}

230 "#,

231 account_id = account.id,

232 station_id = station_id,

233 );

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

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

236 Response::with(())

237}

238

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

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

241 let account =

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

243 let sql = format!(

244 r#"

245 SELECT

246 station.*,

247 station_status.is_restricted,

248 station_status.is_broken,

249 station_status.is_no_track_info,

250 station_status.is_hidden,

251 station_status.is_icon,

252 station_stats.playtime,

253 CASE

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

255 THEN false

256 ELSE true

257 END

258 AS is_favorite,

259 (

260 SELECT

261 count(*)

262 FROM favorite

263 WHERE favorite.station_id = {station_id}

264 )

265 AS likes

266 FROM station

267 LEFT JOIN favorite

268 ON station.id = favorite.station_id

269 AND favorite.account_id = {account_id}

270 LEFT JOIN station_status

271 ON station.id = station_status.station_id

272 LEFT JOIN station_stats

273 ON station.id = station_stats.station_id

274 AND station_stats.account_id = {account_id}

275 WHERE station.id = {station_id}

276 AND station_status.is_hidden IS NOT true

277 "#,

278 account_id = account.id,

279 station_id = station_id,

280 );

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

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

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

284 .await?;

285 Response::with(result)

286}

287

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

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

290 let account =

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

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

293 let sql = format!(

294 r#"

295 SELECT

296 station_group.*

297 FROM station_group

298 WHERE station_group.id = {group_id}

299 "#,

300 group_id = group_id,

301 );

302 let group = unwrap_option_or_throw!(

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

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

305 .await?,

306 "no group with id found!"

307 );

308 let sql = format!(

309 r#"

310 SELECT

311 station.*,

312 station_status.is_restricted,

313 station_status.is_broken,

314 station_status.is_no_track_info,

315 station_status.is_hidden,

316 station_status.is_icon,

317 station_stats.playtime,

318 CASE

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

320 THEN false

321 ELSE true

322 END AS is_favorite

323 FROM station

324 LEFT JOIN favorite

325 ON station.id = favorite.station_id

326 AND favorite.account_id = {account_id}

327 LEFT JOIN station_status

328 ON station.id = station_status.station_id

329 LEFT JOIN station_stats

330 ON station.id = station_stats.station_id

331 AND station_stats.account_id = {account_id}

332 WHERE station.group_id = {group_id}

333 AND station_status.is_hidden IS NOT true

334 "#,

335 account_id = account.id,

336 group_id = group_id,

337 );

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

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

340 .await?;

341 #[derive(Serialize)]

342 struct Result {

343 group: model::StationGroup,

344 stations: Vec<model::Station>,

345 }

346 let result = Result { group, stations };

347 Response::with(result)

348}

349

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

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

352 let account =

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

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

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

356 let sql = format!(

357 r#"

358 SELECT

359 station.*,

360 station_status.is_icon,

361 CASE

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

363 THEN false

364 ELSE true

365 END AS is_favorite

366 FROM station

367 LEFT JOIN favorite

368 ON station.id = favorite.station_id

369 AND favorite.account_id = {account_id}

370 LEFT JOIN station_status

371 ON station.id = station_status.station_id

372 LEFT JOIN station_stats

373 ON station.id = station_stats.station_id

374 AND station_stats.account_id = {account_id}

375 WHERE station_status.is_hidden IS NOT true

376 {category}

377 LIMIT 5

378 "#,

379 account_id = account.id,

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

381 );

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

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

384 .await?;

385 Response::with(result)

386}

387

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

389 let sql = r#"

390 SELECT

391 country

392 FROM station

393 WHERE country != ''

394 GROUP BY country

395 ORDER BY COUNT(*) DESC;

396 "#

397 .to_string();

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

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

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

401 .await?;

402 Response::with(result)

403}

404

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

406 let sql = r#"

407 SELECT

408 UNNEST(languages) AS language

409 FROM station

410 GROUP BY UNNEST(languages)

411 ORDER BY COUNT(*) DESC;

412 "#

413 .to_string();

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

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

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

417 .await?;

418 Response::with(result)

419}

420

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

422 let sql = r#"

423 SELECT

424 UNNEST(tags) AS tag

425 FROM station

426 GROUP BY UNNEST(tags)

427 ORDER BY COUNT(*) DESC

428 LIMIT 100;

429 "#

430 .to_string();

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

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

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

434 .await?;

435 Response::with(result)

436}

437

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

439 let account =

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

441 let sql = format!(

442 r#"

443 SELECT

444 device.*

445 FROM device

446 WHERE device.account_id = {account_id}

447 "#,

448 account_id = account.id,

449 );

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

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

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

453 .await?;

454 Response::with(result)

455}

456

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

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

459 let account =

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

461 let sql = format!(

462 r#"

463 UPDATE

464 account

465 SET

466 name = '{name}',

467 language = '{language}'

468 WHERE account.id = {account_id}

469 RETURNING *

470 "#,

471 account_id = account.id,

472 name = updated_account.name.unwrap_or_default(),

473 language = updated_account.language,

474 );

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

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

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

478 .await?;

479 Response::with(result)

480}