A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
blob: bc330f0a0c03dff300359435a21cf212cf66076a (10872 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 account =64
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");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
let sql = format!(101
r#"102
INSERT INTO103
station_stats104
(account_id, station_id, playtime)105
VALUES106
({account_id}, {station_id}, 1)107
ON CONFLICT (account_id, station_id)108
DO UPDATE109
SET playtime = station_stats.playtime + EXCLUDED.playtime;110
"#,111
account_id = account.id,112
station_id = station.id,113
);114
let mut conn = req.sqlx_conn::<Postgres>().await;115
sqlx::query(&sql).execute(conn.acquire().await?).await?;116
Response::with(title)117
}119
pub async fn get_favorites(req: tide::Request<()>) -> tide::Result {120
let account =121
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");122
let sql = format!(123
r#"124
SELECT125
station.*,126
station_status.is_restricted,127
station_status.is_broken,128
station_status.is_no_track_info,129
station_status.is_hidden,130
station_status.is_icon,131
true as is_favorite132
FROM station133
LEFT JOIN favorite134
ON station.id = favorite.station_id135
LEFT JOIN station_status136
ON station.id = station_status.station_id137
WHERE favorite.account_id = {account_id}138
AND station_status.is_hidden IS NOT true139
"#,140
account_id = account.id,141
);142
let mut conn = req.sqlx_conn::<Postgres>().await;143
let result = sqlx::query_as::<_, model::Station>(&sql)144
.fetch_all(conn.acquire().await?)145
.await?;146
Response::with(result)147
}149
pub async fn add_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
INSERT INTO156
favorite157
(account_id, station_id)158
VALUES159
({account_id}, {station_id})160
"#,161
account_id = account.id,162
station_id = station_id,163
);164
let mut conn = req.sqlx_conn::<Postgres>().await;165
sqlx::query(&sql).execute(conn.acquire().await?).await?;166
Response::with(())167
}169
pub async fn delete_favorite(mut req: tide::Request<()>) -> tide::Result {170
let station_id = req.body_json::<i32>().await?;171
let account =172
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");173
let sql = format!(174
r#"175
DELETE FROM176
favorite177
WHERE account_id = {account_id}178
AND station_id = {station_id}179
"#,180
account_id = account.id,181
station_id = station_id,182
);183
let mut conn = req.sqlx_conn::<Postgres>().await;184
sqlx::query(&sql).execute(conn.acquire().await?).await?;185
Response::with(())186
}188
pub async fn get_station(req: tide::Request<()>) -> tide::Result {189
let station_id = unwrap_result_or_throw!(req.param("id"), "no station id found!");190
let account =191
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");192
let sql = format!(193
r#"194
SELECT195
station.*,196
station_status.is_restricted,197
station_status.is_broken,198
station_status.is_no_track_info,199
station_status.is_hidden,200
station_status.is_icon,201
CASE202
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}203
THEN false204
ELSE true205
END AS is_favorite206
FROM station207
LEFT JOIN favorite208
ON station.id = favorite.station_id209
LEFT JOIN station_status210
ON station.id = station_status.station_id211
WHERE station.id = {station_id}212
AND station_status.is_hidden IS NOT true213
"#,214
account_id = account.id,215
station_id = station_id,216
);217
let mut conn = req.sqlx_conn::<Postgres>().await;218
let result = sqlx::query_as::<_, model::Station>(&sql)219
.fetch_optional(conn.acquire().await?)220
.await?;221
Response::with(result)222
}224
pub async fn get_countries(req: tide::Request<()>) -> tide::Result {225
let sql = r#"226
SELECT227
country228
FROM station229
WHERE country != ''230
GROUP BY country231
ORDER BY COUNT(*) DESC;232
"#233
.to_string();234
let mut conn = req.sqlx_conn::<Postgres>().await;235
let result = sqlx::query_as::<_, model::Value>(&sql)236
.fetch_all(conn.acquire().await?)237
.await?;238
Response::with(result)239
}241
pub async fn get_languages(req: tide::Request<()>) -> tide::Result {242
let sql = r#"243
SELECT244
UNNEST(languages) AS language245
FROM station246
GROUP BY UNNEST(languages)247
ORDER BY COUNT(*) DESC;248
"#249
.to_string();250
let mut conn = req.sqlx_conn::<Postgres>().await;251
let result = sqlx::query_as::<_, model::Value>(&sql)252
.fetch_all(conn.acquire().await?)253
.await?;254
Response::with(result)255
}257
pub async fn get_tags(req: tide::Request<()>) -> tide::Result {258
let sql = r#"259
SELECT260
UNNEST(tags) AS tag261
FROM station262
GROUP BY UNNEST(tags)263
ORDER BY COUNT(*) DESC264
LIMIT 100;265
"#266
.to_string();267
let mut conn = req.sqlx_conn::<Postgres>().await;268
let result = sqlx::query_as::<_, model::Value>(&sql)269
.fetch_all(conn.acquire().await?)270
.await?;271
Response::with(result)272
}274
pub async fn get_devices(req: tide::Request<()>) -> tide::Result {275
let account =276
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");277
let sql = format!(278
r#"279
SELECT280
device.*281
FROM device282
WHERE device.account_id = {account_id}283
"#,284
account_id = account.id,285
);286
let mut conn = req.sqlx_conn::<Postgres>().await;287
let result = sqlx::query_as::<_, model::Device>(&sql)288
.fetch_all(conn.acquire().await?)289
.await?;290
Response::with(result)291
}293
pub async fn update_account(mut req: tide::Request<()>) -> tide::Result {294
let updated_account = req.body_json::<model::Account>().await?;295
let account =296
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");297
let sql = format!(298
r#"299
UPDATE300
account301
SET302
name = '{name}',303
language = '{language}'304
WHERE account.id = {account_id}305
RETURNING *306
"#,307
account_id = account.id,308
name = updated_account.name.unwrap_or_default(),309
language = updated_account.language,310
);311
let mut conn = req.sqlx_conn::<Postgres>().await;312
let result = sqlx::query_as::<_, model::Account>(&sql)313
.fetch_one(conn.acquire().await?)314
.await?;315
Response::with(result)316
}