A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
blob: fc06c9a346219d1b4c587f2799ac392baac8e247 (14890 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::Response;12
use crate::ToSql;14
pub async fn do_prefetch(_: tide::Request<()>) -> tide::Result {15
Ok(tide::Response::new(200))16
}18
pub async fn get_account(req: tide::Request<()>) -> tide::Result {19
let account =20
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");21
Response::with(account)22
}24
pub async fn add_account(mut req: tide::Request<()>) -> tide::Result {25
if req.ext::<model::Account>().is_some() {26
return Response::throw("already logged in with another account!");27
}28
let add_account = req.body_json::<model::AddAccount>().await?;29
let mut conn = req.sqlx_conn::<Postgres>().await;30
let sql = format!(31
r#"32
INSERT INTO33
account34
(name, language)35
VALUES36
('{name}', '{language}')37
RETURNING account.*38
"#,39
name = add_account.name,40
language = add_account.language,41
);42
let account = sqlx::query_as::<_, model::Account>(&sql)43
.fetch_one(conn.acquire().await?)44
.await?;45
let sql = format!(46
r#"47
INSERT INTO48
device49
(uid, account_id)50
VALUES51
(uuid_generate_v4(), {account_id})52
RETURNING device.*53
"#,54
account_id = account.id,55
);56
let device = sqlx::query_as::<_, model::Device>(&sql)57
.fetch_one(conn.acquire().await?)58
.await?;59
Response::with(device)60
}62
pub async fn do_search(req: tide::Request<()>) -> tide::Result {63
let query = req.query::<model::Query>()?;64
let account =65
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");66
let sql = format!(67
r#"68
SELECT69
station.*,70
station_status.is_restricted,71
station_status.is_broken,72
station_status.is_no_track_info,73
station_status.is_hidden,74
station_status.is_icon,75
station_stats.playtime,76
CASE77
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}78
THEN false79
ELSE true80
END AS is_favorite81
FROM station82
LEFT JOIN favorite83
ON station.id = favorite.station_id84
LEFT JOIN station_status85
ON station.id = station_status.station_id86
LEFT JOIN station_stats87
ON station.id = station_stats.station_id88
AND station_stats.account_id = {account_id}89
{conditions}90
AND station_status.is_hidden IS NOT true91
OFFSET {offset}92
LIMIT 1093
"#,94
account_id = account.id,95
offset = query.page.unwrap_or_default() * 10,96
conditions = unwrap_result_or_throw!(query.to_sql(), "cannot parse sql statement!"),97
);98
let mut conn = req.sqlx_conn::<Postgres>().await;99
let result = sqlx::query_as::<_, model::Station>(&sql)100
.fetch_all(conn.acquire().await?)101
.await?;102
Response::with(result)103
}105
pub async fn get_song(req: tide::Request<()>) -> tide::Result {106
let account =107
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");108
let station = req.query::<model::Station>()?;109
let sql = format!(110
r#"111
INSERT INTO112
station_stats113
(account_id, station_id, playtime)114
VALUES115
({account_id}, {station_id}, 1)116
ON CONFLICT (account_id, station_id)117
DO UPDATE118
SET playtime = station_stats.playtime + EXCLUDED.playtime,119
latest_at = now();120
"#,121
account_id = account.id,122
station_id = station.id,123
);124
let mut conn = req.sqlx_conn::<Postgres>().await;125
sqlx::query(&sql).execute(conn.acquire().await?).await?;126
let mut response = surf::get(&station.url).header("icy-metadata", "1").await?;127
let meta_int = match response.header("icy-metaint") {128
Some(header) => header.as_str(),129
None => return Response::throw("no icy metadata header found!"),130
};131
let interval = match meta_int.parse::<usize>() {132
Ok(interval) => interval * 2,133
Err(_) => return Response::throw("icy metadata interval is not a number!"),134
};135
let mut total = 0;136
let mut bytes = Vec::new();137
let mut buf = [0; 10000];138
let mut title = None;139
loop {140
let len =141
unwrap_result_or_throw!(response.read(&mut buf).await, "cannot read stream data!");142
bytes.extend_from_slice(&buf);143
if total + len > interval {144
let metadata = String::from_utf8_lossy(&bytes);145
if let Some(cap) =146
unwrap_result_or_throw!(Regex::new("StreamTitle='([^;]*)';"), "cannot parse regex!")147
.captures_iter(&metadata)148
.next()149
{150
title = Some(cap[1].to_string());151
}152
break;153
}154
if total > interval * 2 {155
warn!("too many iterations while acquiring song title!");156
break;157
}158
total += len;159
}160
Response::with(title)161
}163
pub async fn get_favorites(req: tide::Request<()>) -> tide::Result {164
let account =165
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");166
let sql = format!(167
r#"168
SELECT169
station.*,170
station_status.is_restricted,171
station_status.is_broken,172
station_status.is_no_track_info,173
station_status.is_hidden,174
station_status.is_icon,175
station_stats.playtime,176
true as is_favorite177
FROM station178
LEFT JOIN favorite179
ON station.id = favorite.station_id180
LEFT JOIN station_status181
ON station.id = station_status.station_id182
LEFT JOIN station_stats183
ON station.id = station_stats.station_id184
AND station_stats.account_id = {account_id}185
WHERE favorite.account_id = {account_id}186
AND station_status.is_hidden IS NOT true187
"#,188
account_id = account.id,189
);190
let mut conn = req.sqlx_conn::<Postgres>().await;191
let result = sqlx::query_as::<_, model::Station>(&sql)192
.fetch_all(conn.acquire().await?)193
.await?;194
Response::with(result)195
}197
pub async fn add_favorite(mut req: tide::Request<()>) -> tide::Result {198
let station_id = req.body_json::<i32>().await?;199
let account =200
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");201
let sql = format!(202
r#"203
INSERT INTO204
favorite205
(account_id, station_id)206
VALUES207
({account_id}, {station_id})208
"#,209
account_id = account.id,210
station_id = station_id,211
);212
let mut conn = req.sqlx_conn::<Postgres>().await;213
sqlx::query(&sql).execute(conn.acquire().await?).await?;214
Response::with(())215
}217
pub async fn delete_favorite(mut req: tide::Request<()>) -> tide::Result {218
let station_id = req.body_json::<i32>().await?;219
let account =220
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");221
let sql = format!(222
r#"223
DELETE FROM224
favorite225
WHERE account_id = {account_id}226
AND station_id = {station_id}227
"#,228
account_id = account.id,229
station_id = station_id,230
);231
let mut conn = req.sqlx_conn::<Postgres>().await;232
sqlx::query(&sql).execute(conn.acquire().await?).await?;233
Response::with(())234
}236
pub async fn get_station(req: tide::Request<()>) -> tide::Result {237
let station_id = unwrap_result_or_throw!(req.param("id"), "no station id found!");238
let account =239
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");240
let sql = format!(241
r#"242
SELECT243
station.*,244
station_status.is_restricted,245
station_status.is_broken,246
station_status.is_no_track_info,247
station_status.is_hidden,248
station_status.is_icon,249
station_stats.playtime,250
CASE251
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}252
THEN false253
ELSE true254
END AS is_favorite255
FROM station256
LEFT JOIN favorite257
ON station.id = favorite.station_id258
LEFT JOIN station_status259
ON station.id = station_status.station_id260
LEFT JOIN station_stats261
ON station.id = station_stats.station_id262
AND station_stats.account_id = {account_id}263
WHERE station.id = {station_id}264
AND station_status.is_hidden IS NOT true265
"#,266
account_id = account.id,267
station_id = station_id,268
);269
let mut conn = req.sqlx_conn::<Postgres>().await;270
let result = sqlx::query_as::<_, model::StationDetail>(&sql)271
.fetch_optional(conn.acquire().await?)272
.await?;273
Response::with(result)274
}276
pub async fn get_group(req: tide::Request<()>) -> tide::Result {277
let group_id = unwrap_result_or_throw!(req.param("id"), "no group id found!");278
let account =279
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");280
let mut conn = req.sqlx_conn::<Postgres>().await;281
let sql = format!(282
r#"283
SELECT284
station_group.*285
FROM station_group286
WHERE station_group.id = {group_id}287
"#,288
group_id = group_id,289
);290
let group = unwrap_option_or_throw!(291
sqlx::query_as::<_, model::StationGroup>(&sql)292
.fetch_optional(conn.acquire().await?)293
.await?,294
"no group with id found!"295
);296
let sql = format!(297
r#"298
SELECT299
station.*,300
station_status.is_restricted,301
station_status.is_broken,302
station_status.is_no_track_info,303
station_status.is_hidden,304
station_status.is_icon,305
station_stats.playtime,306
CASE307
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}308
THEN false309
ELSE true310
END AS is_favorite311
FROM station312
LEFT JOIN favorite313
ON station.id = favorite.station_id314
LEFT JOIN station_status315
ON station.id = station_status.station_id316
LEFT JOIN station_stats317
ON station.id = station_stats.station_id318
AND station_stats.account_id = {account_id}319
WHERE station.group_id = {group_id}320
AND station_status.is_hidden IS NOT true321
"#,322
account_id = account.id,323
group_id = group_id,324
);325
let stations = sqlx::query_as::<_, model::Station>(&sql)326
.fetch_all(conn.acquire().await?)327
.await?;328
#[derive(Serialize)]329
struct Result {330
group: model::StationGroup,331
stations: Vec<model::Station>,332
}333
let result = Result { group, stations };334
Response::with(result)335
}337
pub async fn get_countries(req: tide::Request<()>) -> tide::Result {338
let sql = r#"339
SELECT340
country341
FROM station342
WHERE country != ''343
GROUP BY country344
ORDER BY COUNT(*) DESC;345
"#346
.to_string();347
let mut conn = req.sqlx_conn::<Postgres>().await;348
let result = sqlx::query_as::<_, model::Value>(&sql)349
.fetch_all(conn.acquire().await?)350
.await?;351
Response::with(result)352
}354
pub async fn get_languages(req: tide::Request<()>) -> tide::Result {355
let sql = r#"356
SELECT357
UNNEST(languages) AS language358
FROM station359
GROUP BY UNNEST(languages)360
ORDER BY COUNT(*) DESC;361
"#362
.to_string();363
let mut conn = req.sqlx_conn::<Postgres>().await;364
let result = sqlx::query_as::<_, model::Value>(&sql)365
.fetch_all(conn.acquire().await?)366
.await?;367
Response::with(result)368
}370
pub async fn get_tags(req: tide::Request<()>) -> tide::Result {371
let sql = r#"372
SELECT373
UNNEST(tags) AS tag374
FROM station375
GROUP BY UNNEST(tags)376
ORDER BY COUNT(*) DESC377
LIMIT 100;378
"#379
.to_string();380
let mut conn = req.sqlx_conn::<Postgres>().await;381
let result = sqlx::query_as::<_, model::Value>(&sql)382
.fetch_all(conn.acquire().await?)383
.await?;384
Response::with(result)385
}387
pub async fn get_devices(req: tide::Request<()>) -> tide::Result {388
let account =389
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");390
let sql = format!(391
r#"392
SELECT393
device.*394
FROM device395
WHERE device.account_id = {account_id}396
"#,397
account_id = account.id,398
);399
let mut conn = req.sqlx_conn::<Postgres>().await;400
let result = sqlx::query_as::<_, model::Device>(&sql)401
.fetch_all(conn.acquire().await?)402
.await?;403
Response::with(result)404
}406
pub async fn update_account(mut req: tide::Request<()>) -> tide::Result {407
let updated_account = req.body_json::<model::Account>().await?;408
let account =409
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");410
let sql = format!(411
r#"412
UPDATE413
account414
SET415
name = '{name}',416
language = '{language}'417
WHERE account.id = {account_id}418
RETURNING *419
"#,420
account_id = account.id,421
name = updated_account.name.unwrap_or_default(),422
language = updated_account.language,423
);424
let mut conn = req.sqlx_conn::<Postgres>().await;425
let result = sqlx::query_as::<_, model::Account>(&sql)426
.fetch_one(conn.acquire().await?)427
.await?;428
Response::with(result)429
}