A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
1
#[macro_use]2
extern crate diesel;4
use diesel::prelude::*;4
use tide_diesel::DieselMiddleware;6
use tide_diesel::DieselRequestExt;5
use tide_compress::CompressMiddleware;7
mod utils;
12
mod adapter;13
mod response;14
mod middleware;15
mod api;16
mod state;17
mod service;19
use error::ErrorKind;20
use config::Config;19
use models::*;20
use schema::account::dsl::account;21
use state::State;22
use response::Response;22
use middleware::CorsMiddleware;23
use middleware::{CorsMiddleware, AuthMiddleware};24
use api::Search;26
#[async_std::main]27
async fn main() -> tide::Result<()> {
29
let config = Config::from_file("./config.ron")30
.expect("Unable to parse config!");30
let mut app = tide::new();32
let mut app = tide::with_state(State::new());34
/* bind database middleware */35
app.with(DieselMiddleware::new(&config.database.to_string()).unwrap());
37
/* bind cors middleware */38
app.with(CorsMiddleware::new(&config.options.origin));40
/* bind auth middleware */41
app.with(AuthMiddleware::new());43
/* bind compression middleware */44
app.with(CompressMiddleware::new());46
/* handle prefetch */42
app.at("*").options(|_: tide::Request<()>| async move {47
app.at("*").options(|_: tide::Request<State>| async move {48
Ok(tide::Response::new(200))49
});
57
/* provide app */58
app.at("/app").serve_dir("app/")?;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)60
app.at("/api/search").get(|req: tide::Request<State>| async move {61
let state = req.state();62
let search = match req.query::<Search>() {63
Ok(query) => query,64
Err(err) => return Response::throw(ErrorKind::Arguments, &err.to_string()),65
};66
let result = match state.service.search(search).await {67
Ok(result) => result,68
Err(err) => return Response::throw(ErrorKind::Fetch, &err.to_string()),69
};70
Response::with(result)71
});73
app.listen(&config.server.to_string()).await?;
1
pub struct CorsMiddleware {2
origin: String,3
}1
mod cors;2
mod auth;5
impl CorsMiddleware {6
pub fn new(origin: &str) -> Self {7
Self { origin: origin.into() }8
}9
}11
#[tide::utils::async_trait]12
impl<State: Clone + Send + Sync + 'static> tide::Middleware<State> for CorsMiddleware {13
async fn handle(&self, req: tide::Request<State>, next: tide::Next<'_, State>) -> tide::Result {14
let mut res = next.run(req).await;15
res.insert_header("Access-Control-Allow-Origin", &self.origin);16
res.insert_header("Access-Control-Allow-Headers", "*");17
res.insert_header("Access-Control-Allow-Methods", "*");18
Ok(res)19
}20
}4
pub use cors::CorsMiddleware;5
pub use auth::AuthMiddleware;
1
use diesel::prelude::*;2
use tide_diesel::DieselRequestExt;4
use crate::error::ErrorKind;5
use crate::response::Response;6
use crate::models::*;7
use crate::schema::account;8
use crate::schema::device;10
pub struct AuthMiddleware {}12
impl AuthMiddleware {13
pub fn new() -> Self {14
Self {}15
}16
}18
#[tide::utils::async_trait]19
impl<State: Clone + Send + Sync + 'static> tide::Middleware<State> for AuthMiddleware {20
async fn handle(&self, mut req: tide::Request<State>, next: tide::Next<'_, State>) -> tide::Result {21
if req.url().path().starts_with("/api") {22
let token = match req.header("verbal-token") {23
Some(header) => header.as_str(),24
None => return Response::throw(ErrorKind::Identity, "No request header 'verbal-token' provided!"),25
};26
let conn = req.pg_conn().await?;27
let identity: Option<(Account, Device)> = account::table28
.inner_join(device::table)29
.filter(device::dsl::token.eq(token))30
.first(&conn)31
.optional()?;32
if identity.is_none() {33
return Response::throw(ErrorKind::Identity, "No account found for provided header 'verbal-token'!");34
}35
req.set_ext(identity.unwrap());36
}37
let res = next.run(req).await;38
Ok(res)39
}40
}
1
pub struct CorsMiddleware {2
origin: String,3
}5
impl CorsMiddleware {6
pub fn new(origin: &str) -> Self {7
Self { origin: origin.into() }8
}9
}11
#[tide::utils::async_trait]12
impl<State: Clone + Send + Sync + 'static> tide::Middleware<State> for CorsMiddleware {13
async fn handle(&self, req: tide::Request<State>, next: tide::Next<'_, State>) -> tide::Result {14
let mut res = next.run(req).await;15
res.insert_header("Access-Control-Allow-Origin", &self.origin);16
res.insert_header("Access-Control-Allow-Headers", "*");17
res.insert_header("Access-Control-Allow-Methods", "*");18
Ok(res)19
}20
}
31
pub state: Option<String>,32
}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
// }34
#[derive(Debug, Serialize, Queryable)]35
pub struct Favorite {36
pub id: i32,37
pub account_id: i32,38
pub station_id: i32,39
}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
// }41
// use rand::{distributions::Alphanumeric, Rng};43
// #[derive(Debug, Deserialize, Serialize, FromRow)]44
// pub struct Code {
1
use serde::Serialize;2
use crate::error::{Error, ErrorKind};4
#[derive(Debug, Serialize)]5
pub struct Response<T, E> {
12
pub fn success() -> Result<tide::Body, tide::Error> {13
tide::Body::from_json(&Self { ok: true, data: None, error: None })14
}15
pub fn respond(body: Result<tide::Body, tide::Error>) -> tide::Result {16
Ok(17
tide::Response::builder(200)18
.body(body.unwrap())19
.build()20
)21
}22
}24
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 })25
pub fn with(data: T) -> tide::Result {26
Response::respond(tide::Body::from_json(&Self { ok: true, data: Some(data), error: None }))27
}28
pub fn with_option(data: Option<T>) -> Result<tide::Body, tide::Error> {29
tide::Body::from_json(&Self { ok: true, data, error: None })30
}31
}33
impl<E> Response<(), E> where E: Serialize {27
pub fn throw(error: E) -> Result<tide::Body, tide::Error> {34
pub fn with_error(error: E) -> Result<tide::Body, tide::Error> {35
tide::Body::from_json(&Self { ok: false, data: None, error: Some(error) })36
}37
}39
impl Response<(), Error> {40
pub fn throw(error_kind: ErrorKind, message: &str) -> tide::Result {41
Response::respond(tide::Body::from_json(&Self { ok: false, data: None, error: Some(Error::new(error_kind, message)) }))42
}43
}
30
state -> Nullable<Text>,31
}32
}34
table! {35
favorite (id) {36
id -> Integer,37
account_id -> Integer,38
station_id -> Integer,39
}40
}42
joinable!(device -> account (account_id));43
joinable!(favorite -> account (account_id));44
joinable!(favorite -> station (station_id));46
allow_tables_to_appear_in_same_query!(47
account,48
device,49
favorite,50
);
1
use crate::error::Result;2
use crate::api::{RadioBrowserApi, Search};3
use crate::models::Station;5
#[derive(Clone)]6
pub struct Service {}8
impl Service {9
pub fn new() -> Self {10
Self {}11
}13
pub async fn search(&self, search: Search) -> Result<Vec<Station>> {14
RadioBrowserApi::search(search).await15
}16
}
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 { service: Service::new() }11
}12
}
12
.unwrap()13
.is_match(&url)14
{15
/* TODO: include in config struct */16
return format!("https://api.radio.typable.dev/pass?redirect={}", &url);15
return format!("https://verbal.fm/api/upgrade?redirect={}", &url);16
}17
url18
}