A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
1
use serde::Deserialize;3
use crate::models::Station;4
use crate::utils::{to_array, upgrade_to_https};6
#[derive(Debug, Deserialize)]7
pub struct StationAdapter {8
pub stationuuid: String,9
pub name: String,10
pub url: String,11
pub votes: i32,12
pub favicon: String,13
pub homepage: String,14
pub tags: String,15
pub countrycode: String,16
pub languagecodes: String,17
pub state: String,18
}20
impl Into<Station> for StationAdapter {21
fn into(self) -> Station {22
Station {23
id: 0,24
uuid: self.stationuuid,25
name: self.name,26
stream_url: upgrade_to_https(self.url),27
votes: self.votes,28
favicon: Some(self.favicon),29
homepage: Some(self.homepage),30
tags: to_array(self.tags),31
country: Some(self.countrycode),32
languages: to_array(self.languagecodes),33
state: Some(self.state),34
}35
}36
}
1
use serde::{Deserialize, Serialize};1
use serde::Deserialize;2
use std::fmt;4
use crate::adapter::StationAdapter;4
use crate::error::{Error, ErrorKind, Result};6
use crate::models::Station;5
use crate::rest;7
const API_URLS: [&str; 3] = [8
"https://de1.api.radio-browser.info",
10
"https://nl1.api.radio-browser.info",11
];14
#[derive(Debug, Default, Deserialize, Serialize)]13
#[derive(Debug, Default, Deserialize)]14
pub struct Search {15
pub name: String,16
pub page: Option<i64>,
30
pub struct RadioBrowserApi;32
impl RadioBrowserApi {34
pub async fn search(search: Search) -> Result<Vec<Station>> {33
pub async fn search(search: Search) -> Result<Vec<rest::Station>> {34
let uri = format!("/json/stations/search?{}", &search);35
let mut response = match RadioBrowserApi::fetch(&uri).await {36
Ok(response) => response,37
Err(err) => return Err(err),38
};39
match response.body_json::<Vec<rest::Station>>().await {40
Ok(data) => Ok(data),41
Err(err) => Err(Error::new(ErrorKind::Parse, &err.to_string())),42
}43
}45
pub async fn by_uuids(uuids: Vec<String>) -> Result<Vec<rest::Station>> {46
let uri = format!("/json/stations/byuuid?uuids={}", &uuids.join(","));47
let mut response = match RadioBrowserApi::fetch(&uri).await {48
Ok(response) => response,49
Err(err) => return Err(err),50
};51
match response.body_json::<Vec<rest::Station>>().await {52
Ok(data) => Ok(data),53
Err(err) => Err(Error::new(ErrorKind::Parse, &err.to_string())),54
}55
}57
async fn fetch(uri: &str) -> Result<surf::Response> {58
let mut successful_response = None;59
for api_url in API_URLS {37
let url = format!("{}/json/stations/search?{}", &api_url, &search,);60
let url = format!("{}{}", &api_url, &uri,);61
match surf::get(&url).await {62
Ok(response) => {63
successful_response = Some(response);
66
Err(err) => println!("{}", Error::new(ErrorKind::Fetch, &err.to_string())),67
}68
}46
let mut response = match successful_response {47
Some(response) => response,69
match successful_response {70
Some(response) => Ok(response),71
None => return Err(Error::new(ErrorKind::Fetch, "All request attempts failed!")),49
};50
let adapters = match response.body_json::<Vec<StationAdapter>>().await {51
Ok(adapters) => adapters,52
Err(err) => return Err(Error::new(ErrorKind::Parse, &err.to_string())),53
};54
let mut stations = vec![];55
for adapter in adapters {56
stations.push(adapter.into());72
}58
Ok(stations)73
}74
}
1
use serde::Serialize;3
use crate::model;4
use crate::utils::upgrade_to_https;6
#[derive(Debug, Serialize)]7
pub struct Station {8
pub name: String,9
pub stream_url: String,10
pub votes: i32,11
pub favicon: Option<String>,12
pub homepage: Option<String>,13
pub tags: Vec<String>,14
pub country: Option<String>,15
pub languages: Vec<String>,16
pub state: Option<String>,17
pub is_favorite: bool,18
}20
impl Into<Station> for model::Station {21
fn into(self) -> Station {22
Station {23
name: self.name,24
stream_url: upgrade_to_https(self.stream_url),25
votes: self.votes,26
favicon: self.favicon,27
homepage: self.homepage,28
tags: self.tags,29
country: self.country,30
languages: self.languages,31
state: self.state,32
is_favorite: false,33
}34
}35
}
8
pub enum ErrorKind {9
Identity,10
Arguments,11
Query,11
Fetch,12
Parse,13
}
4
use tide_compress::CompressMiddleware;5
use tide_diesel::DieselMiddleware;7
mod adapter;7
mod api;8
mod config;9
mod data;10
mod error;11
mod middleware;12
mod models;12
mod model;13
mod response;14
mod rest;15
mod schema;16
mod service;16
mod state;17
mod utils;19
use api::Search;
21
use error::ErrorKind;22
use middleware::{AuthMiddleware, CorsMiddleware};23
use response::Response;24
use state::State;24
use service::Service;26
#[async_std::main]27
async fn main() -> tide::Result<()> {28
let config = Config::from_file("./config.ron").expect("Unable to parse config!");30
let mut app = tide::with_state(State::new());30
let mut app = tide::new();32
/* bind database middleware */33
app.with(DieselMiddleware::new(&config.database.to_string()).unwrap());
44
/* handle prefetch */45
app.at("*")46
.options(|_: tide::Request<State>| async move { Ok(tide::Response::new(200)) });46
.options(|_: tide::Request<()>| async move { Ok(tide::Response::new(200)) });48
/* provide index */49
app.at("/").serve_file("www/index.html")?;
55
app.at("/app").serve_dir("app/")?;57
app.at("/api/search")58
.get(|req: tide::Request<State>| async move {59
let state = req.state();58
.get(|req: tide::Request<()>| async move {59
let search = match req.query::<Search>() {60
Ok(query) => query,61
Err(err) => return Response::throw(ErrorKind::Arguments, &err.to_string()),62
};64
let result = match state.service.search(search).await {65
Ok(result) => result,66
Err(err) => return Response::throw(ErrorKind::Fetch, &err.to_string()),67
};68
Response::with(result)63
match Service::search(search, req).await {64
Ok(data) => Response::with(data),65
Err(err) => Response::throw(ErrorKind::Fetch, &err.to_string()),66
}67
});69
app.at("/api/favorite")70
.get(|req: tide::Request<()>| async move {71
match Service::get_favorites(req).await {72
Ok(data) => Response::with(data),73
Err(err) => Response::throw(ErrorKind::Fetch, &err.to_string()),74
}75
});77
app.listen(&config.server.to_string()).await?;79
Ok(())80
}76
// /* get account */77
// app.at("/api/account").get(|req: tide::Request<State>| async move {78
// let account = match identify(&req).await {79
// Ok(model) => model,80
// Err(err) => return Response::throw(err),81
// };82
// Response::with(&account.inner)83
// });85
// /* create account */86
// app.at("/api/account").post(|req: tide::Request<State>| async move {87
// let mut conn = req.sqlx_conn::<Postgres>().await;88
// let account = Model::new(Account::default());89
// match sqlx::query(&account.into_insert("account"))90
// .execute(conn.acquire().await.unwrap())91
// .await92
// {93
// Ok(_) => Response::success(),94
// Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),95
// }96
// });98
// /* update account */99
// app.at("/api/account").put(|mut req: tide::Request<State>| async move {100
// let mut account = match identify(&req).await {101
// Ok(model) => model,102
// Err(err) => return Response::throw(err),103
// };104
// let inner = match req.body_json::<Account>().await {105
// Ok(inner) => inner,106
// Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),107
// };108
// account.inner = inner;109
// let mut conn = req.sqlx_conn::<Postgres>().await;110
// match sqlx::query(&account.into_update("account"))111
// .execute(conn.acquire().await.unwrap())112
// .await113
// {114
// Ok(_) => Response::success(),115
// Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),116
// }117
// });119
// /* get favorite */120
// app.at("/api/favorite").get(|req: tide::Request<State>| async move {121
// let state = req.state();122
// let account = match identify(&req).await {123
// Ok(model) => model,124
// Err(err) => return Response::throw(err),125
// };126
// let query = format!(127
// "128
// SELECT station_id FROM favorite129
// WHERE account_id = {}130
// ORDER BY created_at DESC131
// ",132
// &account.id,133
// );134
// let mut conn = req.sqlx_conn::<Postgres>().await;135
// let station_ids = match sqlx::query(&query)136
// .fetch_all(conn.acquire().await.unwrap())137
// .await138
// {139
// Ok(rows) => rows.iter().map(|row| row.get("station_id")).collect::<Vec<String>>(),140
// Err(err) => return Response::throw(Error::new(ErrorKind::Query, &err.to_string())),141
// };142
// let url = format!(143
// "{}/json/stations/byuuid?uuids={}",144
// &state.config.options.api_url,145
// &station_ids.join(","),146
// );147
// let mut response = match surf::get(&url).await {148
// Ok(response) => response,149
// Err(err) => return Response::throw(Error::new(ErrorKind::Fetch, &err.to_string())),150
// };151
// let adapters = match response.body_json::<Vec<StationAdapter>>().await {152
// Ok(adapters) => adapters,153
// Err(err) => return Response::throw(Error::new(ErrorKind::Parse, &err.to_string())),154
// };155
// let mut stations = vec![];156
// for station_id in station_ids {157
// for adapter in &adapters {158
// if adapter.stationuuid == station_id {159
// let mut station = Station::default();160
// station.is_favorite = true;161
// stations.push(adapter.clone().populate(station));162
// }163
// }164
// }165
// Response::with(&stations)166
// });168
// /* create favorite */169
// app.at("/api/favorite").post(|mut req: tide::Request<State>| async move {170
// let account = match identify(&req).await {171
// Ok(model) => model,172
// Err(err) => return Response::throw(err),173
// };174
// let id = match req.body_json::<String>().await {175
// Ok(inner) => inner,176
// Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),177
// };178
// let mut conn = req.sqlx_conn::<Postgres>().await;179
// let favorite = Model::new(Favorite::new(&id, account.id));180
// match sqlx::query(&favorite.into_insert("favorite"))181
// .execute(conn.acquire().await.unwrap())182
// .await183
// {184
// Ok(_) => Response::success(),185
// Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),186
// }187
// });189
// /* delete favorite */190
// app.at("/api/favorite").delete(|mut req: tide::Request<State>| async move {191
// let account = match identify(&req).await {192
// Ok(model) => model,193
// Err(err) => return Response::throw(err),194
// };195
// let id = match req.body_json::<String>().await {196
// Ok(inner) => inner,197
// Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),198
// };199
// let mut conn = req.sqlx_conn::<Postgres>().await;200
// match sqlx::query(&format!(201
// "202
// DELETE FROM favorite203
// WHERE account_id = {}204
// AND station_id = '{}'205
// ",206
// &account.id,207
// &id,208
// ))209
// .execute(conn.acquire().await.unwrap())210
// .await211
// {212
// Ok(_) => Response::success(),213
// Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),214
// }215
// });217
// /* search */218
// app.at("/api/search").get(|req: tide::Request<State>| async move {219
// let account = match identify(&req).await {220
// Ok(model) => model,221
// Err(err) => return Response::throw(err),222
// };223
// let inner = match req.query::<Search>() {224
// Ok(inner) => inner,225
// Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),226
// };227
// let state = req.state();228
// let url = format!(229
// "{}/json/stations/search?{}",230
// &state.config.options.api_url,231
// &inner.into_query(),232
// );233
// let mut response = match surf::get(&url).await {234
// Ok(response) => response,235
// Err(err) => return Response::throw(Error::new(ErrorKind::Fetch, &err.to_string())),236
// };237
// let adapters = match response.body_json::<Vec<StationAdapter>>().await {238
// Ok(adapters) => adapters,239
// Err(err) => return Response::throw(Error::new(ErrorKind::Parse, &err.to_string())),240
// };241
// let query = format!(242
// "243
// SELECT station_id244
// FROM favorite245
// WHERE account_id = {}246
// ",247
// &account.id,248
// );249
// let mut conn = req.sqlx_conn::<Postgres>().await;250
// let station_ids = match sqlx::query(&query)251
// .fetch_all(conn.acquire().await.unwrap())252
// .await253
// {254
// Ok(rows) => rows.iter().map(|row| row.get("station_id")).collect::<Vec<String>>(),255
// Err(err) => return Response::throw(Error::new(ErrorKind::Query, &err.to_string())),256
// };257
// let mut stations = vec![];258
// for adapter in &adapters {259
// let mut station = Station::default();260
// station.is_favorite = station_ids.contains(&adapter.stationuuid);261
// stations.push(adapter.clone().populate(station));262
// }263
// Response::with(&stations)264
// });266
// /* song */267
// app.at("/api/song").get(|mut req: tide::Request<State>| async move {268
// let _ = match identify(&req).await {269
// Ok(model) => model,270
// Err(err) => return Response::throw(err),271
// };272
// let inner = match req.body_json::<String>().await {273
// Ok(inner) => inner,274
// Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),275
// };276
// let mut response = match surf::get(&inner)277
// .header("icy-metadata", "1")278
// .await {279
// Ok(response) => response,280
// Err(err) => return Response::throw(Error::new(ErrorKind::Fetch, &err.to_string())),281
// };282
// let meta_int = match response.header("icy-metaint") {283
// Some(header) => header.as_str(),284
// None => return Response::throw(Error::new(ErrorKind::Arguments, "No request header 'icy-metaint' found!")),285
// };286
// let interval = match meta_int.parse::<usize>() {287
// Ok(value) => value * 2,288
// Err(err) => return Response::throw(Error::new(ErrorKind::Parse, &err.to_string())),289
// };290
// let mut count = 0;291
// let mut bytes = vec![];292
// let mut buf = [0; 10000];293
// let mut title = None;294
// loop {295
// let len = response.read(&mut buf).await.unwrap();296
// bytes.extend_from_slice(&buf);297
// if count + len > interval {298
// let metadata = String::from_utf8_lossy(&bytes);299
// for cap in Regex::new("StreamTitle='([^;]*)';").unwrap()300
// .captures_iter(&metadata)301
// {302
// title = Some(cap[1].to_string());303
// break;304
// }305
// break;306
// }307
// count += len;308
// }309
// Response::with_option(title)310
// });312
// /* get code */313
// app.at("/api/code").get(|req: tide::Request<State>| async move {314
// let account = match identify(&req).await {315
// Ok(model) => model,316
// Err(err) => return Response::throw(err),317
// };318
// let mut conn = req.sqlx_conn::<Postgres>().await;319
// match sqlx::query_as::<_, Code>(320
// &format!(321
// "322
// SELECT *, timestamp <= CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '1 minutes' as expired323
// FROM code324
// WHERE account_id = {}325
// ",326
// &account.id,327
// )328
// )329
// .fetch_one(conn.acquire().await.unwrap())330
// .await331
// {332
// Ok(code) => Response::with(code),333
// Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),334
// }335
// });337
// /* create code */338
// app.at("/api/code").post(|req: tide::Request<State>| async move {339
// let account = match identify(&req).await {340
// Ok(model) => model,341
// Err(err) => return Response::throw(err),342
// };343
// let mut conn = req.sqlx_conn::<Postgres>().await;344
// let code = Code::new();345
// match sqlx::query(346
// &format!(347
// "348
// INSERT INTO code349
// (code, account_id, timestamp, used)350
// VALUES351
// ('{}', '{}', CURRENT_TIMESTAMP, false)352
// ON CONFLICT353
// (account_id)354
// DO UPDATE355
// SET356
// code = excluded.code,357
// timestamp = excluded.timestamp,358
// used = excluded.used359
// ",360
// &code.code,361
// &account.id,362
// )363
// )364
// .execute(conn.acquire().await.unwrap())365
// .await366
// {367
// Ok(_) => Response::with(code),368
// Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),369
// }370
// });372
// /* update code */373
// app.at("/api/code").put(|req: tide::Request<State>| async move {374
// let _ = match identify(&req).await {375
// Ok(model) => model,376
// Err(err) => return Response::throw(err),377
// };378
// Response::success()379
// });381
// async fn identify(req: &tide::Request<State>) -> Result<Model<Account>, Error> {382
// let token = match req.header("verbal-token") {383
// Some(header) => header.as_str(),384
// None => return Err(Error::new(ErrorKind::Identity, "No request header 'verbal-token' provided!")),385
// };386
// let query = format!(387
// "388
// SELECT account.* FROM account389
// INNER JOIN device390
// ON device.account_id = account.id391
// WHERE device.token = '{}'392
// ",393
// &token,394
// );395
// let mut conn = req.sqlx_conn::<Postgres>().await;396
// let id = match sqlx::query(&query)397
// .fetch_one(conn.acquire().await.unwrap())398
// .await399
// {400
// Ok(row) => row.get("id"),401
// Err(_) => return Err(Error::new(ErrorKind::Identity, "No account found for provided header 'verbal-token'!")),402
// };403
// let inner = match sqlx::query_as::<_, Account>(&query)404
// .fetch_one(conn.acquire().await.unwrap())405
// .await406
// {407
// Ok(inner) => inner,408
// Err(_) => return Err(Error::new(ErrorKind::Identity, "No account found for provided header 'verbal-token'!")),409
// };410
// Ok(Model::from(id, inner))411
// }
2
use tide_diesel::DieselRequestExt;4
use crate::error::ErrorKind;5
use crate::models::*;5
use crate::model;6
use crate::response::Response;7
use crate::schema::account;8
use crate::schema::device;7
use crate::schema;9
pub struct AuthMiddleware {}
32
}33
};34
let conn = req.pg_conn().await?;36
let identity: Option<(Account, Device)> = account::table37
.inner_join(device::table)38
.filter(device::dsl::token.eq(token))35
let identity: Option<(model::Account, model::Device)> = schema::account::table36
.inner_join(schema::device::table)37
.filter(schema::device::dsl::token.eq(token))38
.first(&conn)39
.optional()?;40
if identity.is_none() {
1
use diesel::{Insertable, Queryable};3
use crate::schema::station;5
#[derive(Debug, Queryable)]6
pub struct Account {7
pub id: i32,8
pub username: Option<String>,9
pub language: String,10
pub is_playback_history: bool,11
}13
#[derive(Debug, Queryable)]14
pub struct Device {15
pub id: i32,16
pub token: String,17
pub account_id: i32,18
}20
#[derive(Debug, Clone, Queryable, Insertable)]21
#[table_name = "station"]22
pub struct Station {23
pub id: i32,24
pub uuid: String,25
pub name: String,26
pub stream_url: String,27
pub votes: i32,28
pub favicon: Option<String>,29
pub homepage: Option<String>,30
pub tags: Vec<String>,31
pub country: Option<String>,32
pub languages: Vec<String>,33
pub state: Option<String>,34
}36
#[derive(Debug, Queryable)]37
pub struct Like {38
pub id: i32,39
pub account_id: i32,40
pub station_id: String,41
}43
// use rand::{distributions::Alphanumeric, Rng};45
// #[derive(Debug, Deserialize, Serialize, FromRow)]46
// pub struct Code {47
// pub code: String,48
// pub used: bool,49
// pub expired: bool,50
// }52
// impl Code {53
// pub fn new() -> Self {54
// let code = rand::thread_rng()55
// .sample_iter(&Alphanumeric)56
// .take(6)57
// .map(char::from)58
// .map(|c| c.to_uppercase().to_string())59
// .collect::<String>();60
// Self { code, used: false, expired: false }61
// }62
// }
1
use diesel::Queryable;2
use serde::Serialize;4
#[derive(Debug, Serialize, Queryable)]5
pub struct Account {6
pub id: i32,7
pub username: Option<String>,8
pub language: String,9
pub is_playback_history: bool,10
}12
#[derive(Debug, Serialize, Queryable)]13
pub struct Device {14
pub id: i32,15
pub token: String,16
pub account_id: i32,17
}19
#[derive(Debug, Serialize, Queryable)]20
pub struct Station {21
pub id: i32,22
pub uuid: String,23
pub name: String,24
pub stream_url: String,25
pub votes: i32,26
pub favicon: Option<String>,27
pub homepage: Option<String>,28
pub tags: Vec<String>,29
pub country: Option<String>,30
pub languages: Vec<String>,31
pub state: Option<String>,32
}34
#[derive(Debug, Serialize, Queryable)]35
pub struct Favorite {36
pub id: i32,37
pub account_id: i32,38
pub station_id: i32,39
}41
// use rand::{distributions::Alphanumeric, Rng};43
// #[derive(Debug, Deserialize, Serialize, FromRow)]44
// pub struct Code {45
// pub code: String,46
// pub used: bool,47
// pub expired: bool,48
// }50
// impl Code {51
// pub fn new() -> Self {52
// let code = rand::thread_rng()53
// .sample_iter(&Alphanumeric)54
// .take(6)55
// .map(char::from)56
// .map(|c| c.to_uppercase().to_string())57
// .collect::<String>();58
// Self { code, used: false, expired: false }59
// }60
// }
9
}11
impl Response<(), ()> {12
pub fn success() -> Result<tide::Body, tide::Error> {13
tide::Body::from_json(&Self {14
ok: true,15
data: None,16
error: None,17
})18
}12
pub fn respond(body: Result<tide::Body, tide::Error>) -> tide::Result {13
Ok(tide::Response::builder(200).body(body.unwrap()).build())14
}
25
error: None,26
}))27
}35
pub fn with_option(data: Option<T>) -> Result<tide::Body, tide::Error> {36
tide::Body::from_json(&Self {37
ok: true,38
data,39
error: None,40
})41
}42
}44
impl<E> Response<(), E>45
where46
E: Serialize,47
{48
pub fn with_error(error: E) -> Result<tide::Body, tide::Error> {49
tide::Body::from_json(&Self {50
ok: false,51
data: None,52
error: Some(error),53
})54
}28
}30
impl Response<(), Error> {
1
use serde::Deserialize;3
use crate::data;4
use crate::utils::{to_array, upgrade_to_https};6
#[derive(Debug, Clone, Deserialize)]7
pub struct Station {8
pub stationuuid: String,9
pub name: String,10
pub url: String,11
pub votes: i32,12
pub favicon: String,13
pub homepage: String,14
pub tags: String,15
pub countrycode: String,16
pub languagecodes: String,17
pub state: String,18
}20
impl Into<data::Station> for Station {21
fn into(self) -> data::Station {22
data::Station {23
name: self.name,24
stream_url: upgrade_to_https(self.url),25
votes: self.votes,26
favicon: Some(self.favicon),27
homepage: Some(self.homepage),28
tags: to_array(self.tags),29
country: Some(self.countrycode),30
languages: to_array(self.languagecodes),31
state: Some(self.state),32
is_favorite: false,33
}34
}35
}
32
}34
table! {35
favorite (id) {35
like (id) {36
id -> Integer,37
account_id -> Integer,38
station_id -> Integer,38
station_id -> Text,39
}40
}42
joinable!(device -> account (account_id));43
joinable!(favorite -> account (account_id));44
joinable!(favorite -> station (station_id));43
joinable!(like -> account (account_id));46
allow_tables_to_appear_in_same_query!(account, device, favorite,);45
allow_tables_to_appear_in_same_query!(account, device, like,);
1
use diesel::prelude::*;2
use tide_diesel::DieselRequestExt;4
use crate::api::{RadioBrowserApi, Search};5
use crate::data;6
use crate::error::Result;3
use crate::models::Station;7
use crate::model;8
use crate::schema;5
#[derive(Clone)]10
pub struct Service {}12
impl Service {9
pub fn new() -> Self {10
Self {}13
pub async fn search(search: Search, req: tide::Request<()>) -> Result<Vec<data::Station>> {14
let conn = req.pg_conn().await.unwrap();15
let rest = match RadioBrowserApi::search(search).await {16
Ok(rest) => rest,17
Err(err) => return Err(err),18
};19
let (account, _) = req.ext::<(model::Account, model::Device)>().unwrap();20
let likes = schema::like::dsl::like21
.filter(schema::like::account_id.eq(account.id))22
.load::<model::Like>(&conn)23
.unwrap();24
let data = rest25
.iter()26
.cloned()27
.map(|item| {28
let mut data: data::Station = item.clone().into();29
data.is_favorite = likes.iter().any(|like| like.station_id == item.stationuuid);30
data31
})32
.collect::<Vec<data::Station>>();33
Ok(data)34
}13
pub async fn search(&self, search: Search) -> Result<Vec<Station>> {14
RadioBrowserApi::search(search).await36
pub async fn get_favorites(req: tide::Request<()>) -> Result<Vec<data::Station>> {37
let conn = req.pg_conn().await.unwrap();38
let (account, _) = req.ext::<(model::Account, model::Device)>().unwrap();39
let likes = schema::like::dsl::like40
.filter(schema::like::account_id.eq(account.id))41
.load::<model::Like>(&conn)42
.unwrap();43
let uuids = likes44
.iter()45
.map(|like| &like.station_id)46
.cloned()47
.collect::<Vec<String>>();48
let rest = match RadioBrowserApi::by_uuids(uuids).await {49
Ok(rest) => rest,50
Err(err) => return Err(err),51
};52
let data = rest53
.iter()54
.cloned()55
.map(|item| {56
let mut data: data::Station = item.clone().into();57
data.is_favorite = true;58
data59
})60
.collect::<Vec<data::Station>>();61
Ok(data)62
}63
}
1
use crate::service::Service;3
#[derive(Clone)]4
pub struct State {5
pub service: Service,6
}8
impl State {9
pub fn new() -> Self {10
Self {11
service: Service::new(),12
}13
}14
}
4
use diesel::pg::PgConnection;5
use diesel::prelude::*;7
mod adapter;7
mod api;8
mod data;9
mod error;10
mod models;10
mod model;11
mod rest;12
mod schema;13
mod utils;15
use api::{RadioBrowserApi, Search};15
use models::*;16
use model::*;17
use schema::account::dsl::*;19
#[async_std::main]