A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
16
tokio = { version = "1.19.2", features = ["full"] }17
async-std = { version = "1.12.0", features = ["attributes", "tokio1"] }18
sqlx = { version = "0.5.13", features = ["runtime-tokio-rustls", "postgres"] }19
dirs = "4.0.0"20
env_logger = "0.9.0"21
log = "0.4.17"22
reqwest = { version = "0.11.11", features = ["json"] }
1
use serde::Deserialize;2
use std::fmt;4
use crate::error::{Error, ErrorKind, Result};4
use crate::error::Error;5
use crate::rest;6
use crate::Result;8
const API_URLS: [&str; 3] = [9
"https://de1.api.radio-browser.info",
36
let mut response = RadioBrowserApi::fetch(&uri).await?;37
match response.body_json::<Vec<rest::Station>>().await {38
Ok(data) => Ok(data),38
Err(err) => Err(Error::new(ErrorKind::Parse, &err.to_string())),39
Err(err) => Err(Error::new(&err.to_string())),40
}41
}
45
let mut response = RadioBrowserApi::fetch(&uri).await?;46
match response.body_json::<Vec<rest::Station>>().await {47
Ok(data) => Ok(data),47
Err(err) => Err(Error::new(ErrorKind::Parse, &err.to_string())),48
Err(err) => Err(Error::new(&err.to_string())),49
}50
}
58
successful_response = Some(response);59
break;60
}60
Err(err) => println!("{}", Error::new(ErrorKind::Fetch, &err.to_string())),61
Err(err) => println!("{}", Error::new(&err.to_string())),62
}63
}64
match successful_response {65
Some(response) => Ok(response),65
None => Err(Error::new(ErrorKind::Fetch, "All request attempts failed!")),66
None => Err(Error::new("All request attempts failed!")),67
}68
}69
}
2
use std::fmt;3
use std::fs;5
use crate::error::Error;6
use crate::Result;7
use crate::APP_NAME;9
#[derive(Debug, Clone, Deserialize)]10
pub struct Server {11
pub hostname: String,
50
}52
impl Config {49
pub fn from_file(path: &str) -> Result<Self, toml::de::Error> {50
let raw = fs::read_to_string(path).expect("Unable to locate config file!");51
toml::from_str(&raw)53
pub fn acquire() -> Result<Self> {54
let mut config_path = match dirs::config_dir() {55
Some(config_path) => config_path,56
None => return Err(Error::new("unable to determine config path!")),57
};58
config_path.push(APP_NAME);59
config_path.push("config.toml");60
let raw = fs::read_to_string(&config_path)?;61
let config: Self = toml::from_str(&raw)?;62
Ok(config)63
}64
}
48
Self {49
uuid: model.uuid,50
name: model.name,51
stream_url: upgrade_to_https(model.stream_url),51
stream_url: upgrade_to_https(&model.stream_url),52
votes: model.votes,53
favicon: model.favicon,54
homepage: model.homepage,
66
Self {67
uuid: rest.stationuuid,68
name: rest.name,69
stream_url: upgrade_to_https(rest.url),69
stream_url: upgrade_to_https(&rest.url),70
votes: rest.votes,71
favicon: Some(rest.favicon),72
homepage: Some(rest.homepage),73
tags: to_array(rest.tags),73
tags: to_array(&rest.tags),74
country: Some(rest.countrycode),75
languages: to_array(rest.languagecodes),75
languages: to_array(&rest.languagecodes),76
state: Some(rest.state),77
is_favorite: false,78
}
1
use std::fmt;1
use serde::Serialize;5
pub type Result<T> = std::result::Result<T, Error>;7
#[derive(Debug, Clone, Serialize)]8
pub enum ErrorKind {9
Identity,10
Arguments,11
Fetch,12
Parse,13
Query,14
}16
impl fmt::Display for ErrorKind {17
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {18
write!(f, "{:?}", self)19
}20
}2
use std::fmt;4
#[derive(Debug, Clone, Serialize)]5
pub struct Error {24
kind: ErrorKind,6
message: String,7
}9
impl Error {29
pub fn new(kind: ErrorKind, message: &str) -> Self {10
#[must_use]11
pub fn new(message: &str) -> Self {12
Self {31
kind,13
message: message.into(),14
}15
}
18
impl fmt::Display for Error {19
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {39
write!(f, "[{}] {}", self.kind, self.message)20
write!(f, "{}", self.message)21
}22
}24
impl From<std::io::Error> for Error {25
fn from(err: std::io::Error) -> Self {26
Self::new(&err.to_string())27
}28
}30
impl From<toml::de::Error> for Error {31
fn from(err: toml::de::Error) -> Self {32
Self::new(&err.to_string())33
}34
}
1
use env_logger::Builder;2
use env_logger::Target;3
use log::LevelFilter;4
use std::process;6
pub mod api;7
pub mod data;8
pub mod error;9
pub mod middleware;10
pub mod model;11
pub mod rest;12
pub mod utils;14
mod config;15
mod response;16
mod server;17
mod service;19
pub use config::Config;20
pub use response::Response;21
pub use server::Server;22
pub use service::Service;24
use error::Error;26
#[macro_use]27
extern crate log;29
pub const APP_NAME: &str = "verbal";31
pub type Result<T> = std::result::Result<T, Error>;33
pub fn init_logger() {34
Builder::new()35
.format_timestamp_secs()36
.filter_module(APP_NAME, LevelFilter::Info)37
.target(Target::Stdout)38
.init();39
}41
pub fn abort(err: &Error) -> ! {42
error!("{}", err);43
process::exit(1)44
}
1
use data::Song;2
use sqlx::postgres::Postgres;3
use tide_compress::CompressMiddleware;4
use tide_sqlx::SQLxMiddleware;6
mod api;7
mod config;8
mod data;9
mod error;10
mod middleware;11
mod model;12
mod response;13
mod rest;14
mod service;15
mod utils;17
use api::Search;18
use config::Config;19
use error::ErrorKind;20
use middleware::{AuthMiddleware, CorsMiddleware};21
use response::Response;22
use service::Service;1
use verbal::abort;2
use verbal::init_logger;3
use verbal::Server;5
#[tokio::main]25
async fn main() -> tide::Result<()> {26
let config = Config::from_file("./config.toml").expect("Unable to parse config!");28
let mut app = tide::new();30
/* bind database middleware */31
app.with(32
SQLxMiddleware::<Postgres>::new(&config.database.to_string())33
.await34
.unwrap(),35
);37
/* bind cors middleware */38
app.with(CorsMiddleware::new(&config.server.options.origin));40
/* bind auth middleware */41
app.with(AuthMiddleware::new());43
/* bind compression middleware */44
app.with(CompressMiddleware::new());46
/* handle prefetch */47
app.at("*")48
.options(|_: tide::Request<()>| async move { Ok(tide::Response::new(200)) });50
/* provide index */51
app.at("/").serve_file("www/index.html")?;53
/* provide assets */54
app.at("/asset").serve_dir("www/asset/")?;56
/* provide app */57
app.at("/app").serve_dir("app/")?;59
app.at("/api/account")60
.get(|req: tide::Request<()>| async move {61
let account = req.ext::<model::Account>().unwrap();62
let data: data::Account = (*account).clone().into();63
Response::with(data)64
});66
app.at("/api/search")67
.get(|req: tide::Request<()>| async move {68
let search = match req.query::<Search>() {69
Ok(query) => query,70
Err(err) => return Response::throw(ErrorKind::Arguments, &err.to_string()),71
};72
match Service::search(search, req).await {73
Ok(data) => Response::with(data),74
Err(err) => Response::throw(ErrorKind::Fetch, &err.to_string()),75
}76
});78
app.at("/api/song")79
.get(|req: tide::Request<()>| async move {80
let song = match req.query::<Song>() {81
Ok(song) => song,82
Err(err) => return Response::throw(ErrorKind::Arguments, &err.to_string()),83
};84
match Service::get_song(song).await {85
Ok(data) => Response::with(data),86
Err(err) => Response::throw(ErrorKind::Fetch, &err.to_string()),87
}88
});90
app.at("/api/like")91
.get(|req: tide::Request<()>| async move {92
match Service::get_likes(req).await {93
Ok(data) => Response::with(data),94
Err(err) => Response::throw(ErrorKind::Fetch, &err.to_string()),95
}96
});98
app.at("/api/like")99
.post(|req: tide::Request<()>| async move {100
match Service::add_like(req).await {101
Ok(data) => Response::with(data),102
Err(err) => Response::throw(ErrorKind::Fetch, &err.to_string()),103
}104
});106
app.at("/api/like")107
.delete(|req: tide::Request<()>| async move {108
match Service::remove_like(req).await {109
Ok(data) => Response::with(data),110
Err(err) => Response::throw(ErrorKind::Fetch, &err.to_string()),111
}112
});114
app.listen(&config.server.to_string()).await?;116
Ok(())6
async fn main() {7
init_logger();8
let server = Server::default();9
server.run().await.unwrap_or_else(|err| abort(&err));10
}
1
mod auth;2
mod cors;4
pub use auth::AuthMiddleware;5
pub use cors::CorsMiddleware;4
pub use auth::Auth;5
pub use cors::Cors;
2
use sqlx::Acquire;3
use tide_sqlx::SQLxRequestExt;5
use crate::error::ErrorKind;5
use crate::model;6
use crate::response::Response;9
pub struct AuthMiddleware {}11
impl AuthMiddleware {12
pub fn new() -> Self {13
Self {}14
}15
}8
#[derive(Default)]9
pub struct Auth;11
#[tide::utils::async_trait]18
impl<State: Clone + Send + Sync + 'static> tide::Middleware<State> for AuthMiddleware {12
impl<State: Clone + Send + Sync + 'static> tide::Middleware<State> for Auth {13
async fn handle(14
&self,15
mut req: tide::Request<State>,
18
if req.url().path().starts_with("/api") {19
let token = match req.header("verbal-token") {20
Some(header) => header.as_str(),27
None => {28
return Response::throw(29
ErrorKind::Identity,30
"No request header 'verbal-token' provided!",31
)32
}21
None => return Response::throw("No request header 'verbal-token' provided!"),22
};23
let query = format!(24
"
36
option_account = sqlx::query_as::<_, model::Account>(&query)37
.fetch_optional(conn.acquire().await.unwrap())38
.await50
.unwrap()39
.unwrap();40
}41
match option_account {42
Some(account) => {43
req.set_ext(account);44
}45
None => {57
return Response::throw(58
ErrorKind::Identity,59
"No account found for provided header 'verbal-token'!",60
);46
return Response::throw("No account found for provided header 'verbal-token'!");47
}48
}49
}
1
pub struct CorsMiddleware {1
pub struct Cors {2
origin: String,3
}5
impl CorsMiddleware {5
impl Cors {6
#[must_use]7
pub fn new(origin: &str) -> Self {8
Self {9
origin: origin.into(),
12
}14
#[tide::utils::async_trait]14
impl<State: Clone + Send + Sync + 'static> tide::Middleware<State> for CorsMiddleware {15
impl<State: Clone + Send + Sync + 'static> tide::Middleware<State> for Cors {16
async fn handle(&self, req: tide::Request<State>, next: tide::Next<'_, State>) -> tide::Result {17
let mut res = next.run(req).await;18
res.insert_header("Access-Control-Allow-Origin", &self.origin);
1
use crate::error::{Error, ErrorKind};1
use crate::error::Error;2
use serde::Serialize;4
#[derive(Debug, Serialize)]
28
}30
impl Response<(), Error> {31
pub fn throw(error_kind: ErrorKind, message: &str) -> tide::Result {31
pub fn throw(message: &str) -> tide::Result {32
Response::respond(tide::Body::from_json(&Self {33
ok: false,34
data: None,35
error: Some(Error::new(error_kind, message)),35
error: Some(Error::new(message)),36
}))37
}38
}
1
use sqlx::postgres::Postgres;2
use tide_compress::CompressMiddleware;3
use tide_sqlx::SQLxMiddleware;5
use crate::abort;6
use crate::api::Search;7
use crate::data;8
use crate::middleware::Auth;9
use crate::middleware::Cors;10
use crate::model;11
use crate::Config;12
use crate::Response;13
use crate::Result;14
use crate::Service;16
#[derive(Default)]17
pub struct Server {}19
impl Server {20
pub async fn run(&self) -> Result<()> {21
let config = Config::acquire().unwrap_or_else(|err| abort(&err));22
let mut app = tide::new();24
/* bind middleware */25
app.with(Auth::default());26
app.with(Cors::new(&config.server.options.origin));27
app.with(CompressMiddleware::new());28
app.with(29
SQLxMiddleware::<Postgres>::new(&config.database.to_string())30
.await31
.unwrap(),32
);34
/* handle prefetch */35
app.at("*")36
.options(|_: tide::Request<()>| async move { Ok(tide::Response::new(200)) });38
/* serve content */39
app.at("/").serve_file("www/index.html")?;40
app.at("/asset").serve_dir("www/asset/")?;41
app.at("/app").serve_dir("app/")?;43
app.at("/api/account").get(get_account);45
app.at("/api/search")46
.get(|req: tide::Request<()>| async move {47
let search = match req.query::<Search>() {48
Ok(query) => query,49
Err(err) => return Response::throw(&err.to_string()),50
};51
match Service::search(search, req).await {52
Ok(data) => Response::with(data),53
Err(err) => Response::throw(&err.to_string()),54
}55
});57
app.at("/api/song")58
.get(|req: tide::Request<()>| async move {59
let song = match req.query::<data::Song>() {60
Ok(song) => song,61
Err(err) => return Response::throw(&err.to_string()),62
};63
match Service::get_song(song).await {64
Ok(data) => Response::with(data),65
Err(err) => Response::throw(&err.to_string()),66
}67
});69
app.at("/api/like")70
.get(|req: tide::Request<()>| async move {71
match Service::get_likes(req).await {72
Ok(data) => Response::with(data),73
Err(err) => Response::throw(&err.to_string()),74
}75
});77
app.at("/api/like")78
.post(|req: tide::Request<()>| async move {79
match Service::add_like(req).await {80
Ok(data) => Response::with(data),81
Err(err) => Response::throw(&err.to_string()),82
}83
});85
app.at("/api/like")86
.delete(|req: tide::Request<()>| async move {87
match Service::remove_like(req).await {88
Ok(data) => Response::with(data),89
Err(err) => Response::throw(&err.to_string()),90
}91
});93
app.listen(&config.server.to_string()).await?;94
Ok(())95
}96
}98
async fn get_account(req: tide::Request<()>) -> tide::Result {99
let account = req.ext::<model::Account>().unwrap();100
let data: data::Account = (*account).clone().into();101
Response::with(data)102
}
7
use crate::api::{RadioBrowserApi, Search};8
use crate::data::{self, Song};9
use crate::error::{Error, ErrorKind, Result};9
use crate::error::Error;10
use crate::model;11
use crate::Result;13
pub struct Service {}
47
pub async fn get_song(song: Song) -> Result<Option<String>> {48
let mut response = match surf::get(&song.url).header("icy-metadata", "1").await {49
Ok(response) => response,49
Err(_) => return Err(Error::new(ErrorKind::Fetch, "Unable to fetch metadata!")),50
Err(_) => return Err(Error::new("Unable to fetch metadata!")),51
};52
let meta_int = match response.header("icy-metaint") {53
Some(header) => header.as_str(),53
None => return Err(Error::new(ErrorKind::Parse, "Invalid icy metadata!")),54
None => return Err(Error::new("Invalid icy metadata!")),55
};56
let interval = match meta_int.parse::<usize>() {57
Ok(value) => value * 2,57
Err(_) => {58
return Err(Error::new(59
ErrorKind::Parse,60
"Unable to parse icy metadata!",61
))62
}58
Err(_) => return Err(Error::new("Unable to parse icy metadata!")),59
};60
let mut count = 0;61
let mut bytes = vec![];
66
bytes.extend_from_slice(&buf);67
if count + len > interval {68
let metadata = String::from_utf8_lossy(&bytes);73
for cap in Regex::new("StreamTitle='([^;]*)';")69
if let Some(cap) = Regex::new("StreamTitle='([^;]*)';")70
.unwrap()71
.captures_iter(&metadata)72
.next()73
{74
data = Some(cap[1].to_string());78
break;75
}76
break;77
}
122
pub async fn add_like(mut req: tide::Request<()>) -> Result<()> {123
let uuid = match req.body_json::<String>().await {124
Ok(body) => body,129
Err(_) => {130
return Err(Error::new(131
ErrorKind::Arguments,132
"No station uuid provided!",133
))134
}125
Err(_) => return Err(Error::new("No station uuid provided!")),126
};127
let account = req.ext::<model::Account>().unwrap();128
let query = format!(
140
.await141
{142
Ok(_) => Ok(()),152
Err(err) => Err(Error::new(ErrorKind::Query, &err.to_string())),143
Err(err) => Err(Error::new(&err.to_string())),144
}145
}147
pub async fn remove_like(mut req: tide::Request<()>) -> Result<()> {148
let uuid = match req.body_json::<String>().await {149
Ok(body) => body,159
Err(_) => {160
return Err(Error::new(161
ErrorKind::Arguments,162
"No station uuid provided!",163
))164
}150
Err(_) => return Err(Error::new("No station uuid provided!")),151
};152
let account = req.ext::<model::Account>().unwrap();153
let query = format!(
164
.await165
{166
Ok(_) => Ok(()),181
Err(err) => Err(Error::new(ErrorKind::Query, &err.to_string())),167
Err(err) => Err(Error::new(&err.to_string())),168
}169
}170
}
1
use regex::Regex;3
pub fn to_array(value: String) -> Vec<String> {1
pub fn to_array(value: &str) -> Vec<String> {2
value3
.split(',')4
.map(str::to_string)
6
.collect::<Vec<String>>()7
}11
pub fn upgrade_to_https(url: String) -> String {12
if Regex::new("^http://").unwrap().is_match(&url) {9
pub fn upgrade_to_https(url: &str) -> String {10
if url.starts_with("http://") {11
return format!("https://verbal.fm/api/upgrade?redirect={}", &url);12
}15
url13
url.to_string()14
}