A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
blob: 5a2e34f9a9b9c4fc3112c1de078a04bc799c4324 (10207 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 do_search(req: tide::Request<()>) -> tide::Result {24
let query = req.query::<model::Query>()?;25
let account =26
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");27
let sql = format!(28
r#"29
SELECT30
station.*,31
station_status.is_restricted,32
station_status.is_broken,33
station_status.is_no_track_info,34
station_status.is_hidden,35
station_status.is_icon,36
CASE37
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}38
THEN false39
ELSE true40
END AS is_favorite41
FROM station42
LEFT JOIN favorite43
ON station.id = favorite.station_id44
LEFT JOIN station_status45
ON station.id = station_status.station_id46
{conditions}47
AND station_status.is_hidden IS NOT true48
OFFSET {offset}49
LIMIT 1050
"#,51
account_id = account.id,52
offset = query.page.unwrap_or_default() * 10,53
conditions = unwrap_result_or_throw!(query.to_sql(), "cannot parse sql statement!"),54
);55
let mut conn = req.sqlx_conn::<Postgres>().await;56
let result = sqlx::query_as::<_, model::Station>(&sql)57
.fetch_all(conn.acquire().await?)58
.await?;59
Response::with(result)60
}62
pub async fn get_song(req: tide::Request<()>) -> tide::Result {63
let station = req.query::<model::Station>()?;64
let mut response = surf::get(&station.url).header("icy-metadata", "1").await?;65
let meta_int = match response.header("icy-metaint") {66
Some(header) => header.as_str(),67
None => return Response::throw("no icy metadata header found!"),68
};69
let interval = match meta_int.parse::<usize>() {70
Ok(interval) => interval * 2,71
Err(_) => return Response::throw("icy metadata interval is not a number!"),72
};73
let mut total = 0;74
let mut bytes = Vec::new();75
let mut buf = [0; 10000];76
let mut title = None;77
loop {78
let len =79
unwrap_result_or_throw!(response.read(&mut buf).await, "cannot read stream data!");80
bytes.extend_from_slice(&buf);81
if total + len > interval {82
let metadata = String::from_utf8_lossy(&bytes);83
if let Some(cap) =84
unwrap_result_or_throw!(Regex::new("StreamTitle='([^;]*)';"), "cannot parse regex!")85
.captures_iter(&metadata)86
.next()87
{88
title = Some(cap[1].to_string());89
}90
break;91
}92
if total > interval * 2 {93
warn!("too many iterations while acquiring song title!");94
break;95
}96
total += len;97
}98
Response::with(title)99
}101
pub async fn get_favorites(req: tide::Request<()>) -> tide::Result {102
let account =103
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");104
let sql = format!(105
r#"106
SELECT107
station.*,108
station_status.is_restricted,109
station_status.is_broken,110
station_status.is_no_track_info,111
station_status.is_hidden,112
station_status.is_icon,113
true as is_favorite114
FROM station115
LEFT JOIN favorite116
ON station.id = favorite.station_id117
LEFT JOIN station_status118
ON station.id = station_status.station_id119
WHERE favorite.account_id = {account_id}120
AND station_status.is_hidden IS NOT true121
"#,122
account_id = account.id,123
);124
let mut conn = req.sqlx_conn::<Postgres>().await;125
let result = sqlx::query_as::<_, model::Station>(&sql)126
.fetch_all(conn.acquire().await?)127
.await?;128
Response::with(result)129
}131
pub async fn add_favorite(mut req: tide::Request<()>) -> tide::Result {132
let station_id = req.body_json::<i32>().await?;133
let account =134
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");135
let sql = format!(136
r#"137
INSERT INTO138
favorite139
(account_id, station_id)140
VALUES141
({account_id}, {station_id})142
"#,143
account_id = account.id,144
station_id = station_id,145
);146
let mut conn = req.sqlx_conn::<Postgres>().await;147
sqlx::query(&sql).execute(conn.acquire().await?).await?;148
Response::with(())149
}151
pub async fn delete_favorite(mut req: tide::Request<()>) -> tide::Result {152
let station_id = req.body_json::<i32>().await?;153
let account =154
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");155
let sql = format!(156
r#"157
DELETE FROM158
favorite159
WHERE account_id = {account_id}160
AND station_id = {station_id}161
"#,162
account_id = account.id,163
station_id = station_id,164
);165
let mut conn = req.sqlx_conn::<Postgres>().await;166
sqlx::query(&sql).execute(conn.acquire().await?).await?;167
Response::with(())168
}170
pub async fn get_station(req: tide::Request<()>) -> tide::Result {171
let station_id = unwrap_result_or_throw!(req.param("id"), "no station id found!");172
let account =173
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");174
let sql = format!(175
r#"176
SELECT177
station.*,178
station_status.is_restricted,179
station_status.is_broken,180
station_status.is_no_track_info,181
station_status.is_hidden,182
station_status.is_icon,183
CASE184
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}185
THEN false186
ELSE true187
END AS is_favorite188
FROM station189
LEFT JOIN favorite190
ON station.id = favorite.station_id191
LEFT JOIN station_status192
ON station.id = station_status.station_id193
WHERE station.id = {station_id}194
AND station_status.is_hidden IS NOT true195
"#,196
account_id = account.id,197
station_id = station_id,198
);199
let mut conn = req.sqlx_conn::<Postgres>().await;200
let result = sqlx::query_as::<_, model::Station>(&sql)201
.fetch_optional(conn.acquire().await?)202
.await?;203
Response::with(result)204
}206
pub async fn get_countries(req: tide::Request<()>) -> tide::Result {207
let sql = r#"208
SELECT209
country210
FROM station211
WHERE country != ''212
GROUP BY country213
ORDER BY COUNT(*) DESC;214
"#215
.to_string();216
let mut conn = req.sqlx_conn::<Postgres>().await;217
let result = sqlx::query_as::<_, model::Value>(&sql)218
.fetch_all(conn.acquire().await?)219
.await?;220
Response::with(result)221
}223
pub async fn get_languages(req: tide::Request<()>) -> tide::Result {224
let sql = r#"225
SELECT226
UNNEST(languages) AS language227
FROM station228
GROUP BY UNNEST(languages)229
ORDER BY COUNT(*) DESC;230
"#231
.to_string();232
let mut conn = req.sqlx_conn::<Postgres>().await;233
let result = sqlx::query_as::<_, model::Value>(&sql)234
.fetch_all(conn.acquire().await?)235
.await?;236
Response::with(result)237
}239
pub async fn get_tags(req: tide::Request<()>) -> tide::Result {240
let sql = r#"241
SELECT242
UNNEST(tags) AS tag243
FROM station244
GROUP BY UNNEST(tags)245
ORDER BY COUNT(*) DESC246
LIMIT 100;247
"#248
.to_string();249
let mut conn = req.sqlx_conn::<Postgres>().await;250
let result = sqlx::query_as::<_, model::Value>(&sql)251
.fetch_all(conn.acquire().await?)252
.await?;253
Response::with(result)254
}256
pub async fn get_devices(req: tide::Request<()>) -> tide::Result {257
let account =258
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");259
let sql = format!(260
r#"261
SELECT262
device.*263
FROM device264
WHERE device.account_id = {account_id}265
"#,266
account_id = account.id,267
);268
let mut conn = req.sqlx_conn::<Postgres>().await;269
let result = sqlx::query_as::<_, model::Device>(&sql)270
.fetch_all(conn.acquire().await?)271
.await?;272
Response::with(result)273
}275
pub async fn update_account(mut req: tide::Request<()>) -> tide::Result {276
let updated_account = req.body_json::<model::Account>().await?;277
let account =278
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");279
let sql = format!(280
r#"281
UPDATE282
account283
SET284
name = '{name}',285
language = '{language}'286
WHERE account.id = {account_id}287
RETURNING *288
"#,289
account_id = account.id,290
name = updated_account.name.unwrap_or_default(),291
language = updated_account.language,292
);293
let mut conn = req.sqlx_conn::<Postgres>().await;294
let result = sqlx::query_as::<_, model::Account>(&sql)295
.fetch_one(conn.acquire().await?)296
.await?;297
Response::with(result)298
}