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]
1
use async_std::io::ReadExt;2
use regex::Regex;3
use serde::Serialize;4
use sqlx::Acquire;5
use sqlx::Postgres;6
use tide_sqlx::SQLxRequestExt;8
use crate::model;9
use crate::unwrap_option_or_throw;10
use crate::unwrap_result_or_throw;11
use crate::Category;12
use crate::Response;13
use crate::ToSql;15
pub async fn do_prefetch(_: tide::Request<()>) -> tide::Result {16
Ok(tide::Response::new(200))17
}19
pub 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
}25
pub 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 INTO34
account35
(name, language)36
VALUES37
('{name}', '{language}')38
RETURNING39
account.*,40
(41
SELECT42
sum(playtime)43
FROM get_playtime(account.id)44
)45
AS playtime46
"#,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 INTO56
device57
(uid, account_id)58
VALUES59
(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
}70
pub 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
SELECT77
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
CASE85
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}86
THEN false87
ELSE true88
END AS is_favorite89
FROM station90
LEFT JOIN favorite91
ON station.id = favorite.station_id92
AND favorite.account_id = {account_id}93
LEFT JOIN station_status94
ON station.id = station_status.station_id95
LEFT JOIN station_stats96
ON station.id = station_stats.station_id97
AND station_stats.account_id = {account_id}98
{conditions}99
AND station_status.is_hidden IS NOT true100
OFFSET {offset}101
LIMIT 10102
"#,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
}114
pub 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 INTO121
station_stats122
(account_id, station_id, playtime)123
VALUES124
({account_id}, {station_id}, 1)125
ON CONFLICT (account_id, station_id)126
DO UPDATE127
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
}172
pub 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
SELECT178
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_favorite186
FROM station187
LEFT JOIN favorite188
ON station.id = favorite.station_id189
AND favorite.account_id = {account_id}190
LEFT JOIN station_status191
ON station.id = station_status.station_id192
LEFT JOIN station_stats193
ON station.id = station_stats.station_id194
AND station_stats.account_id = {account_id}195
WHERE favorite.account_id = {account_id}196
AND station_status.is_hidden IS NOT true197
"#,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
}207
pub 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 INTO214
favorite215
(account_id, station_id)216
VALUES217
({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
}227
pub 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 FROM234
favorite235
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
}246
pub 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
SELECT251
account.*,252
(253
SELECT254
sum(playtime)255
FROM get_playtime(account.id)256
)257
AS playtime258
FROM account259
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
}270
pub 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
SELECT277
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
CASE285
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}286
THEN false287
ELSE true288
END289
AS is_favorite,290
(291
SELECT292
count(*)293
FROM favorite294
WHERE favorite.station_id = {station_id}295
)296
AS likes297
FROM station298
LEFT JOIN favorite299
ON station.id = favorite.station_id300
AND favorite.account_id = {account_id}301
LEFT JOIN station_status302
ON station.id = station_status.station_id303
LEFT JOIN station_stats304
ON station.id = station_stats.station_id305
AND station_stats.account_id = {account_id}306
WHERE station.id = {station_id}307
AND station_status.is_hidden IS NOT true308
"#,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
}319
pub 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
SELECT327
station_group.*328
FROM station_group329
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
SELECT342
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
CASE350
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}351
THEN false352
ELSE true353
END AS is_favorite354
FROM station355
LEFT JOIN favorite356
ON station.id = favorite.station_id357
AND favorite.account_id = {account_id}358
LEFT JOIN station_status359
ON station.id = station_status.station_id360
LEFT JOIN station_stats361
ON station.id = station_stats.station_id362
AND station_stats.account_id = {account_id}363
WHERE station.group_id = {group_id}364
AND station_status.is_hidden IS NOT true365
"#,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
}381
pub 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
SELECT390
station.*,391
station_status.is_icon,392
CASE393
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}394
THEN false395
ELSE true396
END AS is_favorite397
FROM station398
LEFT JOIN favorite399
ON station.id = favorite.station_id400
AND favorite.account_id = {account_id}401
LEFT JOIN station_status402
ON station.id = station_status.station_id403
LEFT JOIN station_stats404
ON station.id = station_stats.station_id405
AND station_stats.account_id = {account_id}406
WHERE station_status.is_hidden IS NOT true407
{category}408
LIMIT 10409
"#,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
}419
pub async fn get_countries(req: tide::Request<()>) -> tide::Result {420
let sql = r#"421
SELECT422
country423
FROM station424
WHERE country != ''425
GROUP BY country426
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
}436
pub async fn get_languages(req: tide::Request<()>) -> tide::Result {437
let sql = r#"438
SELECT439
UNNEST(languages) AS language440
FROM station441
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
}452
pub async fn get_tags(req: tide::Request<()>) -> tide::Result {453
let sql = r#"454
SELECT455
UNNEST(tags) AS tag456
FROM station457
GROUP BY UNNEST(tags)458
ORDER BY COUNT(*) DESC459
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
}469
pub 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
SELECT475
device.*476
FROM device477
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
}488
pub 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
UPDATE495
account496
SET497
name = '{name}',498
language = '{language}'499
WHERE account.id = {account_id}500
RETURNING501
account.*,502
(503
SELECT504
sum(playtime)505
FROM get_playtime(account.id)506
)507
AS playtime508
"#,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
}