A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
blob: 860704b3ea3c266c82960daa5e5cd130ac5be50e (10087 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
CASE36
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}37
THEN false38
ELSE true39
END AS is_favorite40
FROM station41
LEFT JOIN favorite42
ON station.id = favorite.station_id43
LEFT JOIN station_status44
ON station.id = station_status.station_id45
{conditions}46
AND station_status.is_hidden IS NOT true47
OFFSET {offset}48
LIMIT 1049
"#,50
account_id = account.id,51
offset = query.page.unwrap_or_default() * 10,52
conditions = unwrap_result_or_throw!(query.to_sql(), "cannot parse sql statement!"),53
);54
let mut conn = req.sqlx_conn::<Postgres>().await;55
let result = sqlx::query_as::<_, model::Station>(&sql)56
.fetch_all(conn.acquire().await?)57
.await?;58
Response::with(result)59
}61
pub async fn get_song(req: tide::Request<()>) -> tide::Result {62
let station = req.query::<model::Station>()?;63
let mut response = surf::get(&station.url).header("icy-metadata", "1").await?;64
let meta_int = match response.header("icy-metaint") {65
Some(header) => header.as_str(),66
None => return Response::throw("no icy metadata header found!"),67
};68
let interval = match meta_int.parse::<usize>() {69
Ok(interval) => interval * 2,70
Err(_) => return Response::throw("icy metadata interval is not a number!"),71
};72
let mut total = 0;73
let mut bytes = Vec::new();74
let mut buf = [0; 10000];75
let mut title = None;76
loop {77
let len =78
unwrap_result_or_throw!(response.read(&mut buf).await, "cannot read stream data!");79
bytes.extend_from_slice(&buf);80
if total + len > interval {81
let metadata = String::from_utf8_lossy(&bytes);82
if let Some(cap) =83
unwrap_result_or_throw!(Regex::new("StreamTitle='([^;]*)';"), "cannot parse regex!")84
.captures_iter(&metadata)85
.next()86
{87
title = Some(cap[1].to_string());88
}89
break;90
}91
if total > interval * 2 {92
warn!("too many iterations while acquiring song title!");93
break;94
}95
total += len;96
}97
Response::with(title)98
}100
pub async fn get_favorites(req: tide::Request<()>) -> tide::Result {101
let account =102
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");103
let sql = format!(104
r#"105
SELECT106
station.*,107
station_status.is_restricted,108
station_status.is_broken,109
station_status.is_no_track_info,110
station_status.is_hidden,111
true as is_favorite112
FROM station113
LEFT JOIN favorite114
ON station.id = favorite.station_id115
LEFT JOIN station_status116
ON station.id = station_status.station_id117
WHERE favorite.account_id = {account_id}118
AND station_status.is_hidden IS NOT true119
"#,120
account_id = account.id,121
);122
let mut conn = req.sqlx_conn::<Postgres>().await;123
let result = sqlx::query_as::<_, model::Station>(&sql)124
.fetch_all(conn.acquire().await?)125
.await?;126
Response::with(result)127
}129
pub async fn add_favorite(mut req: tide::Request<()>) -> tide::Result {130
let station_id = req.body_json::<i32>().await?;131
let account =132
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");133
let sql = format!(134
r#"135
INSERT INTO136
favorite137
(account_id, station_id)138
VALUES139
({account_id}, {station_id})140
"#,141
account_id = account.id,142
station_id = station_id,143
);144
let mut conn = req.sqlx_conn::<Postgres>().await;145
sqlx::query(&sql).execute(conn.acquire().await?).await?;146
Response::with(())147
}149
pub async fn delete_favorite(mut req: tide::Request<()>) -> tide::Result {150
let station_id = req.body_json::<i32>().await?;151
let account =152
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");153
let sql = format!(154
r#"155
DELETE FROM156
favorite157
WHERE account_id = {account_id}158
AND station_id = {station_id}159
"#,160
account_id = account.id,161
station_id = station_id,162
);163
let mut conn = req.sqlx_conn::<Postgres>().await;164
sqlx::query(&sql).execute(conn.acquire().await?).await?;165
Response::with(())166
}168
pub async fn get_station(req: tide::Request<()>) -> tide::Result {169
let station_id = unwrap_result_or_throw!(req.param("id"), "no station id found!");170
let account =171
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");172
let sql = format!(173
r#"174
SELECT175
station.*,176
station_status.is_restricted,177
station_status.is_broken,178
station_status.is_no_track_info,179
station_status.is_hidden,180
CASE181
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}182
THEN false183
ELSE true184
END AS is_favorite185
FROM station186
LEFT JOIN favorite187
ON station.id = favorite.station_id188
LEFT JOIN station_status189
ON station.id = station_status.station_id190
WHERE station.id = {station_id}191
AND station_status.is_hidden IS NOT true192
"#,193
account_id = account.id,194
station_id = station_id,195
);196
let mut conn = req.sqlx_conn::<Postgres>().await;197
let result = sqlx::query_as::<_, model::Station>(&sql)198
.fetch_optional(conn.acquire().await?)199
.await?;200
Response::with(result)201
}203
pub async fn get_countries(req: tide::Request<()>) -> tide::Result {204
let sql = r#"205
SELECT206
country207
FROM station208
WHERE country != ''209
GROUP BY country210
ORDER BY COUNT(*) DESC;211
"#212
.to_string();213
let mut conn = req.sqlx_conn::<Postgres>().await;214
let result = sqlx::query_as::<_, model::Value>(&sql)215
.fetch_all(conn.acquire().await?)216
.await?;217
Response::with(result)218
}220
pub async fn get_languages(req: tide::Request<()>) -> tide::Result {221
let sql = r#"222
SELECT223
UNNEST(languages) AS language224
FROM station225
GROUP BY UNNEST(languages)226
ORDER BY COUNT(*) DESC;227
"#228
.to_string();229
let mut conn = req.sqlx_conn::<Postgres>().await;230
let result = sqlx::query_as::<_, model::Value>(&sql)231
.fetch_all(conn.acquire().await?)232
.await?;233
Response::with(result)234
}236
pub async fn get_tags(req: tide::Request<()>) -> tide::Result {237
let sql = r#"238
SELECT239
UNNEST(tags) AS tag240
FROM station241
GROUP BY UNNEST(tags)242
ORDER BY COUNT(*) DESC243
LIMIT 100;244
"#245
.to_string();246
let mut conn = req.sqlx_conn::<Postgres>().await;247
let result = sqlx::query_as::<_, model::Value>(&sql)248
.fetch_all(conn.acquire().await?)249
.await?;250
Response::with(result)251
}253
pub async fn get_devices(req: tide::Request<()>) -> tide::Result {254
let account =255
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");256
let sql = format!(257
r#"258
SELECT259
device.*260
FROM device261
WHERE device.account_id = {account_id}262
"#,263
account_id = account.id,264
);265
let mut conn = req.sqlx_conn::<Postgres>().await;266
let result = sqlx::query_as::<_, model::Device>(&sql)267
.fetch_all(conn.acquire().await?)268
.await?;269
Response::with(result)270
}272
pub async fn update_account(mut req: tide::Request<()>) -> tide::Result {273
let updated_account = req.body_json::<model::Account>().await?;274
let account =275
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");276
let sql = format!(277
r#"278
UPDATE279
account280
SET281
name = '{name}',282
language = '{language}'283
WHERE account.id = {account_id}284
RETURNING *285
"#,286
account_id = account.id,287
name = updated_account.name.unwrap_or_default(),288
language = updated_account.language,289
);290
let mut conn = req.sqlx_conn::<Postgres>().await;291
let result = sqlx::query_as::<_, model::Account>(&sql)292
.fetch_one(conn.acquire().await?)293
.await?;294
Response::with(result)295
}