so://phie

verbal

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

blob: 090b40b8bd4ca94ce2bdebb75c994a0e3169e132 (16687 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 LEFT JOIN station_status

86 ON station.id = station_status.station_id

87 LEFT JOIN station_stats

88 ON station.id = station_stats.station_id

89 AND station_stats.account_id = {account_id}

90 {conditions}

91 AND station_status.is_hidden IS NOT true

92 OFFSET {offset}

93 LIMIT 10

94 "#,

95 account_id = account.id,

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

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

98 );

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

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

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

102 .await?;

103 Response::with(result)

104}

105

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

107 let account =

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

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

110 let sql = format!(

111 r#"

112 INSERT INTO

113 station_stats

114 (account_id, station_id, playtime)

115 VALUES

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

117 ON CONFLICT (account_id, station_id)

118 DO UPDATE

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

120 latest_at = now();

121 "#,

122 account_id = account.id,

123 station_id = station.id,

124 );

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

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

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

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

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

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

131 };

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

133 Ok(interval) => interval * 2,

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

135 };

136 let mut total = 0;

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

138 let mut buf = [0; 10000];

139 let mut title = None;

140 loop {

141 let len =

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

143 bytes.extend_from_slice(&buf);

144 if total + len > interval {

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

146 if let Some(cap) =

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

148 .captures_iter(&metadata)

149 .next()

150 {

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

152 }

153 break;

154 }

155 if total > interval * 2 {

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

157 break;

158 }

159 total += len;

160 }

161 Response::with(title)

162}

163

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

165 let account =

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

167 let sql = format!(

168 r#"

169 SELECT

170 station.*,

171 station_status.is_restricted,

172 station_status.is_broken,

173 station_status.is_no_track_info,

174 station_status.is_hidden,

175 station_status.is_icon,

176 station_stats.playtime,

177 true as is_favorite

178 FROM station

179 LEFT JOIN favorite

180 ON station.id = favorite.station_id

181 LEFT JOIN station_status

182 ON station.id = station_status.station_id

183 LEFT JOIN station_stats

184 ON station.id = station_stats.station_id

185 AND station_stats.account_id = {account_id}

186 WHERE favorite.account_id = {account_id}

187 AND station_status.is_hidden IS NOT true

188 "#,

189 account_id = account.id,

190 );

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

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

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

194 .await?;

195 Response::with(result)

196}

197

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

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

200 let account =

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

202 let sql = format!(

203 r#"

204 INSERT INTO

205 favorite

206 (account_id, station_id)

207 VALUES

208 ({account_id}, {station_id})

209 "#,

210 account_id = account.id,

211 station_id = station_id,

212 );

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

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

215 Response::with(())

216}

217

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

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

220 let account =

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

222 let sql = format!(

223 r#"

224 DELETE FROM

225 favorite

226 WHERE account_id = {account_id}

227 AND station_id = {station_id}

228 "#,

229 account_id = account.id,

230 station_id = station_id,

231 );

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

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

234 Response::with(())

235}

236

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

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

239 let account =

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

241 let sql = format!(

242 r#"

243 SELECT

244 station.*,

245 station_status.is_restricted,

246 station_status.is_broken,

247 station_status.is_no_track_info,

248 station_status.is_hidden,

249 station_status.is_icon,

250 station_stats.playtime,

251 CASE

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

253 THEN false

254 ELSE true

255 END

256 AS is_favorite,

257 (

258 SELECT

259 count(*)

260 FROM favorite

261 WHERE favorite.station_id = {station_id}

262 )

263 AS likes

264 FROM station

265 LEFT JOIN favorite

266 ON station.id = favorite.station_id

267 LEFT JOIN station_status

268 ON station.id = station_status.station_id

269 LEFT JOIN station_stats

270 ON station.id = station_stats.station_id

271 AND station_stats.account_id = {account_id}

272 WHERE station.id = {station_id}

273 AND station_status.is_hidden IS NOT true

274 "#,

275 account_id = account.id,

276 station_id = station_id,

277 );

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

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

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

281 .await?;

282 Response::with(result)

283}

284

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

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

287 let account =

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

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

290 let sql = format!(

291 r#"

292 SELECT

293 station_group.*

294 FROM station_group

295 WHERE station_group.id = {group_id}

296 "#,

297 group_id = group_id,

298 );

299 let group = unwrap_option_or_throw!(

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

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

302 .await?,

303 "no group with id found!"

304 );

305 let sql = format!(

306 r#"

307 SELECT

308 station.*,

309 station_status.is_restricted,

310 station_status.is_broken,

311 station_status.is_no_track_info,

312 station_status.is_hidden,

313 station_status.is_icon,

314 station_stats.playtime,

315 CASE

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

317 THEN false

318 ELSE true

319 END AS is_favorite

320 FROM station

321 LEFT JOIN favorite

322 ON station.id = favorite.station_id

323 LEFT JOIN station_status

324 ON station.id = station_status.station_id

325 LEFT JOIN station_stats

326 ON station.id = station_stats.station_id

327 AND station_stats.account_id = {account_id}

328 WHERE station.group_id = {group_id}

329 AND station_status.is_hidden IS NOT true

330 "#,

331 account_id = account.id,

332 group_id = group_id,

333 );

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

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

336 .await?;

337 #[derive(Serialize)]

338 struct Result {

339 group: model::StationGroup,

340 stations: Vec<model::Station>,

341 }

342 let result = Result { group, stations };

343 Response::with(result)

344}

345

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

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

348 let account =

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

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

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

352 let sql = format!(

353 r#"

354 SELECT

355 station.*,

356 station_status.is_icon,

357 CASE

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

359 THEN false

360 ELSE true

361 END AS is_favorite

362 FROM station

363 LEFT JOIN favorite

364 ON station.id = favorite.station_id

365 LEFT JOIN station_status

366 ON station.id = station_status.station_id

367 LEFT JOIN station_stats

368 ON station.id = station_stats.station_id

369 AND station_stats.account_id = {account_id}

370 WHERE station_status.is_hidden IS NOT true

371 {category}

372 LIMIT 5

373 "#,

374 account_id = account.id,

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

376 );

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

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

379 .await?;

380 Response::with(result)

381}

382

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

384 let sql = r#"

385 SELECT

386 country

387 FROM station

388 WHERE country != ''

389 GROUP BY country

390 ORDER BY COUNT(*) DESC;

391 "#

392 .to_string();

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

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

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

396 .await?;

397 Response::with(result)

398}

399

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

401 let sql = r#"

402 SELECT

403 UNNEST(languages) AS language

404 FROM station

405 GROUP BY UNNEST(languages)

406 ORDER BY COUNT(*) DESC;

407 "#

408 .to_string();

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

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

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

412 .await?;

413 Response::with(result)

414}

415

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

417 let sql = r#"

418 SELECT

419 UNNEST(tags) AS tag

420 FROM station

421 GROUP BY UNNEST(tags)

422 ORDER BY COUNT(*) DESC

423 LIMIT 100;

424 "#

425 .to_string();

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

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

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

429 .await?;

430 Response::with(result)

431}

432

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

434 let account =

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

436 let sql = format!(

437 r#"

438 SELECT

439 device.*

440 FROM device

441 WHERE device.account_id = {account_id}

442 "#,

443 account_id = account.id,

444 );

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

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

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

448 .await?;

449 Response::with(result)

450}

451

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

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

454 let account =

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

456 let sql = format!(

457 r#"

458 UPDATE

459 account

460 SET

461 name = '{name}',

462 language = '{language}'

463 WHERE account.id = {account_id}

464 RETURNING *

465 "#,

466 account_id = account.id,

467 name = updated_account.name.unwrap_or_default(),

468 language = updated_account.language,

469 );

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

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

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

473 .await?;

474 Response::with(result)

475}