A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
blob: 87de61a00509aa993a60f89dd7d16e7c8f697c3b (8210 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::model::StationCountry;9
use crate::model::StationId;10
use crate::model::StationLanguage;11
use crate::unwrap_option_or_throw;12
use crate::unwrap_result_or_throw;13
use crate::Response;14
use crate::ToSql;16
pub async fn do_prefetch(_: tide::Request<()>) -> tide::Result {17
Ok(tide::Response::new(200))18
}20
pub async fn get_account(req: tide::Request<()>) -> tide::Result {21
let account =22
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");23
Response::with(account)24
}26
pub async fn do_search(req: tide::Request<()>) -> tide::Result {27
let query = req.query::<model::Query>()?;28
let account =29
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");30
let sql = format!(31
r#"32
SELECT33
station.*,34
station_status.is_restricted,35
station_status.is_broken,36
station_status.is_no_track_info,37
station_status.is_hidden,38
CASE39
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}40
THEN false41
ELSE true42
END AS is_favorite43
FROM station44
LEFT JOIN favorite45
ON station.id = favorite.station_id46
LEFT JOIN station_status47
ON station.id = station_status.station_id48
{conditions}49
AND station_status.is_hidden IS NOT true50
OFFSET {offset}51
LIMIT 1052
"#,53
account_id = account.id,54
offset = query.page.unwrap_or_default() * 10,55
conditions = unwrap_result_or_throw!(query.to_sql(), "cannot parse sql statement!"),56
);57
let mut conn = req.sqlx_conn::<Postgres>().await;58
let result = sqlx::query_as::<_, model::Station>(&sql)59
.fetch_all(conn.acquire().await?)60
.await?;61
Response::with(result)62
}64
pub async fn get_song(req: tide::Request<()>) -> tide::Result {65
let station = req.query::<model::Station>()?;66
let mut response = surf::get(&station.url).header("icy-metadata", "1").await?;67
let meta_int = match response.header("icy-metaint") {68
Some(header) => header.as_str(),69
None => return Response::throw("no icy metadata header found!"),70
};71
let interval = match meta_int.parse::<usize>() {72
Ok(interval) => interval * 2,73
Err(_) => return Response::throw("icy metadata interval is not a number!"),74
};75
let mut total = 0;76
let mut bytes = Vec::new();77
let mut buf = [0; 10000];78
let mut title = None;79
loop {80
let len =81
unwrap_result_or_throw!(response.read(&mut buf).await, "cannot read stream data!");82
bytes.extend_from_slice(&buf);83
if total + len > interval {84
let metadata = String::from_utf8_lossy(&bytes);85
if let Some(cap) =86
unwrap_result_or_throw!(Regex::new("StreamTitle='([^;]*)';"), "cannot parse regex!")87
.captures_iter(&metadata)88
.next()89
{90
title = Some(cap[1].to_string());91
}92
break;93
}94
if total > interval * 2 {95
warn!("too many iterations while acquiring song title!");96
break;97
}98
total += len;99
}100
Response::with(title)101
}103
pub async fn get_favorites(req: tide::Request<()>) -> tide::Result {104
let account =105
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");106
let sql = format!(107
r#"108
SELECT109
station.*,110
station_status.is_restricted,111
station_status.is_broken,112
station_status.is_no_track_info,113
station_status.is_hidden,114
true as is_favorite115
FROM station116
LEFT JOIN favorite117
ON station.id = favorite.station_id118
LEFT JOIN station_status119
ON station.id = station_status.station_id120
WHERE favorite.account_id = {account_id}121
AND station_status.is_hidden IS NOT true122
"#,123
account_id = account.id,124
);125
let mut conn = req.sqlx_conn::<Postgres>().await;126
let result = sqlx::query_as::<_, model::Station>(&sql)127
.fetch_all(conn.acquire().await?)128
.await?;129
Response::with(result)130
}132
pub async fn add_favorite(mut req: tide::Request<()>) -> tide::Result {133
let station_id = req.body_json::<i32>().await?;134
let account =135
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");136
let sql = format!(137
r#"138
INSERT INTO139
favorite140
(account_id, station_id)141
VALUES142
({account_id}, {station_id})143
"#,144
account_id = account.id,145
station_id = station_id,146
);147
let mut conn = req.sqlx_conn::<Postgres>().await;148
sqlx::query(&sql).execute(conn.acquire().await?).await?;149
Response::with(())150
}152
pub async fn delete_favorite(mut req: tide::Request<()>) -> tide::Result {153
let station_id = req.body_json::<i32>().await?;154
let account =155
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");156
let sql = format!(157
r#"158
DELETE FROM159
favorite160
WHERE account_id = {account_id}161
AND station_id = {station_id}162
"#,163
account_id = account.id,164
station_id = station_id,165
);166
let mut conn = req.sqlx_conn::<Postgres>().await;167
sqlx::query(&sql).execute(conn.acquire().await?).await?;168
Response::with(())169
}171
pub async fn get_station(req: tide::Request<()>) -> tide::Result {172
let station_id = req.query::<StationId>()?;173
let account =174
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");175
let sql = format!(176
r#"177
SELECT178
station.*,179
station_status.is_restricted,180
station_status.is_broken,181
station_status.is_no_track_info,182
station_status.is_hidden,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.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 = format!(208
r#"209
SELECT210
country211
FROM station212
WHERE country != ''213
GROUP BY country214
ORDER BY COUNT(*) DESC;215
"#,216
);217
let mut conn = req.sqlx_conn::<Postgres>().await;218
let result = sqlx::query_as::<_, StationCountry>(&sql)219
.fetch_all(conn.acquire().await?)220
.await?;221
Response::with(result)222
}224
pub async fn get_languages(req: tide::Request<()>) -> tide::Result {225
let sql = format!(226
r#"227
SELECT228
UNNEST(languages) AS language229
FROM station230
GROUP BY UNNEST(languages)231
ORDER BY COUNT(*) DESC;232
"#,233
);234
let mut conn = req.sqlx_conn::<Postgres>().await;235
let result = sqlx::query_as::<_, StationLanguage>(&sql)236
.fetch_all(conn.acquire().await?)237
.await?;238
Response::with(result)239
}