A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
blob: 1ca755c815c66a1f8327a20dda9dbf87e0e77ca2 (12739 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 add_account(mut req: tide::Request<()>) -> tide::Result {24
if req.ext::<model::Account>().is_some() {25
return Response::throw("already logged in with another account!");26
}27
let add_account = req.body_json::<model::AddAccount>().await?;28
info!("{:#?}", add_account);29
let mut conn = req.sqlx_conn::<Postgres>().await;30
let sql = format!(31
r#"32
INSERT INTO33
account34
(name, language)35
VALUES36
('{name}', '{language}')37
RETURNING account.*38
"#,39
name = add_account.name,40
language = add_account.language,41
);42
let account = sqlx::query_as::<_, model::Account>(&sql)43
.fetch_one(conn.acquire().await?)44
.await?;45
info!("{:#?}", account);46
let sql = format!(47
r#"48
INSERT INTO49
device50
(uid, account_id)51
VALUES52
(uuid_generate_v4(), {account_id})53
RETURNING device.*54
"#,55
account_id = account.id,56
);57
let device = sqlx::query_as::<_, model::Device>(&sql)58
.fetch_one(conn.acquire().await?)59
.await?;60
info!("{:#?}", device);61
Response::with(device)62
}64
pub async fn do_search(req: tide::Request<()>) -> tide::Result {65
let query = req.query::<model::Query>()?;66
let account =67
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");68
let sql = format!(69
r#"70
SELECT71
station.*,72
station_status.is_restricted,73
station_status.is_broken,74
station_status.is_no_track_info,75
station_status.is_hidden,76
station_status.is_icon,77
station_stats.playtime,78
CASE79
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}80
THEN false81
ELSE true82
END AS is_favorite83
FROM station84
LEFT JOIN favorite85
ON station.id = favorite.station_id86
LEFT JOIN station_status87
ON station.id = station_status.station_id88
LEFT JOIN station_stats89
ON station.id = station_stats.station_id90
AND station_stats.account_id = {account_id}91
{conditions}92
AND station_status.is_hidden IS NOT true93
OFFSET {offset}94
LIMIT 1095
"#,96
account_id = account.id,97
offset = query.page.unwrap_or_default() * 10,98
conditions = unwrap_result_or_throw!(query.to_sql(), "cannot parse sql statement!"),99
);100
let mut conn = req.sqlx_conn::<Postgres>().await;101
let result = sqlx::query_as::<_, model::Station>(&sql)102
.fetch_all(conn.acquire().await?)103
.await?;104
Response::with(result)105
}107
pub async fn get_song(req: tide::Request<()>) -> tide::Result {108
let account =109
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");110
let station = req.query::<model::Station>()?;111
let sql = format!(112
r#"113
INSERT INTO114
station_stats115
(account_id, station_id, playtime)116
VALUES117
({account_id}, {station_id}, 1)118
ON CONFLICT (account_id, station_id)119
DO UPDATE120
SET playtime = station_stats.playtime + EXCLUDED.playtime;121
"#,122
account_id = account.id,123
station_id = station.id,124
);125
let mut conn = req.sqlx_conn::<Postgres>().await;126
sqlx::query(&sql).execute(conn.acquire().await?).await?;127
let mut response = surf::get(&station.url).header("icy-metadata", "1").await?;128
let meta_int = match response.header("icy-metaint") {129
Some(header) => header.as_str(),130
None => return Response::throw("no icy metadata header found!"),131
};132
let interval = match meta_int.parse::<usize>() {133
Ok(interval) => interval * 2,134
Err(_) => return Response::throw("icy metadata interval is not a number!"),135
};136
let mut total = 0;137
let mut bytes = Vec::new();138
let mut buf = [0; 10000];139
let mut title = None;140
loop {141
let len =142
unwrap_result_or_throw!(response.read(&mut buf).await, "cannot read stream data!");143
bytes.extend_from_slice(&buf);144
if total + len > interval {145
let metadata = String::from_utf8_lossy(&bytes);146
if let Some(cap) =147
unwrap_result_or_throw!(Regex::new("StreamTitle='([^;]*)';"), "cannot parse regex!")148
.captures_iter(&metadata)149
.next()150
{151
title = Some(cap[1].to_string());152
}153
break;154
}155
if total > interval * 2 {156
warn!("too many iterations while acquiring song title!");157
break;158
}159
total += len;160
}161
Response::with(title)162
}164
pub async fn get_favorites(req: tide::Request<()>) -> tide::Result {165
let account =166
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");167
let sql = format!(168
r#"169
SELECT170
station.*,171
station_status.is_restricted,172
station_status.is_broken,173
station_status.is_no_track_info,174
station_status.is_hidden,175
station_status.is_icon,176
station_stats.playtime,177
true as is_favorite178
FROM station179
LEFT JOIN favorite180
ON station.id = favorite.station_id181
LEFT JOIN station_status182
ON station.id = station_status.station_id183
LEFT JOIN station_stats184
ON station.id = station_stats.station_id185
AND station_stats.account_id = {account_id}186
WHERE favorite.account_id = {account_id}187
AND station_status.is_hidden IS NOT true188
"#,189
account_id = account.id,190
);191
let mut conn = req.sqlx_conn::<Postgres>().await;192
let result = sqlx::query_as::<_, model::Station>(&sql)193
.fetch_all(conn.acquire().await?)194
.await?;195
Response::with(result)196
}198
pub async fn add_favorite(mut req: tide::Request<()>) -> tide::Result {199
let station_id = req.body_json::<i32>().await?;200
let account =201
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");202
let sql = format!(203
r#"204
INSERT INTO205
favorite206
(account_id, station_id)207
VALUES208
({account_id}, {station_id})209
"#,210
account_id = account.id,211
station_id = station_id,212
);213
let mut conn = req.sqlx_conn::<Postgres>().await;214
sqlx::query(&sql).execute(conn.acquire().await?).await?;215
Response::with(())216
}218
pub async fn delete_favorite(mut req: tide::Request<()>) -> tide::Result {219
let station_id = req.body_json::<i32>().await?;220
let account =221
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");222
let sql = format!(223
r#"224
DELETE FROM225
favorite226
WHERE account_id = {account_id}227
AND station_id = {station_id}228
"#,229
account_id = account.id,230
station_id = station_id,231
);232
let mut conn = req.sqlx_conn::<Postgres>().await;233
sqlx::query(&sql).execute(conn.acquire().await?).await?;234
Response::with(())235
}237
pub async fn get_station(req: tide::Request<()>) -> tide::Result {238
let station_id = unwrap_result_or_throw!(req.param("id"), "no station id found!");239
let account =240
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");241
let sql = format!(242
r#"243
SELECT244
station.*,245
station_status.is_restricted,246
station_status.is_broken,247
station_status.is_no_track_info,248
station_status.is_hidden,249
station_status.is_icon,250
station_stats.playtime,251
CASE252
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}253
THEN false254
ELSE true255
END AS is_favorite256
FROM station257
LEFT JOIN favorite258
ON station.id = favorite.station_id259
LEFT JOIN station_status260
ON station.id = station_status.station_id261
LEFT JOIN station_stats262
ON station.id = station_stats.station_id263
AND station_stats.account_id = {account_id}264
WHERE station.id = {station_id}265
AND station_status.is_hidden IS NOT true266
"#,267
account_id = account.id,268
station_id = station_id,269
);270
let mut conn = req.sqlx_conn::<Postgres>().await;271
let result = sqlx::query_as::<_, model::StationDetail>(&sql)272
.fetch_optional(conn.acquire().await?)273
.await?;274
Response::with(result)275
}277
pub async fn get_countries(req: tide::Request<()>) -> tide::Result {278
let sql = r#"279
SELECT280
country281
FROM station282
WHERE country != ''283
GROUP BY country284
ORDER BY COUNT(*) DESC;285
"#286
.to_string();287
let mut conn = req.sqlx_conn::<Postgres>().await;288
let result = sqlx::query_as::<_, model::Value>(&sql)289
.fetch_all(conn.acquire().await?)290
.await?;291
Response::with(result)292
}294
pub async fn get_languages(req: tide::Request<()>) -> tide::Result {295
let sql = r#"296
SELECT297
UNNEST(languages) AS language298
FROM station299
GROUP BY UNNEST(languages)300
ORDER BY COUNT(*) DESC;301
"#302
.to_string();303
let mut conn = req.sqlx_conn::<Postgres>().await;304
let result = sqlx::query_as::<_, model::Value>(&sql)305
.fetch_all(conn.acquire().await?)306
.await?;307
Response::with(result)308
}310
pub async fn get_tags(req: tide::Request<()>) -> tide::Result {311
let sql = r#"312
SELECT313
UNNEST(tags) AS tag314
FROM station315
GROUP BY UNNEST(tags)316
ORDER BY COUNT(*) DESC317
LIMIT 100;318
"#319
.to_string();320
let mut conn = req.sqlx_conn::<Postgres>().await;321
let result = sqlx::query_as::<_, model::Value>(&sql)322
.fetch_all(conn.acquire().await?)323
.await?;324
Response::with(result)325
}327
pub async fn get_devices(req: tide::Request<()>) -> tide::Result {328
let account =329
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");330
let sql = format!(331
r#"332
SELECT333
device.*334
FROM device335
WHERE device.account_id = {account_id}336
"#,337
account_id = account.id,338
);339
let mut conn = req.sqlx_conn::<Postgres>().await;340
let result = sqlx::query_as::<_, model::Device>(&sql)341
.fetch_all(conn.acquire().await?)342
.await?;343
Response::with(result)344
}346
pub async fn update_account(mut req: tide::Request<()>) -> tide::Result {347
let updated_account = req.body_json::<model::Account>().await?;348
let account =349
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");350
let sql = format!(351
r#"352
UPDATE353
account354
SET355
name = '{name}',356
language = '{language}'357
WHERE account.id = {account_id}358
RETURNING *359
"#,360
account_id = account.id,361
name = updated_account.name.unwrap_or_default(),362
language = updated_account.language,363
);364
let mut conn = req.sqlx_conn::<Postgres>().await;365
let result = sqlx::query_as::<_, model::Account>(&sql)366
.fetch_one(conn.acquire().await?)367
.await?;368
Response::with(result)369
}