A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
blob: e0b2d671867565ff98653d702c6780c3deff394d (12649 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
"#,119
account_id = account.id,120
station_id = station.id,121
);122
let mut conn = req.sqlx_conn::<Postgres>().await;123
sqlx::query(&sql).execute(conn.acquire().await?).await?;124
let mut response = surf::get(&station.url).header("icy-metadata", "1").await?;125
let meta_int = match response.header("icy-metaint") {126
Some(header) => header.as_str(),127
None => return Response::throw("no icy metadata header found!"),128
};129
let interval = match meta_int.parse::<usize>() {130
Ok(interval) => interval * 2,131
Err(_) => return Response::throw("icy metadata interval is not a number!"),132
};133
let mut total = 0;134
let mut bytes = Vec::new();135
let mut buf = [0; 10000];136
let mut title = None;137
loop {138
let len =139
unwrap_result_or_throw!(response.read(&mut buf).await, "cannot read stream data!");140
bytes.extend_from_slice(&buf);141
if total + len > interval {142
let metadata = String::from_utf8_lossy(&bytes);143
if let Some(cap) =144
unwrap_result_or_throw!(Regex::new("StreamTitle='([^;]*)';"), "cannot parse regex!")145
.captures_iter(&metadata)146
.next()147
{148
title = Some(cap[1].to_string());149
}150
break;151
}152
if total > interval * 2 {153
warn!("too many iterations while acquiring song title!");154
break;155
}156
total += len;157
}158
Response::with(title)159
}161
pub async fn get_favorites(req: tide::Request<()>) -> tide::Result {162
let account =163
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");164
let sql = format!(165
r#"166
SELECT167
station.*,168
station_status.is_restricted,169
station_status.is_broken,170
station_status.is_no_track_info,171
station_status.is_hidden,172
station_status.is_icon,173
station_stats.playtime,174
true as is_favorite175
FROM station176
LEFT JOIN favorite177
ON station.id = favorite.station_id178
LEFT JOIN station_status179
ON station.id = station_status.station_id180
LEFT JOIN station_stats181
ON station.id = station_stats.station_id182
AND station_stats.account_id = {account_id}183
WHERE favorite.account_id = {account_id}184
AND station_status.is_hidden IS NOT true185
"#,186
account_id = account.id,187
);188
let mut conn = req.sqlx_conn::<Postgres>().await;189
let result = sqlx::query_as::<_, model::Station>(&sql)190
.fetch_all(conn.acquire().await?)191
.await?;192
Response::with(result)193
}195
pub async fn add_favorite(mut req: tide::Request<()>) -> tide::Result {196
let station_id = req.body_json::<i32>().await?;197
let account =198
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");199
let sql = format!(200
r#"201
INSERT INTO202
favorite203
(account_id, station_id)204
VALUES205
({account_id}, {station_id})206
"#,207
account_id = account.id,208
station_id = station_id,209
);210
let mut conn = req.sqlx_conn::<Postgres>().await;211
sqlx::query(&sql).execute(conn.acquire().await?).await?;212
Response::with(())213
}215
pub async fn delete_favorite(mut req: tide::Request<()>) -> tide::Result {216
let station_id = req.body_json::<i32>().await?;217
let account =218
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");219
let sql = format!(220
r#"221
DELETE FROM222
favorite223
WHERE account_id = {account_id}224
AND station_id = {station_id}225
"#,226
account_id = account.id,227
station_id = station_id,228
);229
let mut conn = req.sqlx_conn::<Postgres>().await;230
sqlx::query(&sql).execute(conn.acquire().await?).await?;231
Response::with(())232
}234
pub async fn get_station(req: tide::Request<()>) -> tide::Result {235
let station_id = unwrap_result_or_throw!(req.param("id"), "no station id found!");236
let account =237
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");238
let sql = format!(239
r#"240
SELECT241
station.*,242
station_status.is_restricted,243
station_status.is_broken,244
station_status.is_no_track_info,245
station_status.is_hidden,246
station_status.is_icon,247
station_stats.playtime,248
CASE249
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}250
THEN false251
ELSE true252
END AS is_favorite253
FROM station254
LEFT JOIN favorite255
ON station.id = favorite.station_id256
LEFT JOIN station_status257
ON station.id = station_status.station_id258
LEFT JOIN station_stats259
ON station.id = station_stats.station_id260
AND station_stats.account_id = {account_id}261
WHERE station.id = {station_id}262
AND station_status.is_hidden IS NOT true263
"#,264
account_id = account.id,265
station_id = station_id,266
);267
let mut conn = req.sqlx_conn::<Postgres>().await;268
let result = sqlx::query_as::<_, model::StationDetail>(&sql)269
.fetch_optional(conn.acquire().await?)270
.await?;271
Response::with(result)272
}274
pub async fn get_countries(req: tide::Request<()>) -> tide::Result {275
let sql = r#"276
SELECT277
country278
FROM station279
WHERE country != ''280
GROUP BY country281
ORDER BY COUNT(*) DESC;282
"#283
.to_string();284
let mut conn = req.sqlx_conn::<Postgres>().await;285
let result = sqlx::query_as::<_, model::Value>(&sql)286
.fetch_all(conn.acquire().await?)287
.await?;288
Response::with(result)289
}291
pub async fn get_languages(req: tide::Request<()>) -> tide::Result {292
let sql = r#"293
SELECT294
UNNEST(languages) AS language295
FROM station296
GROUP BY UNNEST(languages)297
ORDER BY COUNT(*) DESC;298
"#299
.to_string();300
let mut conn = req.sqlx_conn::<Postgres>().await;301
let result = sqlx::query_as::<_, model::Value>(&sql)302
.fetch_all(conn.acquire().await?)303
.await?;304
Response::with(result)305
}307
pub async fn get_tags(req: tide::Request<()>) -> tide::Result {308
let sql = r#"309
SELECT310
UNNEST(tags) AS tag311
FROM station312
GROUP BY UNNEST(tags)313
ORDER BY COUNT(*) DESC314
LIMIT 100;315
"#316
.to_string();317
let mut conn = req.sqlx_conn::<Postgres>().await;318
let result = sqlx::query_as::<_, model::Value>(&sql)319
.fetch_all(conn.acquire().await?)320
.await?;321
Response::with(result)322
}324
pub async fn get_devices(req: tide::Request<()>) -> tide::Result {325
let account =326
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");327
let sql = format!(328
r#"329
SELECT330
device.*331
FROM device332
WHERE device.account_id = {account_id}333
"#,334
account_id = account.id,335
);336
let mut conn = req.sqlx_conn::<Postgres>().await;337
let result = sqlx::query_as::<_, model::Device>(&sql)338
.fetch_all(conn.acquire().await?)339
.await?;340
Response::with(result)341
}343
pub async fn update_account(mut req: tide::Request<()>) -> tide::Result {344
let updated_account = req.body_json::<model::Account>().await?;345
let account =346
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");347
let sql = format!(348
r#"349
UPDATE350
account351
SET352
name = '{name}',353
language = '{language}'354
WHERE account.id = {account_id}355
RETURNING *356
"#,357
account_id = account.id,358
name = updated_account.name.unwrap_or_default(),359
language = updated_account.language,360
);361
let mut conn = req.sqlx_conn::<Postgres>().await;362
let result = sqlx::query_as::<_, model::Account>(&sql)363
.fetch_one(conn.acquire().await?)364
.await?;365
Response::with(result)366
}