A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
blob: 3b787cfe3096c3fe50c7cad81ab12bfc29969052 (11493 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
station_stats.playtime,37
CASE38
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}39
THEN false40
ELSE true41
END AS is_favorite42
FROM station43
LEFT JOIN favorite44
ON station.id = favorite.station_id45
LEFT JOIN station_status46
ON station.id = station_status.station_id47
LEFT JOIN station_stats48
ON station.id = station_stats.station_id49
AND station_stats.account_id = {account_id}50
{conditions}51
AND station_status.is_hidden IS NOT true52
OFFSET {offset}53
LIMIT 1054
"#,55
account_id = account.id,56
offset = query.page.unwrap_or_default() * 10,57
conditions = unwrap_result_or_throw!(query.to_sql(), "cannot parse sql statement!"),58
);59
let mut conn = req.sqlx_conn::<Postgres>().await;60
let result = sqlx::query_as::<_, model::Station>(&sql)61
.fetch_all(conn.acquire().await?)62
.await?;63
Response::with(result)64
}66
pub async fn get_song(req: tide::Request<()>) -> tide::Result {67
let account =68
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");69
let station = req.query::<model::Station>()?;70
let sql = format!(71
r#"72
INSERT INTO73
station_stats74
(account_id, station_id, playtime)75
VALUES76
({account_id}, {station_id}, 1)77
ON CONFLICT (account_id, station_id)78
DO UPDATE79
SET playtime = station_stats.playtime + EXCLUDED.playtime;80
"#,81
account_id = account.id,82
station_id = station.id,83
);84
let mut conn = req.sqlx_conn::<Postgres>().await;85
sqlx::query(&sql).execute(conn.acquire().await?).await?;86
let mut response = surf::get(&station.url).header("icy-metadata", "1").await?;87
let meta_int = match response.header("icy-metaint") {88
Some(header) => header.as_str(),89
None => return Response::throw("no icy metadata header found!"),90
};91
let interval = match meta_int.parse::<usize>() {92
Ok(interval) => interval * 2,93
Err(_) => return Response::throw("icy metadata interval is not a number!"),94
};95
let mut total = 0;96
let mut bytes = Vec::new();97
let mut buf = [0; 10000];98
let mut title = None;99
loop {100
let len =101
unwrap_result_or_throw!(response.read(&mut buf).await, "cannot read stream data!");102
bytes.extend_from_slice(&buf);103
if total + len > interval {104
let metadata = String::from_utf8_lossy(&bytes);105
if let Some(cap) =106
unwrap_result_or_throw!(Regex::new("StreamTitle='([^;]*)';"), "cannot parse regex!")107
.captures_iter(&metadata)108
.next()109
{110
title = Some(cap[1].to_string());111
}112
break;113
}114
if total > interval * 2 {115
warn!("too many iterations while acquiring song title!");116
break;117
}118
total += len;119
}120
Response::with(title)121
}123
pub async fn get_favorites(req: tide::Request<()>) -> tide::Result {124
let account =125
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");126
let sql = format!(127
r#"128
SELECT129
station.*,130
station_status.is_restricted,131
station_status.is_broken,132
station_status.is_no_track_info,133
station_status.is_hidden,134
station_status.is_icon,135
station_stats.playtime,136
true as is_favorite137
FROM station138
LEFT JOIN favorite139
ON station.id = favorite.station_id140
LEFT JOIN station_status141
ON station.id = station_status.station_id142
LEFT JOIN station_stats143
ON station.id = station_stats.station_id144
AND station_stats.account_id = {account_id}145
WHERE favorite.account_id = {account_id}146
AND station_status.is_hidden IS NOT true147
"#,148
account_id = account.id,149
);150
let mut conn = req.sqlx_conn::<Postgres>().await;151
let result = sqlx::query_as::<_, model::Station>(&sql)152
.fetch_all(conn.acquire().await?)153
.await?;154
Response::with(result)155
}157
pub async fn add_favorite(mut req: tide::Request<()>) -> tide::Result {158
let station_id = req.body_json::<i32>().await?;159
let account =160
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");161
let sql = format!(162
r#"163
INSERT INTO164
favorite165
(account_id, station_id)166
VALUES167
({account_id}, {station_id})168
"#,169
account_id = account.id,170
station_id = station_id,171
);172
let mut conn = req.sqlx_conn::<Postgres>().await;173
sqlx::query(&sql).execute(conn.acquire().await?).await?;174
Response::with(())175
}177
pub async fn delete_favorite(mut req: tide::Request<()>) -> tide::Result {178
let station_id = req.body_json::<i32>().await?;179
let account =180
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");181
let sql = format!(182
r#"183
DELETE FROM184
favorite185
WHERE account_id = {account_id}186
AND station_id = {station_id}187
"#,188
account_id = account.id,189
station_id = station_id,190
);191
let mut conn = req.sqlx_conn::<Postgres>().await;192
sqlx::query(&sql).execute(conn.acquire().await?).await?;193
Response::with(())194
}196
pub async fn get_station(req: tide::Request<()>) -> tide::Result {197
let station_id = unwrap_result_or_throw!(req.param("id"), "no station id found!");198
let account =199
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");200
let sql = format!(201
r#"202
SELECT203
station.*,204
station_status.is_restricted,205
station_status.is_broken,206
station_status.is_no_track_info,207
station_status.is_hidden,208
station_status.is_icon,209
station_stats.playtime,210
CASE211
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}212
THEN false213
ELSE true214
END AS is_favorite215
FROM station216
LEFT JOIN favorite217
ON station.id = favorite.station_id218
LEFT JOIN station_status219
ON station.id = station_status.station_id220
LEFT JOIN station_stats221
ON station.id = station_stats.station_id222
AND station_stats.account_id = {account_id}223
WHERE station.id = {station_id}224
AND station_status.is_hidden IS NOT true225
"#,226
account_id = account.id,227
station_id = station_id,228
);229
let mut conn = req.sqlx_conn::<Postgres>().await;230
let result = sqlx::query_as::<_, model::StationDetail>(&sql)231
.fetch_optional(conn.acquire().await?)232
.await?;233
Response::with(result)234
}236
pub async fn get_countries(req: tide::Request<()>) -> tide::Result {237
let sql = r#"238
SELECT239
country240
FROM station241
WHERE country != ''242
GROUP BY country243
ORDER BY COUNT(*) DESC;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_languages(req: tide::Request<()>) -> tide::Result {254
let sql = r#"255
SELECT256
UNNEST(languages) AS language257
FROM station258
GROUP BY UNNEST(languages)259
ORDER BY COUNT(*) DESC;260
"#261
.to_string();262
let mut conn = req.sqlx_conn::<Postgres>().await;263
let result = sqlx::query_as::<_, model::Value>(&sql)264
.fetch_all(conn.acquire().await?)265
.await?;266
Response::with(result)267
}269
pub async fn get_tags(req: tide::Request<()>) -> tide::Result {270
let sql = r#"271
SELECT272
UNNEST(tags) AS tag273
FROM station274
GROUP BY UNNEST(tags)275
ORDER BY COUNT(*) DESC276
LIMIT 100;277
"#278
.to_string();279
let mut conn = req.sqlx_conn::<Postgres>().await;280
let result = sqlx::query_as::<_, model::Value>(&sql)281
.fetch_all(conn.acquire().await?)282
.await?;283
Response::with(result)284
}286
pub async fn get_devices(req: tide::Request<()>) -> tide::Result {287
let account =288
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");289
let sql = format!(290
r#"291
SELECT292
device.*293
FROM device294
WHERE device.account_id = {account_id}295
"#,296
account_id = account.id,297
);298
let mut conn = req.sqlx_conn::<Postgres>().await;299
let result = sqlx::query_as::<_, model::Device>(&sql)300
.fetch_all(conn.acquire().await?)301
.await?;302
Response::with(result)303
}305
pub async fn update_account(mut req: tide::Request<()>) -> tide::Result {306
let updated_account = req.body_json::<model::Account>().await?;307
let account =308
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");309
let sql = format!(310
r#"311
UPDATE312
account313
SET314
name = '{name}',315
language = '{language}'316
WHERE account.id = {account_id}317
RETURNING *318
"#,319
account_id = account.id,320
name = updated_account.name.unwrap_or_default(),321
language = updated_account.language,322
);323
let mut conn = req.sqlx_conn::<Postgres>().await;324
let result = sqlx::query_as::<_, model::Account>(&sql)325
.fetch_one(conn.acquire().await?)326
.await?;327
Response::with(result)328
}