A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
blob: 699756d03c707589fa17def3e0725afd424510b4 (16446 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
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 INTO49
device50
(uid, account_id)51
VALUES52
(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
}63
pub 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
SELECT70
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
CASE78
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}79
THEN false80
ELSE true81
END AS is_favorite82
FROM station83
LEFT JOIN favorite84
ON station.id = favorite.station_id85
LEFT JOIN station_status86
ON station.id = station_status.station_id87
LEFT JOIN station_stats88
ON station.id = station_stats.station_id89
AND station_stats.account_id = {account_id}90
{conditions}91
AND station_status.is_hidden IS NOT true92
OFFSET {offset}93
LIMIT 1094
"#,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
}106
pub 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 INTO113
station_stats114
(account_id, station_id, playtime)115
VALUES116
({account_id}, {station_id}, 1)117
ON CONFLICT (account_id, station_id)118
DO UPDATE119
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
}164
pub 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
SELECT170
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_favorite178
FROM station179
LEFT JOIN favorite180
ON station.id = favorite.station_id181
LEFT JOIN station_status182
ON station.id = station_status.station_id183
LEFT JOIN station_stats184
ON station.id = station_stats.station_id185
AND station_stats.account_id = {account_id}186
WHERE favorite.account_id = {account_id}187
AND station_status.is_hidden IS NOT true188
"#,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
}198
pub 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 INTO205
favorite206
(account_id, station_id)207
VALUES208
({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
}218
pub 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 FROM225
favorite226
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
}237
pub 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
SELECT244
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
CASE252
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}253
THEN false254
ELSE true255
END AS is_favorite256
FROM station257
LEFT JOIN favorite258
ON station.id = favorite.station_id259
LEFT JOIN station_status260
ON station.id = station_status.station_id261
LEFT JOIN station_stats262
ON station.id = station_stats.station_id263
AND station_stats.account_id = {account_id}264
WHERE station.id = {station_id}265
AND station_status.is_hidden IS NOT true266
"#,267
account_id = account.id,268
station_id = station_id,269
);270
let mut conn = req.sqlx_conn::<Postgres>().await;271
let result = sqlx::query_as::<_, model::StationDetail>(&sql)272
.fetch_optional(conn.acquire().await?)273
.await?;274
Response::with(result)275
}277
pub async fn get_group(req: tide::Request<()>) -> tide::Result {278
let group_id = unwrap_result_or_throw!(req.param("id"), "no group id was provided!");279
let account =280
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");281
let mut conn = req.sqlx_conn::<Postgres>().await;282
let sql = format!(283
r#"284
SELECT285
station_group.*286
FROM station_group287
WHERE station_group.id = {group_id}288
"#,289
group_id = group_id,290
);291
let group = unwrap_option_or_throw!(292
sqlx::query_as::<_, model::StationGroup>(&sql)293
.fetch_optional(conn.acquire().await?)294
.await?,295
"no group with id found!"296
);297
let sql = format!(298
r#"299
SELECT300
station.*,301
station_status.is_restricted,302
station_status.is_broken,303
station_status.is_no_track_info,304
station_status.is_hidden,305
station_status.is_icon,306
station_stats.playtime,307
CASE308
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}309
THEN false310
ELSE true311
END AS is_favorite312
FROM station313
LEFT JOIN favorite314
ON station.id = favorite.station_id315
LEFT JOIN station_status316
ON station.id = station_status.station_id317
LEFT JOIN station_stats318
ON station.id = station_stats.station_id319
AND station_stats.account_id = {account_id}320
WHERE station.group_id = {group_id}321
AND station_status.is_hidden IS NOT true322
"#,323
account_id = account.id,324
group_id = group_id,325
);326
let stations = sqlx::query_as::<_, model::Station>(&sql)327
.fetch_all(conn.acquire().await?)328
.await?;329
#[derive(Serialize)]330
struct Result {331
group: model::StationGroup,332
stations: Vec<model::Station>,333
}334
let result = Result { group, stations };335
Response::with(result)336
}338
pub async fn get_category(req: tide::Request<()>) -> tide::Result {339
let kind = unwrap_result_or_throw!(req.param("kind"), "no kind was provided!");340
let account =341
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");342
let category = unwrap_result_or_throw!(Category::from(kind), "invalid category provided!");343
let mut conn = req.sqlx_conn::<Postgres>().await;344
let sql = format!(345
r#"346
SELECT347
station.*,348
station_status.is_icon,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
LEFT JOIN station_status358
ON station.id = station_status.station_id359
LEFT JOIN station_stats360
ON station.id = station_stats.station_id361
AND station_stats.account_id = {account_id}362
WHERE station_status.is_hidden IS NOT true363
{category}364
LIMIT 5365
"#,366
account_id = account.id,367
category = unwrap_result_or_throw!(category.to_sql(), "cannot parse sql statement!"),368
);369
let result = sqlx::query_as::<_, model::Station>(&sql)370
.fetch_all(conn.acquire().await?)371
.await?;372
Response::with(result)373
}375
pub async fn get_countries(req: tide::Request<()>) -> tide::Result {376
let sql = r#"377
SELECT378
country379
FROM station380
WHERE country != ''381
GROUP BY country382
ORDER BY COUNT(*) DESC;383
"#384
.to_string();385
let mut conn = req.sqlx_conn::<Postgres>().await;386
let result = sqlx::query_as::<_, model::Value>(&sql)387
.fetch_all(conn.acquire().await?)388
.await?;389
Response::with(result)390
}392
pub async fn get_languages(req: tide::Request<()>) -> tide::Result {393
let sql = r#"394
SELECT395
UNNEST(languages) AS language396
FROM station397
GROUP BY UNNEST(languages)398
ORDER BY COUNT(*) DESC;399
"#400
.to_string();401
let mut conn = req.sqlx_conn::<Postgres>().await;402
let result = sqlx::query_as::<_, model::Value>(&sql)403
.fetch_all(conn.acquire().await?)404
.await?;405
Response::with(result)406
}408
pub async fn get_tags(req: tide::Request<()>) -> tide::Result {409
let sql = r#"410
SELECT411
UNNEST(tags) AS tag412
FROM station413
GROUP BY UNNEST(tags)414
ORDER BY COUNT(*) DESC415
LIMIT 100;416
"#417
.to_string();418
let mut conn = req.sqlx_conn::<Postgres>().await;419
let result = sqlx::query_as::<_, model::Value>(&sql)420
.fetch_all(conn.acquire().await?)421
.await?;422
Response::with(result)423
}425
pub async fn get_devices(req: tide::Request<()>) -> tide::Result {426
let account =427
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");428
let sql = format!(429
r#"430
SELECT431
device.*432
FROM device433
WHERE device.account_id = {account_id}434
"#,435
account_id = account.id,436
);437
let mut conn = req.sqlx_conn::<Postgres>().await;438
let result = sqlx::query_as::<_, model::Device>(&sql)439
.fetch_all(conn.acquire().await?)440
.await?;441
Response::with(result)442
}444
pub async fn update_account(mut req: tide::Request<()>) -> tide::Result {445
let updated_account = req.body_json::<model::Account>().await?;446
let account =447
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");448
let sql = format!(449
r#"450
UPDATE451
account452
SET453
name = '{name}',454
language = '{language}'455
WHERE account.id = {account_id}456
RETURNING *457
"#,458
account_id = account.id,459
name = updated_account.name.unwrap_or_default(),460
language = updated_account.language,461
);462
let mut conn = req.sqlx_conn::<Postgres>().await;463
let result = sqlx::query_as::<_, model::Account>(&sql)464
.fetch_one(conn.acquire().await?)465
.await?;466
Response::with(result)467
}