A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
blob: 3ae1d95c17f61e2badb88aa2da238a14f972e2a6 (14265 bytes)[doc][blame][raw]
1
use async_std::io::ReadExt;2
use regex::Regex;3
use sqlx::Acquire;4
use sqlx::Postgres;5
use tide_sqlx::SQLxRequestExt;7
use crate::model;8
use crate::unwrap_option_or_throw;9
use crate::unwrap_result_or_throw;10
use crate::Response;11
use crate::ToSql;13
pub async fn do_prefetch(_: tide::Request<()>) -> tide::Result {14
Ok(tide::Response::new(200))15
}17
pub async fn get_account(req: tide::Request<()>) -> tide::Result {18
let account =19
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");20
Response::with(account)21
}23
pub async fn add_account(mut req: tide::Request<()>) -> tide::Result {24
if req.ext::<model::Account>().is_some() {25
return Response::throw("already logged in with another account!");26
}27
let add_account = req.body_json::<model::AddAccount>().await?;28
let mut conn = req.sqlx_conn::<Postgres>().await;29
let sql = format!(30
r#"31
INSERT INTO32
account33
(name, language)34
VALUES35
('{name}', '{language}')36
RETURNING account.*37
"#,38
name = add_account.name,39
language = add_account.language,40
);41
let account = sqlx::query_as::<_, model::Account>(&sql)42
.fetch_one(conn.acquire().await?)43
.await?;44
let sql = format!(45
r#"46
INSERT INTO47
device48
(uid, account_id)49
VALUES50
(uuid_generate_v4(), {account_id})51
RETURNING device.*52
"#,53
account_id = account.id,54
);55
let device = sqlx::query_as::<_, model::Device>(&sql)56
.fetch_one(conn.acquire().await?)57
.await?;58
Response::with(device)59
}61
pub async fn do_search(req: tide::Request<()>) -> tide::Result {62
let query = req.query::<model::Query>()?;63
let account =64
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");65
let sql = format!(66
r#"67
SELECT68
station.*,69
station_status.is_restricted,70
station_status.is_broken,71
station_status.is_no_track_info,72
station_status.is_hidden,73
station_status.is_icon,74
station_stats.playtime,75
CASE76
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}77
THEN false78
ELSE true79
END AS is_favorite80
FROM station81
LEFT JOIN favorite82
ON station.id = favorite.station_id83
LEFT JOIN station_status84
ON station.id = station_status.station_id85
LEFT JOIN station_stats86
ON station.id = station_stats.station_id87
AND station_stats.account_id = {account_id}88
{conditions}89
AND station_status.is_hidden IS NOT true90
OFFSET {offset}91
LIMIT 1092
"#,93
account_id = account.id,94
offset = query.page.unwrap_or_default() * 10,95
conditions = unwrap_result_or_throw!(query.to_sql(), "cannot parse sql statement!"),96
);97
let mut conn = req.sqlx_conn::<Postgres>().await;98
let result = sqlx::query_as::<_, model::Station>(&sql)99
.fetch_all(conn.acquire().await?)100
.await?;101
Response::with(result)102
}104
pub async fn get_song(req: tide::Request<()>) -> tide::Result {105
let account =106
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");107
let station = req.query::<model::Station>()?;108
let sql = format!(109
r#"110
INSERT INTO111
station_stats112
(account_id, station_id, playtime)113
VALUES114
({account_id}, {station_id}, 1)115
ON CONFLICT (account_id, station_id)116
DO UPDATE117
SET playtime = station_stats.playtime + EXCLUDED.playtime,118
latest_at = now();119
"#,120
account_id = account.id,121
station_id = station.id,122
);123
let mut conn = req.sqlx_conn::<Postgres>().await;124
sqlx::query(&sql).execute(conn.acquire().await?).await?;125
let mut response = surf::get(&station.url).header("icy-metadata", "1").await?;126
let meta_int = match response.header("icy-metaint") {127
Some(header) => header.as_str(),128
None => return Response::throw("no icy metadata header found!"),129
};130
let interval = match meta_int.parse::<usize>() {131
Ok(interval) => interval * 2,132
Err(_) => return Response::throw("icy metadata interval is not a number!"),133
};134
let mut total = 0;135
let mut bytes = Vec::new();136
let mut buf = [0; 10000];137
let mut title = None;138
loop {139
let len =140
unwrap_result_or_throw!(response.read(&mut buf).await, "cannot read stream data!");141
bytes.extend_from_slice(&buf);142
if total + len > interval {143
let metadata = String::from_utf8_lossy(&bytes);144
if let Some(cap) =145
unwrap_result_or_throw!(Regex::new("StreamTitle='([^;]*)';"), "cannot parse regex!")146
.captures_iter(&metadata)147
.next()148
{149
title = Some(cap[1].to_string());150
}151
break;152
}153
if total > interval * 2 {154
warn!("too many iterations while acquiring song title!");155
break;156
}157
total += len;158
}159
Response::with(title)160
}162
pub async fn get_favorites(req: tide::Request<()>) -> tide::Result {163
let account =164
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");165
let sql = format!(166
r#"167
SELECT168
station.*,169
station_status.is_restricted,170
station_status.is_broken,171
station_status.is_no_track_info,172
station_status.is_hidden,173
station_status.is_icon,174
station_stats.playtime,175
true as is_favorite176
FROM station177
LEFT JOIN favorite178
ON station.id = favorite.station_id179
LEFT JOIN station_status180
ON station.id = station_status.station_id181
LEFT JOIN station_stats182
ON station.id = station_stats.station_id183
AND station_stats.account_id = {account_id}184
WHERE favorite.account_id = {account_id}185
AND station_status.is_hidden IS NOT true186
"#,187
account_id = account.id,188
);189
let mut conn = req.sqlx_conn::<Postgres>().await;190
let result = sqlx::query_as::<_, model::Station>(&sql)191
.fetch_all(conn.acquire().await?)192
.await?;193
Response::with(result)194
}196
pub async fn add_favorite(mut req: tide::Request<()>) -> tide::Result {197
let station_id = req.body_json::<i32>().await?;198
let account =199
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");200
let sql = format!(201
r#"202
INSERT INTO203
favorite204
(account_id, station_id)205
VALUES206
({account_id}, {station_id})207
"#,208
account_id = account.id,209
station_id = station_id,210
);211
let mut conn = req.sqlx_conn::<Postgres>().await;212
sqlx::query(&sql).execute(conn.acquire().await?).await?;213
Response::with(())214
}216
pub async fn delete_favorite(mut req: tide::Request<()>) -> tide::Result {217
let station_id = req.body_json::<i32>().await?;218
let account =219
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");220
let sql = format!(221
r#"222
DELETE FROM223
favorite224
WHERE account_id = {account_id}225
AND station_id = {station_id}226
"#,227
account_id = account.id,228
station_id = station_id,229
);230
let mut conn = req.sqlx_conn::<Postgres>().await;231
sqlx::query(&sql).execute(conn.acquire().await?).await?;232
Response::with(())233
}235
pub async fn get_station(req: tide::Request<()>) -> tide::Result {236
let station_id = unwrap_result_or_throw!(req.param("id"), "no station id found!");237
let account =238
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");239
let sql = format!(240
r#"241
SELECT242
station.*,243
station_status.is_restricted,244
station_status.is_broken,245
station_status.is_no_track_info,246
station_status.is_hidden,247
station_status.is_icon,248
station_stats.playtime,249
CASE250
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}251
THEN false252
ELSE true253
END AS is_favorite254
FROM station255
LEFT JOIN favorite256
ON station.id = favorite.station_id257
LEFT JOIN station_status258
ON station.id = station_status.station_id259
LEFT JOIN station_stats260
ON station.id = station_stats.station_id261
AND station_stats.account_id = {account_id}262
WHERE station.id = {station_id}263
AND station_status.is_hidden IS NOT true264
"#,265
account_id = account.id,266
station_id = station_id,267
);268
let mut conn = req.sqlx_conn::<Postgres>().await;269
let result = sqlx::query_as::<_, model::StationDetail>(&sql)270
.fetch_optional(conn.acquire().await?)271
.await?;272
Response::with(result)273
}275
pub async fn get_group(req: tide::Request<()>) -> tide::Result {276
let group_id = unwrap_result_or_throw!(req.param("id"), "no group id found!");277
let account =278
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");279
let sql = format!(280
r#"281
SELECT282
station.*,283
station_status.is_restricted,284
station_status.is_broken,285
station_status.is_no_track_info,286
station_status.is_hidden,287
station_status.is_icon,288
station_stats.playtime,289
CASE290
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}291
THEN false292
ELSE true293
END AS is_favorite294
FROM station295
LEFT JOIN favorite296
ON station.id = favorite.station_id297
LEFT JOIN station_status298
ON station.id = station_status.station_id299
LEFT JOIN station_stats300
ON station.id = station_stats.station_id301
AND station_stats.account_id = {account_id}302
WHERE station.group_id = {group_id}303
AND station_status.is_hidden IS NOT true304
"#,305
account_id = account.id,306
group_id = group_id,307
);308
let mut conn = req.sqlx_conn::<Postgres>().await;309
let result = sqlx::query_as::<_, model::Station>(&sql)310
.fetch_all(conn.acquire().await?)311
.await?;312
Response::with(result)313
}315
pub async fn get_countries(req: tide::Request<()>) -> tide::Result {316
let sql = r#"317
SELECT318
country319
FROM station320
WHERE country != ''321
GROUP BY country322
ORDER BY COUNT(*) DESC;323
"#324
.to_string();325
let mut conn = req.sqlx_conn::<Postgres>().await;326
let result = sqlx::query_as::<_, model::Value>(&sql)327
.fetch_all(conn.acquire().await?)328
.await?;329
Response::with(result)330
}332
pub async fn get_languages(req: tide::Request<()>) -> tide::Result {333
let sql = r#"334
SELECT335
UNNEST(languages) AS language336
FROM station337
GROUP BY UNNEST(languages)338
ORDER BY COUNT(*) DESC;339
"#340
.to_string();341
let mut conn = req.sqlx_conn::<Postgres>().await;342
let result = sqlx::query_as::<_, model::Value>(&sql)343
.fetch_all(conn.acquire().await?)344
.await?;345
Response::with(result)346
}348
pub async fn get_tags(req: tide::Request<()>) -> tide::Result {349
let sql = r#"350
SELECT351
UNNEST(tags) AS tag352
FROM station353
GROUP BY UNNEST(tags)354
ORDER BY COUNT(*) DESC355
LIMIT 100;356
"#357
.to_string();358
let mut conn = req.sqlx_conn::<Postgres>().await;359
let result = sqlx::query_as::<_, model::Value>(&sql)360
.fetch_all(conn.acquire().await?)361
.await?;362
Response::with(result)363
}365
pub async fn get_devices(req: tide::Request<()>) -> tide::Result {366
let account =367
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");368
let sql = format!(369
r#"370
SELECT371
device.*372
FROM device373
WHERE device.account_id = {account_id}374
"#,375
account_id = account.id,376
);377
let mut conn = req.sqlx_conn::<Postgres>().await;378
let result = sqlx::query_as::<_, model::Device>(&sql)379
.fetch_all(conn.acquire().await?)380
.await?;381
Response::with(result)382
}384
pub async fn update_account(mut req: tide::Request<()>) -> tide::Result {385
let updated_account = req.body_json::<model::Account>().await?;386
let account =387
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");388
let sql = format!(389
r#"390
UPDATE391
account392
SET393
name = '{name}',394
language = '{language}'395
WHERE account.id = {account_id}396
RETURNING *397
"#,398
account_id = account.id,399
name = updated_account.name.unwrap_or_default(),400
language = updated_account.language,401
);402
let mut conn = req.sqlx_conn::<Postgres>().await;403
let result = sqlx::query_as::<_, model::Account>(&sql)404
.fetch_one(conn.acquire().await?)405
.await?;406
Response::with(result)407
}