A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
blob: 97861657f596b88e5ee698f8692249a5ee7aa69c (16983 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
AND favorite.account_id = {account_id}86
LEFT JOIN station_status87
ON station.id = station_status.station_id88
LEFT JOIN station_stats89
ON station.id = station_stats.station_id90
AND station_stats.account_id = {account_id}91
{conditions}92
AND station_status.is_hidden IS NOT true93
OFFSET {offset}94
LIMIT 1095
"#,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
}107
pub 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 INTO114
station_stats115
(account_id, station_id, playtime)116
VALUES117
({account_id}, {station_id}, 1)118
ON CONFLICT (account_id, station_id)119
DO UPDATE120
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
}165
pub 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
SELECT171
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_favorite179
FROM station180
LEFT JOIN favorite181
ON station.id = favorite.station_id182
AND favorite.account_id = {account_id}183
LEFT JOIN station_status184
ON station.id = station_status.station_id185
LEFT JOIN station_stats186
ON station.id = station_stats.station_id187
AND station_stats.account_id = {account_id}188
WHERE favorite.account_id = {account_id}189
AND station_status.is_hidden IS NOT true190
"#,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
}200
pub 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 INTO207
favorite208
(account_id, station_id)209
VALUES210
({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
}220
pub 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 FROM227
favorite228
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
}239
pub 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
SELECT246
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
CASE254
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}255
THEN false256
ELSE true257
END258
AS is_favorite,259
(260
SELECT261
count(*)262
FROM favorite263
WHERE favorite.station_id = {station_id}264
)265
AS likes266
FROM station267
LEFT JOIN favorite268
ON station.id = favorite.station_id269
AND favorite.account_id = {account_id}270
LEFT JOIN station_status271
ON station.id = station_status.station_id272
LEFT JOIN station_stats273
ON station.id = station_stats.station_id274
AND station_stats.account_id = {account_id}275
WHERE station.id = {station_id}276
AND station_status.is_hidden IS NOT true277
"#,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
}288
pub 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
SELECT296
station_group.*297
FROM station_group298
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
SELECT311
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
CASE319
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}320
THEN false321
ELSE true322
END AS is_favorite323
FROM station324
LEFT JOIN favorite325
ON station.id = favorite.station_id326
AND favorite.account_id = {account_id}327
LEFT JOIN station_status328
ON station.id = station_status.station_id329
LEFT JOIN station_stats330
ON station.id = station_stats.station_id331
AND station_stats.account_id = {account_id}332
WHERE station.group_id = {group_id}333
AND station_status.is_hidden IS NOT true334
"#,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
}350
pub 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
SELECT359
station.*,360
station_status.is_icon,361
CASE362
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}363
THEN false364
ELSE true365
END AS is_favorite366
FROM station367
LEFT JOIN favorite368
ON station.id = favorite.station_id369
AND favorite.account_id = {account_id}370
LEFT JOIN station_status371
ON station.id = station_status.station_id372
LEFT JOIN station_stats373
ON station.id = station_stats.station_id374
AND station_stats.account_id = {account_id}375
WHERE station_status.is_hidden IS NOT true376
{category}377
LIMIT 10378
"#,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
}388
pub async fn get_countries(req: tide::Request<()>) -> tide::Result {389
let sql = r#"390
SELECT391
country392
FROM station393
WHERE country != ''394
GROUP BY country395
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
}405
pub async fn get_languages(req: tide::Request<()>) -> tide::Result {406
let sql = r#"407
SELECT408
UNNEST(languages) AS language409
FROM station410
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
}421
pub async fn get_tags(req: tide::Request<()>) -> tide::Result {422
let sql = r#"423
SELECT424
UNNEST(tags) AS tag425
FROM station426
GROUP BY UNNEST(tags)427
ORDER BY COUNT(*) DESC428
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
}438
pub 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
SELECT444
device.*445
FROM device446
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
}457
pub 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
UPDATE464
account465
SET466
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
}