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]
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
END256
AS is_favorite,257
(258
SELECT259
count(*)260
FROM favorite261
WHERE favorite.station_id = {station_id}262
)263
AS likes264
FROM station265
LEFT JOIN favorite266
ON station.id = favorite.station_id267
LEFT JOIN station_status268
ON station.id = station_status.station_id269
LEFT JOIN station_stats270
ON station.id = station_stats.station_id271
AND station_stats.account_id = {account_id}272
WHERE station.id = {station_id}273
AND station_status.is_hidden IS NOT true274
"#,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
}285
pub 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
SELECT293
station_group.*294
FROM station_group295
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
SELECT308
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
CASE316
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}317
THEN false318
ELSE true319
END AS is_favorite320
FROM station321
LEFT JOIN favorite322
ON station.id = favorite.station_id323
LEFT JOIN station_status324
ON station.id = station_status.station_id325
LEFT JOIN station_stats326
ON station.id = station_stats.station_id327
AND station_stats.account_id = {account_id}328
WHERE station.group_id = {group_id}329
AND station_status.is_hidden IS NOT true330
"#,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
}346
pub 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
SELECT355
station.*,356
station_status.is_icon,357
CASE358
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}359
THEN false360
ELSE true361
END AS is_favorite362
FROM station363
LEFT JOIN favorite364
ON station.id = favorite.station_id365
LEFT JOIN station_status366
ON station.id = station_status.station_id367
LEFT JOIN station_stats368
ON station.id = station_stats.station_id369
AND station_stats.account_id = {account_id}370
WHERE station_status.is_hidden IS NOT true371
{category}372
LIMIT 5373
"#,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
}383
pub async fn get_countries(req: tide::Request<()>) -> tide::Result {384
let sql = r#"385
SELECT386
country387
FROM station388
WHERE country != ''389
GROUP BY country390
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
}400
pub async fn get_languages(req: tide::Request<()>) -> tide::Result {401
let sql = r#"402
SELECT403
UNNEST(languages) AS language404
FROM station405
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
}416
pub async fn get_tags(req: tide::Request<()>) -> tide::Result {417
let sql = r#"418
SELECT419
UNNEST(tags) AS tag420
FROM station421
GROUP BY UNNEST(tags)422
ORDER BY COUNT(*) DESC423
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
}433
pub 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
SELECT439
device.*440
FROM device441
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
}452
pub 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
UPDATE459
account460
SET461
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
}