A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
9
rand = "*"10
surf = "*"11
regex = "*"12
tide-sqlx = "*"12
diesel = { version = "*", features = ["postgres"] }13
serde_json = "*"14
tide-diesel = "*"15
tide-compress = "*"16
serde = { version = "*", features = ["derive"] }17
async-std = { version = "*", features = ["attributes", "tokio1"] }
22
path = "src/main.rs"24
[[bin]]24
name = "import"25
path = "src/import.rs"27
[[bin]]25
name = "test"26
path = "src/test.rs"
1
[print_schema]2
file = "src/schema.rs"
1
mod station_adapter;1
use serde::Deserialize;3
pub use station_adapter::StationAdapter;3
use crate::utils::{to_array, upgrade_to_https};4
use crate::models::Station;5
pub trait Adapter<T> {6
fn populate(self, target: T) -> T;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};2
use regex::Regex;4
use crate::common::Station;5
use crate::adapter::Adapter;7
#[derive(Debug, Deserialize, Clone)]8
pub struct StationAdapter {9
pub stationuuid: String,10
pub name: String,11
pub url: String,12
pub votes: i64,13
pub favicon: String,14
pub homepage: String,15
pub tags: String,16
pub clicktrend: i64,17
pub clickcount: i64,18
pub countrycode: String,19
pub languagecodes: String,20
pub state: String,21
}23
impl Adapter<Station> for StationAdapter {24
fn populate(self, mut target: Station) -> Station {25
target.id = self.stationuuid;26
target.name = self.name;27
target.stream_url = upgrade_to_https(self.url);28
target.votes = self.votes;29
target.favicon = self.favicon;30
target.homepage = self.homepage;31
target.tags = to_array(self.tags);32
target.click_trend = self.clicktrend;33
target.click_count = self.clickcount;34
target.country = self.countrycode;35
target.languages = to_array(self.languagecodes);36
target.state = self.state;37
target38
}39
}41
fn to_array(value: String) -> Vec<String> {42
value.split(",")43
.map(str::to_string)44
.filter(|tag| tag.trim().len() > 0)45
.collect::<Vec<String>>()46
}48
fn upgrade_to_https(url: String) -> String {49
if Regex::new("^http://")50
.unwrap()51
.is_match(&url)52
{53
/* TODO: include in config struct */54
return format!("https://api.radio.typable.dev/pass?redirect={}", &url);55
}56
url57
}
1
use std::fmt;2
use serde::{Deserialize, Serialize};4
use crate::error::{Result, Error, ErrorKind};5
use crate::models::Station;6
use crate::adapter::StationAdapter;8
const API_URLS: [&str; 3] = [9
"https://de1.api.radio-browser.info",10
"https://fr1.api.radio-browser.info",11
"https://nl1.api.radio-browser.info",12
];14
#[derive(Debug, Default, Deserialize, Serialize)]15
pub struct Search {16
pub name: String,17
pub page: Option<i64>,18
}20
impl fmt::Display for Search {21
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {22
write!(23
f,24
"name={}&offset={}&limit=10&order=votes&reverse=true&hidebroken=true",25
&self.name,26
&self.page.unwrap_or(0) * 10,27
)28
}29
}31
pub struct RadioBrowserApi;33
impl RadioBrowserApi {35
pub async fn search(search: Search) -> Result<Vec<Station>> {36
let mut successful_response = None;37
for api_url in API_URLS {38
let url = format!(39
"{}/json/stations/search?{}",40
&api_url,41
&search,42
);43
match surf::get(&url).await {44
Ok(response) => {45
successful_response = Some(response);46
break;47
},48
Err(err) => println!("{}", Error::new(ErrorKind::Fetch, &err.to_string())),49
}50
}51
let mut response = match successful_response {52
Some(response) => response,53
None => return Err(Error::new(ErrorKind::Fetch, "All request attempts failed!")),54
};55
let adapters = match response.body_json::<Vec<StationAdapter>>().await {56
Ok(adapters) => adapters,57
Err(err) => return Err(Error::new(ErrorKind::Parse, &err.to_string())),58
};59
let mut stations = vec![];60
for adapter in adapters {61
stations.push(adapter.into());62
}63
Ok(stations)64
}66
}
1
pub mod api;
1
use serde::{Deserialize, Serialize};3
use crate::common::Station;4
use crate::error::{Result, Error, ErrorKind};5
use crate::adapter::{Adapter, StationAdapter};7
const API_URLS: [&str; 3] = [8
"https://de1.api.radio-browser.info",9
"https://fr1.api.radio-browser.info",10
"https://nl1.api.radio-browser.info",11
];13
#[derive(Debug, Default, Deserialize, Serialize)]14
pub struct Search {15
pub name: String,16
pub page: Option<i64>,17
}19
impl Search {21
pub fn into_query(&self) -> String {22
format!(23
"name={}&offset={}&limit=10&order=votes&reverse=true&hidebroken=true",24
&self.name,25
&self.page.unwrap_or(0) * 10,26
)27
}29
}31
pub struct RadioBrowserApi;33
impl RadioBrowserApi {35
pub async fn search(search: Search) -> Result<Vec<Station>> {36
let mut successful_response = None;37
for api_url in API_URLS {38
let url = format!(39
"{}/json/stations/search?{}",40
&api_url,41
&search.into_query(),42
);43
match surf::get(&url).await {44
Ok(response) => {45
successful_response = Some(response);46
break;47
},48
Err(err) => println!("{}", Error::new(ErrorKind::Fetch, &err.to_string())),49
}50
}51
let mut response = match successful_response {52
Some(response) => response,53
None => return Err(Error::new(ErrorKind::Fetch, "All request attempts failed!")),54
};55
let adapters = match response.body_json::<Vec<StationAdapter>>().await {56
Ok(adapters) => adapters,57
Err(err) => return Err(Error::new(ErrorKind::Parse, &err.to_string())),58
};59
let mut stations = vec![];60
for adapter in &adapters {61
stations.push(62
adapter.clone().populate(Station::default())63
);64
}65
Ok(stations)66
}68
}
1
mod station;3
pub use station::Station;
1
use serde::{Deserialize, Serialize};3
#[derive(Debug, Default, Deserialize, Serialize)]4
pub struct Station {5
pub id: String,6
pub name: String,7
pub stream_url: String,8
pub votes: i64,9
pub favicon: String,10
pub homepage: String,11
pub tags: Vec<String>,12
pub click_trend: i64,13
pub click_count: i64,14
pub country: String,15
pub languages: Vec<String>,16
pub state: String,17
}
1
use std::fs;2
use serde::{Deserialize};2
use std::fmt;3
use serde::Deserialize;5
#[derive(Debug, Clone, Deserialize)]6
pub struct Server {
8
pub port: i32,9
}10
impl ToString for Server {11
fn to_string(&self) -> String {12
format!(11
impl fmt::Display for Server {12
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {13
write!(14
f,15
"{}:{}",16
self.hostname,17
self.port,
28
pub database: String,29
}29
impl ToString for Database {30
fn to_string(&self) -> String {31
format!(32
"postgressql://{}:{}@{}:{}/{}?sslmode=disable",31
impl fmt::Display for Database {32
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {33
write!(34
f,35
"postgres://{}:{}@{}:{}/{}?sslmode=disable",36
self.username,37
self.password,38
self.hostname,
45
#[derive(Debug, Clone, Deserialize)]46
pub struct Options {47
pub origin: String,45
pub api_url: String,48
}50
#[derive(Debug, Clone, Deserialize)]
1
use surf;2
use sqlx::postgres::PgPool;4
mod common;5
mod adapter;6
mod models;8
use adapter::Adapter;9
use models::{Station, StationAdapter};11
trait IntoInsert {12
fn into_insert(&self) -> String;13
}15
impl IntoInsert for Station {16
fn into_insert(&self) -> String {17
format!(18
"19
INSERT INTO station20
(21
created_at,22
updated_at,23
name,24
stream_url,25
votes,26
favicon,27
homepage,28
tags,29
country,30
languages,31
state32
)33
VALUES34
(35
CURRENT_TIMESTAMP,36
CURRENT_TIMESTAMP,37
'{}',38
'{}',39
{},40
'{}',41
'{}',42
'{{{}}}',43
'{}',44
'{{{}}}',45
'{}'46
);47
",48
escape_sql(&self.name),49
&self.stream_url,50
&self.votes,51
&self.favicon,52
escape_sql(&self.homepage),53
&self.tags54
.iter()55
.map(|tag| escape_sql(&tag))56
.map(|tag| format!("\"{}\"", &tag))57
.collect::<Vec<String>>()58
.join(","),59
escape_sql(&self.country),60
&self.languages.join(","),61
escape_sql(&self.state),62
)63
}64
}66
fn escape_sql(text: &str) -> String {67
text.replace("'", "''")68
.replace("\"", "\\\"")69
}71
#[async_std::main]72
async fn main() {73
let limit = 500;74
let offset = 3 * limit;75
let url = format!("https://de1.api.radio-browser.info/json/stations?limit={}&offset={}&hidebroken=true&order=name", limit, offset);76
let mut response = match surf::get(&url).await {77
Ok(response) => response,78
Err(err) => panic!("{}", &err.to_string()),79
};80
let adapters = match response.body_json::<Vec<StationAdapter>>().await {81
Ok(adapters) => adapters,82
Err(err) => panic!("{}", &err.to_string()),83
};84
let pool = match PgPool::connect("postgres://typable:De24Si98@192.168.2.3:9748/verbal?sslmode=disable").await {85
Ok(pool) => pool,86
Err(err) => panic!("{}", &err.to_string()),87
};88
let mut transaction = match pool.begin().await {89
Ok(transaction) => transaction,90
Err(err) => panic!("{}", &err.to_string()),91
};92
for adapter in &adapters {93
let station = adapter.clone().populate(Station::default());94
match sqlx::query(&station.into_insert())95
.execute(&mut *transaction)96
.await97
{98
Ok(_) => (),99
Err(err) => panic!("{}", &err.to_string()),100
}101
}102
match transaction.commit().await {103
Ok(_) => println!("DONE"),104
Err(err) => panic!("{}", &err.to_string()),105
}106
}
1
use std::fmt::Display;2
use serde::Serialize;4
mod config;6
pub mod model;7
pub mod middleware;9
pub use config::Config;11
pub struct Utils {}13
impl Utils {14
pub fn null<T>(value: &Option<T>) -> String where T: Display {15
match value {16
Some(value) => format!("'{}'", &value),17
None => "NULL".to_string(),18
}19
}20
}22
#[derive(Debug, Clone)]23
pub struct State {24
pub config: Config,25
}27
impl State {28
pub fn new(config: Config) -> Self {29
Self { config }30
}31
}33
#[derive(Debug, Serialize)]34
pub struct Response<T, E> {35
pub ok: bool,36
pub data: Option<T>,37
pub error: Option<E>,38
}40
impl Response<(), ()> {41
pub fn success() -> Result<tide::Body, tide::Error> {42
tide::Body::from_json(&Self { ok: true, data: None, error: None })43
}44
}46
impl<T> Response<T, ()> where T: Serialize {47
pub fn with(data: T) -> Result<tide::Body, tide::Error> {48
tide::Body::from_json(&Self { ok: true, data: Some(data), error: None })49
}50
pub fn with_option(data: Option<T>) -> Result<tide::Body, tide::Error> {51
tide::Body::from_json(&Self { ok: true, data, error: None })52
}53
}56
impl<E> Response<(), E> where E: Serialize {57
pub fn throw(error: E) -> Result<tide::Body, tide::Error> {58
tide::Body::from_json(&Self { ok: false, data: None, error: Some(error) })59
}60
}
1
use sqlx::prelude::*;2
use sqlx::postgres::Postgres;3
use tide_sqlx::SQLxMiddleware;4
use tide_sqlx::SQLxRequestExt;5
use regex::Regex;6
use async_std::io::ReadExt;7
use tide_compress::CompressMiddleware;1
#[macro_use]2
extern crate diesel;9
use verbal::Config;10
use verbal::model::Model;11
use verbal::middleware::CorsMiddleware;12
use verbal::{State, Response};4
use diesel::prelude::*;5
use tide_diesel::DieselMiddleware;6
use tide_diesel::DieselRequestExt;7
use tide_compress::CompressMiddleware;14
mod common;9
mod utils;10
mod error;16
mod adapter;11
mod config;12
mod schema;13
mod models;14
mod adapter;15
mod response;16
mod middleware;19
use error::{Error, ErrorKind};20
use adapter::Adapter;21
use models::{Account, Favorite, Search, Code, Station, StationAdapter};18
use config::Config;19
use models::*;20
use schema::account::dsl::account;21
use response::Response;22
use middleware::CorsMiddleware;24
#[async_std::main]25
async fn main() -> tide::Result<()> {
27
let config = Config::from_file("./config.ron")28
.expect("Unable to parse config!");29
let mut app = tide::with_state(State::new(config.clone()));30
let mut app = tide::new();32
/* bind database middleware */32
app.with(SQLxMiddleware::<Postgres>::new(&config.database.to_string()).await?);33
app.with(DieselMiddleware::new(&config.database.to_string()).unwrap());35
/* bind cors middleware */36
app.with(CorsMiddleware::new(&config.options.origin));
39
app.with(CompressMiddleware::new());41
/* handle prefetch */41
app.at("*").options(|_: tide::Request<State>| async move {42
app.at("*").options(|_: tide::Request<()>| async move {43
Ok(tide::Response::new(200))44
});
52
/* provide app */53
app.at("/app").serve_dir("app/")?;54
/* get account */55
app.at("/api/account").get(|req: tide::Request<State>| async move {56
let account = match identify(&req).await {57
Ok(model) => model,58
Err(err) => return Response::throw(err),59
};60
Response::with(&account.inner)55
app.at("/api").get(|req: tide::Request<()>| async move {56
let conn = req.pg_conn().await?;57
let results = account.load::<Account>(&conn)?;58
Response::with(results)59
});63
/* create account */64
app.at("/api/account").post(|req: tide::Request<State>| async move {65
let mut conn = req.sqlx_conn::<Postgres>().await;66
let account = Model::new(Account::default());67
match sqlx::query(&account.into_insert("account"))68
.execute(conn.acquire().await.unwrap())69
.await70
{71
Ok(_) => Response::success(),72
Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),73
}74
});61
app.listen(&config.server.to_string()).await?;76
/* update account */77
app.at("/api/account").put(|mut req: tide::Request<State>| async move {78
let mut account = match identify(&req).await {79
Ok(model) => model,80
Err(err) => return Response::throw(err),81
};82
let inner = match req.body_json::<Account>().await {83
Ok(inner) => inner,84
Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),85
};86
account.inner = inner;87
let mut conn = req.sqlx_conn::<Postgres>().await;88
match sqlx::query(&account.into_update("account"))89
.execute(conn.acquire().await.unwrap())90
.await91
{92
Ok(_) => Response::success(),93
Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),94
}95
});63
Ok(())97
/* get favorite */98
app.at("/api/favorite").get(|req: tide::Request<State>| async move {99
let state = req.state();100
let account = match identify(&req).await {101
Ok(model) => model,102
Err(err) => return Response::throw(err),103
};104
let query = format!(105
"106
SELECT station_id FROM favorite107
WHERE account_id = {}108
ORDER BY created_at DESC109
",110
&account.id,111
);112
let mut conn = req.sqlx_conn::<Postgres>().await;113
let station_ids = match sqlx::query(&query)114
.fetch_all(conn.acquire().await.unwrap())115
.await116
{117
Ok(rows) => rows.iter().map(|row| row.get("station_id")).collect::<Vec<String>>(),118
Err(err) => return Response::throw(Error::new(ErrorKind::Query, &err.to_string())),119
};120
let url = format!(121
"{}/json/stations/byuuid?uuids={}",122
&state.config.options.api_url,123
&station_ids.join(","),124
);125
let mut response = match surf::get(&url).await {126
Ok(response) => response,127
Err(err) => return Response::throw(Error::new(ErrorKind::Fetch, &err.to_string())),128
};129
let adapters = match response.body_json::<Vec<StationAdapter>>().await {130
Ok(adapters) => adapters,131
Err(err) => return Response::throw(Error::new(ErrorKind::Parse, &err.to_string())),132
};133
let mut stations = vec![];134
for station_id in station_ids {135
for adapter in &adapters {136
if adapter.stationuuid == station_id {137
let mut station = Station::default();138
station.is_favorite = true;139
stations.push(adapter.clone().populate(station));140
}141
}142
}143
Response::with(&stations)144
});65
}146
/* create favorite */147
app.at("/api/favorite").post(|mut req: tide::Request<State>| async move {148
let account = match identify(&req).await {149
Ok(model) => model,150
Err(err) => return Response::throw(err),151
};152
let id = match req.body_json::<String>().await {153
Ok(inner) => inner,154
Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),155
};156
let mut conn = req.sqlx_conn::<Postgres>().await;157
let favorite = Model::new(Favorite::new(&id, account.id));158
match sqlx::query(&favorite.into_insert("favorite"))159
.execute(conn.acquire().await.unwrap())160
.await161
{162
Ok(_) => Response::success(),163
Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),164
}165
});67
// /* get account */68
// app.at("/api/account").get(|req: tide::Request<State>| async move {69
// let account = match identify(&req).await {70
// Ok(model) => model,71
// Err(err) => return Response::throw(err),72
// };73
// Response::with(&account.inner)74
// });167
/* delete favorite */168
app.at("/api/favorite").delete(|mut req: tide::Request<State>| async move {169
let account = match identify(&req).await {170
Ok(model) => model,171
Err(err) => return Response::throw(err),172
};173
let id = match req.body_json::<String>().await {174
Ok(inner) => inner,175
Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),176
};177
let mut conn = req.sqlx_conn::<Postgres>().await;178
match sqlx::query(&format!(179
"180
DELETE FROM favorite181
WHERE account_id = {}182
AND station_id = '{}'183
",184
&account.id,185
&id,186
))187
.execute(conn.acquire().await.unwrap())188
.await189
{190
Ok(_) => Response::success(),191
Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),192
}193
});76
// /* create account */77
// app.at("/api/account").post(|req: tide::Request<State>| async move {78
// let mut conn = req.sqlx_conn::<Postgres>().await;79
// let account = Model::new(Account::default());80
// match sqlx::query(&account.into_insert("account"))81
// .execute(conn.acquire().await.unwrap())82
// .await83
// {84
// Ok(_) => Response::success(),85
// Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),86
// }87
// });195
/* search */196
app.at("/api/search").get(|req: tide::Request<State>| async move {197
let account = match identify(&req).await {198
Ok(model) => model,199
Err(err) => return Response::throw(err),200
};201
let inner = match req.query::<Search>() {202
Ok(inner) => inner,203
Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),204
};205
let state = req.state();206
let url = format!(207
"{}/json/stations/search?{}",208
&state.config.options.api_url,209
&inner.into_query(),210
);211
let mut response = match surf::get(&url).await {212
Ok(response) => response,213
Err(err) => return Response::throw(Error::new(ErrorKind::Fetch, &err.to_string())),214
};215
let adapters = match response.body_json::<Vec<StationAdapter>>().await {216
Ok(adapters) => adapters,217
Err(err) => return Response::throw(Error::new(ErrorKind::Parse, &err.to_string())),218
};219
let query = format!(220
"221
SELECT station_id222
FROM favorite223
WHERE account_id = {}224
",225
&account.id,226
);227
let mut conn = req.sqlx_conn::<Postgres>().await;228
let station_ids = match sqlx::query(&query)229
.fetch_all(conn.acquire().await.unwrap())230
.await231
{232
Ok(rows) => rows.iter().map(|row| row.get("station_id")).collect::<Vec<String>>(),233
Err(err) => return Response::throw(Error::new(ErrorKind::Query, &err.to_string())),234
};235
let mut stations = vec![];236
for adapter in &adapters {237
let mut station = Station::default();238
station.is_favorite = station_ids.contains(&adapter.stationuuid);239
stations.push(adapter.clone().populate(station));240
}241
Response::with(&stations)242
});89
// /* update account */90
// app.at("/api/account").put(|mut req: tide::Request<State>| async move {91
// let mut account = match identify(&req).await {92
// Ok(model) => model,93
// Err(err) => return Response::throw(err),94
// };95
// let inner = match req.body_json::<Account>().await {96
// Ok(inner) => inner,97
// Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),98
// };99
// account.inner = inner;100
// let mut conn = req.sqlx_conn::<Postgres>().await;101
// match sqlx::query(&account.into_update("account"))102
// .execute(conn.acquire().await.unwrap())103
// .await104
// {105
// Ok(_) => Response::success(),106
// Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),107
// }108
// });244
/* song */245
app.at("/api/song").get(|mut req: tide::Request<State>| async move {246
let _ = match identify(&req).await {247
Ok(model) => model,248
Err(err) => return Response::throw(err),249
};250
let inner = match req.body_json::<String>().await {251
Ok(inner) => inner,252
Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),253
};254
let mut response = match surf::get(&inner)255
.header("icy-metadata", "1")256
.await {257
Ok(response) => response,258
Err(err) => return Response::throw(Error::new(ErrorKind::Fetch, &err.to_string())),259
};260
let meta_int = match response.header("icy-metaint") {261
Some(header) => header.as_str(),262
None => return Response::throw(Error::new(ErrorKind::Arguments, "No request header 'icy-metaint' found!")),263
};264
let interval = match meta_int.parse::<usize>() {265
Ok(value) => value * 2,266
Err(err) => return Response::throw(Error::new(ErrorKind::Parse, &err.to_string())),267
};268
let mut count = 0;269
let mut bytes = vec![];270
let mut buf = [0; 10000];271
let mut title = None;272
loop {273
let len = response.read(&mut buf).await.unwrap();274
bytes.extend_from_slice(&buf);275
if count + len > interval {276
let metadata = String::from_utf8_lossy(&bytes);277
for cap in Regex::new("StreamTitle='([^;]*)';").unwrap()278
.captures_iter(&metadata)279
{280
title = Some(cap[1].to_string());281
break;282
}283
break;284
}285
count += len;286
}287
Response::with_option(title)288
});110
// /* get favorite */111
// app.at("/api/favorite").get(|req: tide::Request<State>| async move {112
// let state = req.state();113
// let account = match identify(&req).await {114
// Ok(model) => model,115
// Err(err) => return Response::throw(err),116
// };117
// let query = format!(118
// "119
// SELECT station_id FROM favorite120
// WHERE account_id = {}121
// ORDER BY created_at DESC122
// ",123
// &account.id,124
// );125
// let mut conn = req.sqlx_conn::<Postgres>().await;126
// let station_ids = match sqlx::query(&query)127
// .fetch_all(conn.acquire().await.unwrap())128
// .await129
// {130
// Ok(rows) => rows.iter().map(|row| row.get("station_id")).collect::<Vec<String>>(),131
// Err(err) => return Response::throw(Error::new(ErrorKind::Query, &err.to_string())),132
// };133
// let url = format!(134
// "{}/json/stations/byuuid?uuids={}",135
// &state.config.options.api_url,136
// &station_ids.join(","),137
// );138
// let mut response = match surf::get(&url).await {139
// Ok(response) => response,140
// Err(err) => return Response::throw(Error::new(ErrorKind::Fetch, &err.to_string())),141
// };142
// let adapters = match response.body_json::<Vec<StationAdapter>>().await {143
// Ok(adapters) => adapters,144
// Err(err) => return Response::throw(Error::new(ErrorKind::Parse, &err.to_string())),145
// };146
// let mut stations = vec![];147
// for station_id in station_ids {148
// for adapter in &adapters {149
// if adapter.stationuuid == station_id {150
// let mut station = Station::default();151
// station.is_favorite = true;152
// stations.push(adapter.clone().populate(station));153
// }154
// }155
// }156
// Response::with(&stations)157
// });290
/* get code */291
app.at("/api/code").get(|req: tide::Request<State>| async move {292
let account = match identify(&req).await {293
Ok(model) => model,294
Err(err) => return Response::throw(err),295
};296
let mut conn = req.sqlx_conn::<Postgres>().await;297
match sqlx::query_as::<_, Code>(298
&format!(299
"300
SELECT *, timestamp <= CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '1 minutes' as expired301
FROM code302
WHERE account_id = {}303
",304
&account.id,305
)306
)307
.fetch_one(conn.acquire().await.unwrap())308
.await309
{310
Ok(code) => Response::with(code),311
Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),312
}313
});159
// /* create favorite */160
// app.at("/api/favorite").post(|mut req: tide::Request<State>| async move {161
// let account = match identify(&req).await {162
// Ok(model) => model,163
// Err(err) => return Response::throw(err),164
// };165
// let id = match req.body_json::<String>().await {166
// Ok(inner) => inner,167
// Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),168
// };169
// let mut conn = req.sqlx_conn::<Postgres>().await;170
// let favorite = Model::new(Favorite::new(&id, account.id));171
// match sqlx::query(&favorite.into_insert("favorite"))172
// .execute(conn.acquire().await.unwrap())173
// .await174
// {175
// Ok(_) => Response::success(),176
// Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),177
// }178
// });315
/* create code */316
app.at("/api/code").post(|req: tide::Request<State>| async move {317
let account = match identify(&req).await {318
Ok(model) => model,319
Err(err) => return Response::throw(err),320
};321
let mut conn = req.sqlx_conn::<Postgres>().await;322
let code = Code::new();323
match sqlx::query(324
&format!(325
"326
INSERT INTO code327
(code, account_id, timestamp, used)328
VALUES329
('{}', '{}', CURRENT_TIMESTAMP, false)330
ON CONFLICT331
(account_id)332
DO UPDATE333
SET334
code = excluded.code,335
timestamp = excluded.timestamp,336
used = excluded.used337
",338
&code.code,339
&account.id,340
)341
)342
.execute(conn.acquire().await.unwrap())343
.await344
{345
Ok(_) => Response::with(code),346
Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),347
}348
});180
// /* delete favorite */181
// app.at("/api/favorite").delete(|mut req: tide::Request<State>| async move {182
// let account = match identify(&req).await {183
// Ok(model) => model,184
// Err(err) => return Response::throw(err),185
// };186
// let id = match req.body_json::<String>().await {187
// Ok(inner) => inner,188
// Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),189
// };190
// let mut conn = req.sqlx_conn::<Postgres>().await;191
// match sqlx::query(&format!(192
// "193
// DELETE FROM favorite194
// WHERE account_id = {}195
// AND station_id = '{}'196
// ",197
// &account.id,198
// &id,199
// ))200
// .execute(conn.acquire().await.unwrap())201
// .await202
// {203
// Ok(_) => Response::success(),204
// Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),205
// }206
// });350
/* update code */351
app.at("/api/code").put(|req: tide::Request<State>| async move {352
let _ = match identify(&req).await {353
Ok(model) => model,354
Err(err) => return Response::throw(err),355
};356
Response::success()357
});208
// /* search */209
// app.at("/api/search").get(|req: tide::Request<State>| async move {210
// let account = match identify(&req).await {211
// Ok(model) => model,212
// Err(err) => return Response::throw(err),213
// };214
// let inner = match req.query::<Search>() {215
// Ok(inner) => inner,216
// Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),217
// };218
// let state = req.state();219
// let url = format!(220
// "{}/json/stations/search?{}",221
// &state.config.options.api_url,222
// &inner.into_query(),223
// );224
// let mut response = match surf::get(&url).await {225
// Ok(response) => response,226
// Err(err) => return Response::throw(Error::new(ErrorKind::Fetch, &err.to_string())),227
// };228
// let adapters = match response.body_json::<Vec<StationAdapter>>().await {229
// Ok(adapters) => adapters,230
// Err(err) => return Response::throw(Error::new(ErrorKind::Parse, &err.to_string())),231
// };232
// let query = format!(233
// "234
// SELECT station_id235
// FROM favorite236
// WHERE account_id = {}237
// ",238
// &account.id,239
// );240
// let mut conn = req.sqlx_conn::<Postgres>().await;241
// let station_ids = match sqlx::query(&query)242
// .fetch_all(conn.acquire().await.unwrap())243
// .await244
// {245
// Ok(rows) => rows.iter().map(|row| row.get("station_id")).collect::<Vec<String>>(),246
// Err(err) => return Response::throw(Error::new(ErrorKind::Query, &err.to_string())),247
// };248
// let mut stations = vec![];249
// for adapter in &adapters {250
// let mut station = Station::default();251
// station.is_favorite = station_ids.contains(&adapter.stationuuid);252
// stations.push(adapter.clone().populate(station));253
// }254
// Response::with(&stations)255
// });359
app.listen(&config.server.to_string()).await?;257
// /* song */258
// app.at("/api/song").get(|mut req: tide::Request<State>| async move {259
// let _ = match identify(&req).await {260
// Ok(model) => model,261
// Err(err) => return Response::throw(err),262
// };263
// let inner = match req.body_json::<String>().await {264
// Ok(inner) => inner,265
// Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),266
// };267
// let mut response = match surf::get(&inner)268
// .header("icy-metadata", "1")269
// .await {270
// Ok(response) => response,271
// Err(err) => return Response::throw(Error::new(ErrorKind::Fetch, &err.to_string())),272
// };273
// let meta_int = match response.header("icy-metaint") {274
// Some(header) => header.as_str(),275
// None => return Response::throw(Error::new(ErrorKind::Arguments, "No request header 'icy-metaint' found!")),276
// };277
// let interval = match meta_int.parse::<usize>() {278
// Ok(value) => value * 2,279
// Err(err) => return Response::throw(Error::new(ErrorKind::Parse, &err.to_string())),280
// };281
// let mut count = 0;282
// let mut bytes = vec![];283
// let mut buf = [0; 10000];284
// let mut title = None;285
// loop {286
// let len = response.read(&mut buf).await.unwrap();287
// bytes.extend_from_slice(&buf);288
// if count + len > interval {289
// let metadata = String::from_utf8_lossy(&bytes);290
// for cap in Regex::new("StreamTitle='([^;]*)';").unwrap()291
// .captures_iter(&metadata)292
// {293
// title = Some(cap[1].to_string());294
// break;295
// }296
// break;297
// }298
// count += len;299
// }300
// Response::with_option(title)301
// });361
Ok(())303
// /* get code */304
// app.at("/api/code").get(|req: tide::Request<State>| async move {305
// let account = match identify(&req).await {306
// Ok(model) => model,307
// Err(err) => return Response::throw(err),308
// };309
// let mut conn = req.sqlx_conn::<Postgres>().await;310
// match sqlx::query_as::<_, Code>(311
// &format!(312
// "313
// SELECT *, timestamp <= CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '1 minutes' as expired314
// FROM code315
// WHERE account_id = {}316
// ",317
// &account.id,318
// )319
// )320
// .fetch_one(conn.acquire().await.unwrap())321
// .await322
// {323
// Ok(code) => Response::with(code),324
// Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),325
// }326
// });363
}328
// /* create code */329
// app.at("/api/code").post(|req: tide::Request<State>| async move {330
// let account = match identify(&req).await {331
// Ok(model) => model,332
// Err(err) => return Response::throw(err),333
// };334
// let mut conn = req.sqlx_conn::<Postgres>().await;335
// let code = Code::new();336
// match sqlx::query(337
// &format!(338
// "339
// INSERT INTO code340
// (code, account_id, timestamp, used)341
// VALUES342
// ('{}', '{}', CURRENT_TIMESTAMP, false)343
// ON CONFLICT344
// (account_id)345
// DO UPDATE346
// SET347
// code = excluded.code,348
// timestamp = excluded.timestamp,349
// used = excluded.used350
// ",351
// &code.code,352
// &account.id,353
// )354
// )355
// .execute(conn.acquire().await.unwrap())356
// .await357
// {358
// Ok(_) => Response::with(code),359
// Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),360
// }361
// });365
async fn identify(req: &tide::Request<State>) -> Result<Model<Account>, Error> {366
let token = match req.header("verbal-token") {367
Some(header) => header.as_str(),368
None => return Err(Error::new(ErrorKind::Identity, "No request header 'verbal-token' provided!")),369
};370
let query = format!(371
"372
SELECT account.* FROM account373
INNER JOIN device374
ON device.account_id = account.id375
WHERE device.token = '{}'376
",377
&token,378
);379
let mut conn = req.sqlx_conn::<Postgres>().await;380
let id = match sqlx::query(&query)381
.fetch_one(conn.acquire().await.unwrap())382
.await383
{384
Ok(row) => row.get("id"),385
Err(_) => return Err(Error::new(ErrorKind::Identity, "No account found for provided header 'verbal-token'!")),386
};387
let inner = match sqlx::query_as::<_, Account>(&query)388
.fetch_one(conn.acquire().await.unwrap())389
.await390
{391
Ok(inner) => inner,392
Err(_) => return Err(Error::new(ErrorKind::Identity, "No account found for provided header 'verbal-token'!")),393
};394
Ok(Model::from(id, inner))395
}363
// /* update code */364
// app.at("/api/code").put(|req: tide::Request<State>| async move {365
// let _ = match identify(&req).await {366
// Ok(model) => model,367
// Err(err) => return Response::throw(err),368
// };369
// Response::success()370
// });372
// async fn identify(req: &tide::Request<State>) -> Result<Model<Account>, Error> {373
// let token = match req.header("verbal-token") {374
// Some(header) => header.as_str(),375
// None => return Err(Error::new(ErrorKind::Identity, "No request header 'verbal-token' provided!")),376
// };377
// let query = format!(378
// "379
// SELECT account.* FROM account380
// INNER JOIN device381
// ON device.account_id = account.id382
// WHERE device.token = '{}'383
// ",384
// &token,385
// );386
// let mut conn = req.sqlx_conn::<Postgres>().await;387
// let id = match sqlx::query(&query)388
// .fetch_one(conn.acquire().await.unwrap())389
// .await390
// {391
// Ok(row) => row.get("id"),392
// Err(_) => return Err(Error::new(ErrorKind::Identity, "No account found for provided header 'verbal-token'!")),393
// };394
// let inner = match sqlx::query_as::<_, Account>(&query)395
// .fetch_one(conn.acquire().await.unwrap())396
// .await397
// {398
// Ok(inner) => inner,399
// Err(_) => return Err(Error::new(ErrorKind::Identity, "No account found for provided header 'verbal-token'!")),400
// };401
// Ok(Model::from(id, inner))402
// }
1
use serde::{Deserialize, Serialize};2
use sqlx::FromRow;4
pub trait Query {5
fn into_keys(&self) -> String;6
fn into_values(&self) -> String;7
fn into_update(&self) -> String;8
}10
#[derive(Debug, Deserialize, Serialize, FromRow)]11
pub struct Model<T> {12
pub id: i32,13
pub inner: T,14
}16
impl<T> Model<T> where T: Query {17
pub fn new(inner: T) -> Self {18
Self { id: 0, inner }19
}20
pub fn from(id: i32, inner: T) -> Self {21
Self { id, inner }22
}23
pub fn into_insert(&self, table: &str) -> String {24
format!(25
"26
INSERT INTO {}27
(28
{}29
created_at,30
updated_at31
)32
VALUES33
(34
{}35
CURRENT_TIMESTAMP,36
CURRENT_TIMESTAMP37
)38
",39
&table,40
&self.inner.into_keys(),41
&self.inner.into_values(),42
)43
}44
pub fn into_update(&self, table: &str) -> String {45
format!(46
"47
UPDATE {}48
SET49
{}50
updated_at = CURRENT_TIMESTAMP51
WHERE52
id = {}53
",54
&table,55
&self.inner.into_update(),56
&self.id,57
)58
}59
}
1
use serde::Serialize;2
use diesel::Queryable;2
use serde::{Deserialize, Serialize};3
use sqlx::FromRow;4
use regex::Regex;5
use rand::{distributions::Alphanumeric, Rng};7
use verbal::model::Query;8
use verbal::Utils;10
use crate::adapter::Adapter;12
#[derive(Debug, Deserialize, Serialize, FromRow)]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
}19
impl Default for Account {20
fn default() -> Self {21
Self {22
username: None,23
language: "en".into(),24
is_playback_history: true,25
}26
}27
}29
impl Query for Account {30
fn into_keys(&self) -> String {31
format!("32
username,33
language,34
is_playback_history,35
")36
}37
fn into_values(&self) -> String {38
format!(39
"40
{},41
'{}',42
{},43
",44
Utils::null(&self.username),45
&self.language,46
&self.is_playback_history,47
)48
}49
fn into_update(&self) -> String {50
format!(51
"52
username = {},53
language = '{}',54
is_playback_history = {},55
",56
Utils::null(&self.username),57
&self.language,58
&self.is_playback_history,59
)60
}61
}63
#[derive(Debug, Deserialize, Serialize, FromRow)]64
pub struct Favorite {65
pub station_id: String,12
#[derive(Debug, Serialize, Queryable)]13
pub struct Device {14
pub id: i32,15
pub token: String,16
pub account_id: i32,17
}69
impl Favorite {70
pub fn new(station_id: &str, account_id: i32) -> Self {71
Self { station_id: station_id.into(), account_id }72
}73
}75
impl Query for Favorite {76
fn into_keys(&self) -> String {77
format!("78
station_id,79
account_id,80
")81
}82
fn into_values(&self) -> String {83
format!(84
"85
'{}',86
{},87
",88
&self.station_id,89
&self.account_id,90
)91
}92
fn into_update(&self) -> String {93
format!(94
"95
station_id = '{}',96
account_id = {},97
",98
&self.station_id,99
&self.account_id,100
)101
}102
}104
#[derive(Debug, Deserialize, Serialize)]105
pub struct Search {106
pub name: String,107
pub page: Option<i64>,108
}110
impl Search {111
pub fn into_query(&self) -> String {112
format!(113
"name={}&offset={}&limit=10&order=votes&reverse=true&hidebroken=true",114
&self.name,115
&self.page.unwrap_or(0) * 10,116
)117
}118
}120
#[derive(Debug, Default, Deserialize, Serialize)]19
#[derive(Debug, Serialize, Queryable)]20
pub struct Station {122
pub id: String,21
pub id: i32,22
pub uuid: String,23
pub name: String,24
pub stream_url: String,125
pub votes: i64,126
pub favicon: String,127
pub homepage: String,25
pub votes: i32,26
pub favicon: Option<String>,27
pub homepage: Option<String>,28
pub tags: Vec<String>,129
pub click_trend: i64,130
pub click_count: i64,131
pub country: String,29
pub country: Option<String>,30
pub languages: Vec<String>,133
pub state: String,134
pub is_favorite: bool,135
}137
#[derive(Debug, Deserialize, Clone)]138
pub struct StationAdapter {139
pub stationuuid: String,140
pub name: String,141
pub url: String,142
pub votes: i64,143
pub favicon: String,144
pub homepage: String,145
pub tags: String,146
pub clicktrend: i64,147
pub clickcount: i64,148
pub countrycode: String,149
pub languagecodes: String,150
pub state: String,151
}153
impl Adapter<Station> for StationAdapter {154
fn populate(self, mut target: Station) -> Station {155
target.id = self.stationuuid;156
target.name = self.name;157
target.stream_url = upgrade_to_https(self.url);158
target.votes = self.votes;159
target.favicon = self.favicon;160
target.homepage = self.homepage;161
target.tags = to_array(self.tags);162
target.click_trend = self.clicktrend;163
target.click_count = self.clickcount;164
target.country = self.countrycode;165
target.languages = to_array(self.languagecodes);166
target.state = self.state;167
target168
}31
pub state: Option<String>,32
}171
fn to_array(value: String) -> Vec<String> {172
value.split(",")173
.map(str::to_string)174
.filter(|tag| tag.trim().len() > 0)175
.collect::<Vec<String>>()176
}178
fn upgrade_to_https(url: String) -> String {179
if Regex::new("^http://")180
.unwrap()181
.is_match(&url)182
{183
/* TODO: include in config struct */184
return format!("https://api.radio.typable.dev/pass?redirect={}", &url);185
}186
url187
}189
#[derive(Debug, Deserialize, Serialize, FromRow)]190
pub struct Code {191
pub code: String,192
pub used: bool,193
pub expired: bool,194
}196
impl Code {197
pub fn new() -> Self {198
let code = rand::thread_rng()199
.sample_iter(&Alphanumeric)200
.take(6)201
.map(char::from)202
.map(|c| c.to_uppercase().to_string())203
.collect::<String>();204
Self { code, used: false, expired: false }205
}206
}34
// use rand::{distributions::Alphanumeric, Rng};36
// #[derive(Debug, Deserialize, Serialize, FromRow)]37
// pub struct Account {38
// pub username: Option<String>,39
// pub language: String,40
// pub is_playback_history: bool,41
// }43
// impl Default for Account {44
// fn default() -> Self {45
// Self {46
// username: None,47
// language: "en".into(),48
// is_playback_history: true,49
// }50
// }51
// }53
// impl Query for Account {54
// fn into_keys(&self) -> String {55
// format!("56
// username,57
// language,58
// is_playback_history,59
// ")60
// }61
// fn into_values(&self) -> String {62
// format!(63
// "64
// {},65
// '{}',66
// {},67
// ",68
// Utils::null(&self.username),69
// &self.language,70
// &self.is_playback_history,71
// )72
// }73
// fn into_update(&self) -> String {74
// format!(75
// "76
// username = {},77
// language = '{}',78
// is_playback_history = {},79
// ",80
// Utils::null(&self.username),81
// &self.language,82
// &self.is_playback_history,83
// )84
// }85
// }87
// #[derive(Debug, Deserialize, Serialize, FromRow)]88
// pub struct Favorite {89
// pub station_id: String,90
// pub account_id: i32,91
// }93
// impl Favorite {94
// pub fn new(station_id: &str, account_id: i32) -> Self {95
// Self { station_id: station_id.into(), account_id }96
// }97
// }99
// impl Query for Favorite {100
// fn into_keys(&self) -> String {101
// format!("102
// station_id,103
// account_id,104
// ")105
// }106
// fn into_values(&self) -> String {107
// format!(108
// "109
// '{}',110
// {},111
// ",112
// &self.station_id,113
// &self.account_id,114
// )115
// }116
// fn into_update(&self) -> String {117
// format!(118
// "119
// station_id = '{}',120
// account_id = {},121
// ",122
// &self.station_id,123
// &self.account_id,124
// )125
// }126
// }128
// #[derive(Debug, Default, Deserialize, Serialize)]129
// pub struct Station {130
// pub id: String,131
// pub name: String,132
// pub stream_url: String,133
// pub votes: i64,134
// pub favicon: String,135
// pub homepage: String,136
// pub tags: Vec<String>,137
// pub click_trend: i64,138
// pub click_count: i64,139
// pub country: String,140
// pub languages: Vec<String>,141
// pub state: String,142
// pub is_favorite: bool,143
// }145
// #[derive(Debug, Deserialize, Serialize, FromRow)]146
// pub struct Code {147
// pub code: String,148
// pub used: bool,149
// pub expired: bool,150
// }152
// impl Code {153
// pub fn new() -> Self {154
// let code = rand::thread_rng()155
// .sample_iter(&Alphanumeric)156
// .take(6)157
// .map(char::from)158
// .map(|c| c.to_uppercase().to_string())159
// .collect::<String>();160
// Self { code, used: false, expired: false }161
// }162
// }
1
use serde::Serialize;3
#[derive(Debug, Serialize)]4
pub struct Response<T, E> {5
pub ok: bool,6
pub data: Option<T>,7
pub error: Option<E>,8
}10
impl Response<(), ()> {11
pub fn success() -> Result<tide::Body, tide::Error> {12
tide::Body::from_json(&Self { ok: true, data: None, error: None })13
}14
}16
impl<T> Response<T, ()> where T: Serialize {17
pub fn with(data: T) -> Result<tide::Body, tide::Error> {18
tide::Body::from_json(&Self { ok: true, data: Some(data), error: None })19
}20
pub fn with_option(data: Option<T>) -> Result<tide::Body, tide::Error> {21
tide::Body::from_json(&Self { ok: true, data, error: None })22
}23
}26
impl<E> Response<(), E> where E: Serialize {27
pub fn throw(error: E) -> Result<tide::Body, tide::Error> {28
tide::Body::from_json(&Self { ok: false, data: None, error: Some(error) })29
}30
}
1
table! {2
account (id) {3
id -> Integer,4
username -> Nullable<Text>,5
language -> Text,6
is_playback_history -> Bool,7
}8
}10
table! {11
device (id) {12
id -> Integer,13
token -> Text,14
account_id -> Integer,15
}16
}18
table! {19
station (id) {20
id -> Integer,21
uuid -> Text,22
name -> Text,23
stream_url -> Text,24
votes -> Integer,25
favicon -> Nullable<Text>,26
homepage -> Nullable<Text>,27
tags -> Array<Text>,28
country -> Nullable<Text>,29
languages -> Array<Text>,30
state -> Nullable<Text>,31
}32
}
1
mod common;1
#[macro_use]2
extern crate diesel;4
use diesel::prelude::*;5
use diesel::pg::PgConnection;7
mod utils;8
mod error;3
mod backend;9
mod api;10
mod adapter;11
mod models;12
mod schema;6
use backend::api::{RadioBrowserApi, Search};14
use models::*;15
use schema::account::dsl::*;16
use api::{RadioBrowserApi, Search};18
#[async_std::main]19
async fn main() {20
let database_url = "postgres://typable:De24Si98@192.168.2.3:9748/verbal";21
let conn = PgConnection::establish(&database_url)22
.expect("Unable to connect to database!");23
let results = account.load::<Account>(&conn)24
.expect("Unable to load model!");25
for item in results {26
println!("{:?}", item);27
}28
let mut search = Search::default();29
search.name = "bbc".into();30
match RadioBrowserApi::search(search).await {
1
use regex::Regex;3
pub fn to_array(value: String) -> Vec<String> {4
value.split(",")5
.map(str::to_string)6
.filter(|tag| tag.trim().len() > 0)7
.collect::<Vec<String>>()8
}10
pub fn upgrade_to_https(url: String) -> String {11
if Regex::new("^http://")12
.unwrap()13
.is_match(&url)14
{15
/* TODO: include in config struct */16
return format!("https://api.radio.typable.dev/pass?redirect={}", &url);17
}18
url19
}