A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
6
[dependencies]7
toml = "0.5.9"8
tide = "0.16.0"9
rand = "0.8.5"10
surf = "2.3.2"9
regex = "1.5.6"10
tide-sqlx = "0.6.1"11
serde_json = "1.0.82"
14
tokio = { version = "1.19.2", features = ["full"] }15
async-std = { version = "1.12.0", features = ["attributes", "tokio1"] }16
sqlx = { version = "0.5.13", features = ["runtime-tokio-rustls", "postgres"] }17
dirs = "4.0.0"18
env_logger = "0.9.0"19
log = "0.4.17"20
surf = "2.3.2"21
tide-rustls = "0.3.0"
27
></v-button>28
</div>29
<v-button30
:text="state.account.username"30
:text="state.account.name"31
icon="user"32
:title="$lang('global.account')"33
:active="state.tab === 'account'"
34
$lang,35
async setLike(is_favorite) {36
try {37
await http`${is_favorite ? 'post' : 'delete'}::/api/like`(this.station.uuid);37
await http`${is_favorite ? 'post' : 'delete'}::/api/favorite`(this.station.id);38
this.station.is_favorite = is_favorite;39
state.app.$refs.favorites.doFetch();40
}
82
title: this.title,83
artist: this.station.name,84
artwork: [85
{ src: this.station.favicon, sizes: '96x96', type: 'image/jpg' },86
{ src: this.station.favicon, sizes: '128x128', type: 'image/jpg' },87
{ src: this.station.favicon, sizes: '192x192', type: 'image/jpg' },88
{ src: this.station.favicon, sizes: '256x256', type: 'image/jpg' },89
{ src: this.station.favicon, sizes: '384x384', type: 'image/jpg' },90
{ src: this.station.favicon, sizes: '512x512', type: 'image/jpg' }85
{ src: this.station.icon, sizes: '96x96', type: 'image/jpg' },86
{ src: this.station.icon, sizes: '128x128', type: 'image/jpg' },87
{ src: this.station.icon, sizes: '192x192', type: 'image/jpg' },88
{ src: this.station.icon, sizes: '256x256', type: 'image/jpg' },89
{ src: this.station.icon, sizes: '384x384', type: 'image/jpg' },90
{ src: this.station.icon, sizes: '512x512', type: 'image/jpg' }91
]92
});93
}94
},95
async fetchSong() {96
try {97
const song = await http`get::/api/song`({ url: this.station.stream_url });97
const song = await http`get::/api/song`(this.station);98
this.title = song === '' ? '- No song title available -' : song;99
}100
catch(err) {101
console.error(err);102
this.title = '- No song title available -';103
}104
this.updateMediaSession();
124
<audio125
ref="player"126
controls autoplay126
:src="station.stream_url"127
:src="station.url"128
@loadeddata="onLoad"129
@play="onPlay"130
@pause="onPause"131
@error="onError"132
class="select-none pointer-events-none w-0 h-0 opacity-0"133
>133
<source :src="station.stream_url" type="audio/mpeg">134
<source :src="station.stream_url" type="audio/ogg">135
<source :src="station.stream_url" type="audio/aac">134
<source :src="station.url" type="audio/mpeg">135
<source :src="station.url" type="audio/ogg">136
<source :src="station.url" type="audio/aac">137
</audio>138
<div class="p-5 bg-zinc-800 rounded-xl flex gap-5 items-center relative overflow-hidden shadow-2xl z-30">139
<img139
v-if="station.favicon"140
:src="station.favicon"140
v-if="station.icon"141
:src="station.icon"142
:alt="station.name"143
:class="{ 'animate-pulse': playing }"144
class="w-full h-full object-cover absolute top-0 left-0 right-0 bottom-0 blur-2xl opacity-30 z-0 pointer-events-none select-none"145
>146
<div class="w-[64px] h-[64px] min-w-[64px] bg-zinc-900 rounded-lg overflow-hidden z-10">147
<img147
v-if="station.favicon"148
:src="station.favicon"148
v-if="station.icon"149
:src="station.icon"150
:alt="station.name"151
class="w-full h-full object-contain select-none"152
>
158
></v-icon>159
</div>160
<div160
class="flex flex-col flex-1 z-10 min-w-0 cursor-pointer"161
class="flex flex-col flex-1 z-10 min-w-0"162
>163
<p class="text-xl font-semibold text-white pb-1 overflow-hidden text-ellipsis whitespace-nowrap select-none pointer-events-none">164
{{station.name}}
169
</div>170
<div class="inline-flex gap-4 z-10 pr-2">171
<v-button171
:icon="[ station.is_favorite ? 'heart-off' : 'heart' ]"172
:icon="[ station.is_favorite ? 'bookmark-off' : 'bookmark' ]"173
:title="[ $lang(station.is_favorite ? 'global.unlike' : 'global.like') ]"174
:active="station.is_favorite"175
class="bg-zinc-900 hover:bg-white focus:ring-[6px] ring-white/10"
13
$lang,14
async setLike(is_favorite) {15
try {16
await http`${is_favorite ? 'post' : 'delete'}::/api/like`(this.station.uuid);16
await http`${is_favorite ? 'post' : 'delete'}::/api/favorite`(this.station.id);17
this.station.is_favorite = is_favorite;18
state.app.$refs.favorites.doFetch();19
}
29
<div class="w-full gap-4 group flex items-center">30
<div class="w-[54px] h-[54px] min-w-[54px] bg-zinc-900 rounded-lg overflow-hidden">31
<img32
v-if="station.favicon"32
v-if="station.icon"33
:alt="station.name"34
:src="station.favicon"35
@error="() => station.favicon = null"34
:src="station.icon"35
@error="() => station.icon = null"36
class="w-full h-full object-contain"37
>38
<v-icon
84
</div>85
<div class="inline-flex gap-3 sm:gap-4">86
<v-button87
:icon="[ station.is_favorite ? 'heart-off' : 'heart' ]"87
:icon="[ station.is_favorite ? 'bookmark-off' : 'bookmark' ]"88
:title="[ $lang(station.is_favorite ? 'global.unlike' : 'global.like') ]"89
:active="station.is_favorite"90
@click="() => setLike(!station.is_favorite)"
8
export const state = {9
app: null,10
tab: 'search',10
tab: 'account',11
account: {12
username: '',13
language: 'en'
21
async doFetch() {22
this.results = [];23
this.loading = true;24
const result = await http`get::/api/like`();24
const result = await http`get::/api/favorite`();25
this.loading = false;26
this.results = result;27
}
26
let body = null;27
let params = '';28
if(method === 'get' || method === 'head') {29
if(query !== undefined && query !== null) {30
for(const [key, value] of Object.entries(query)) {31
if(Array.isArray(value)) {32
delete query[key];33
for(let i = 0; i < value.length; i++) {34
query[`${key}[${i}]`] = value[i];35
}36
}37
}38
}39
params = '?' + new URLSearchParams(query).toString();40
params = params.replaceAll(/%5B/g, '[');41
params = params.replaceAll(/%5D/g, ']');42
}43
else {44
body = JSON.stringify(query);
55
return;56
}57
if(!ok) {46
reject(`[${error.kind}] ${error.message}`);58
reject(error.message);59
return;60
}61
resolve(data);
36
echo "Response"37
echo "------------------------------------------------------------"39
curl $url -I39
curl "$url" -I -g41
curl $url -s -X "${config["method"]}" -H "verbal-token: ${config["token"]}" | jq -r "."41
curl "$url" -s -g -X "${config["method"]}" -H "verbal-token: ${config["token"]}" | jq -r "."
1
{2
"scripts": {3
"build": "npx tailwindcss -i ./www/asset/css/input.css -o ./www/asset/css/style.css --minify"4
},5
"devDependencies": {6
"tailwindcss": "^3.0.23"7
}8
}
1
use serde::Deserialize;2
use std::fmt;4
use crate::error::{Error, ErrorKind, Result};5
use crate::rest;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)]14
pub struct Search {15
pub name: String,16
pub page: Option<i64>,17
}19
impl fmt::Display for Search {20
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {21
write!(22
f,23
"name={}&offset={}&limit=10&order=votes&reverse=true&hidebroken=true",24
&self.name,25
&self.page.unwrap_or(0) * 10,26
)27
}28
}30
pub struct RadioBrowserApi;32
impl RadioBrowserApi {33
pub async fn search(search: Search) -> Result<Vec<rest::Station>> {34
let uri = format!("/json/stations/search?{}", &search);35
let mut response = RadioBrowserApi::fetch(&uri).await?;36
match response.body_json::<Vec<rest::Station>>().await {37
Ok(data) => Ok(data),38
Err(err) => Err(Error::new(ErrorKind::Parse, &err.to_string())),39
}40
}42
pub async fn by_uuids(uuids: Vec<String>) -> Result<Vec<rest::Station>> {43
let uri = format!("/json/stations/byuuid?uuids={}", &uuids.join(","));44
let mut response = RadioBrowserApi::fetch(&uri).await?;45
match response.body_json::<Vec<rest::Station>>().await {46
Ok(data) => Ok(data),47
Err(err) => Err(Error::new(ErrorKind::Parse, &err.to_string())),48
}49
}51
async fn fetch(uri: &str) -> Result<surf::Response> {52
let mut successful_response = None;53
for api_url in API_URLS {54
let url = format!("{}{}", &api_url, &uri,);55
match surf::get(&url).await {56
Ok(response) => {57
successful_response = Some(response);58
break;59
}60
Err(err) => println!("{}", Error::new(ErrorKind::Fetch, &err.to_string())),61
}62
}63
match successful_response {64
Some(response) => Ok(response),65
None => Err(Error::new(ErrorKind::Fetch, "All request attempts failed!")),66
}67
}68
}
1
use serde::Deserialize;2
use std::fmt;2
use std::fmt::Write;3
use std::fs;5
use crate::error::Error;6
use crate::Result;7
use crate::ToUrl;8
use crate::APP_NAME;10
#[derive(Debug, Clone, Deserialize)]11
pub struct Server {12
pub hostname: String,13
pub port: i32,14
pub cert_path: Option<String>,15
pub key_path: Option<String>,16
pub options: Options,17
}12
impl fmt::Display for Server {13
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {14
write!(f, "{}:{}", self.hostname, self.port,)19
impl Server {20
pub fn is_tls(&self) -> bool {21
if !443.eq(&self.port) {22
return false;23
}24
if self.cert_path.is_none() || self.key_path.is_none() {25
warn!("the port 443 is usually used for TLS only!");26
return false;27
}28
true29
}30
}32
impl ToUrl for Server {33
fn to_url(&self) -> Result<String> {34
let mut url = String::new();35
write!(url, "{}:{}", self.hostname, self.port)?;36
Ok(url)37
}38
}
51
pub database: String,52
}32
impl fmt::Display for Database {33
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {54
impl ToUrl for Database {55
fn to_url(&self) -> Result<String> {56
let mut url = String::new();57
write!(35
f,58
url,59
"postgres://{}:{}@{}:{}/{}?sslmode=disable",60
self.username, self.password, self.hostname, self.port, self.database,38
)61
)?;62
Ok(url)63
}64
}
70
}72
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)73
pub fn acquire() -> Result<Self> {74
let mut config_path = match dirs::config_dir() {75
Some(config_path) => config_path,76
None => return Err(Error::new("unable to determine config path!")),77
};78
config_path.push(APP_NAME);79
config_path.push("config.toml");80
let raw = fs::read_to_string(&config_path)?;81
let config: Self = toml::from_str(&raw)?;82
Ok(config)83
}84
}
1
use serde::Deserialize;2
use serde::Serialize;4
use crate::model;5
use crate::rest;6
use crate::utils::to_array;7
use crate::utils::upgrade_to_https;9
#[derive(Debug, Default, Deserialize)]10
pub struct Song {11
pub url: String,12
}14
#[derive(Debug, Serialize)]15
pub struct Account {16
pub username: Option<String>,17
pub language: String,18
pub is_playback_history: bool,19
}21
impl From<model::Account> for Account {22
fn from(model: model::Account) -> Self {23
Self {24
username: model.username,25
language: model.language,26
is_playback_history: model.is_playback_history,27
}28
}29
}31
#[derive(Debug, Serialize)]32
pub struct Station {33
pub uuid: String,34
pub name: String,35
pub stream_url: String,36
pub votes: i32,37
pub favicon: Option<String>,38
pub homepage: Option<String>,39
pub tags: Vec<String>,40
pub country: Option<String>,41
pub languages: Vec<String>,42
pub state: Option<String>,43
pub is_favorite: bool,44
}46
impl From<model::Station> for Station {47
fn from(model: model::Station) -> Self {48
Self {49
uuid: model.uuid,50
name: model.name,51
stream_url: upgrade_to_https(model.stream_url),52
votes: model.votes,53
favicon: model.favicon,54
homepage: model.homepage,55
tags: model.tags,56
country: model.country,57
languages: model.languages,58
state: model.state,59
is_favorite: false,60
}61
}62
}64
impl From<rest::Station> for Station {65
fn from(rest: rest::Station) -> Self {66
Self {67
uuid: rest.stationuuid,68
name: rest.name,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),74
country: Some(rest.countrycode),75
languages: to_array(rest.languagecodes),76
state: Some(rest.state),77
is_favorite: false,78
}79
}80
}
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<std::fmt::Error> for Error {31
fn from(err: std::fmt::Error) -> Self {32
Self::new(&err.to_string())33
}34
}36
impl From<toml::de::Error> for Error {37
fn from(err: toml::de::Error) -> Self {38
Self::new(&err.to_string())39
}40
}
1
use env_logger::Builder;2
use env_logger::Target;3
use log::LevelFilter;5
pub mod error;6
pub mod middleware;7
pub mod model;8
pub mod route;10
mod config;11
mod response;12
mod server;14
pub use config::Config;15
pub use response::Response;16
pub use server::Server;18
use error::Error;20
#[macro_use]21
extern crate log;23
#[macro_export]24
macro_rules! abort {25
($message:expr) => {{26
error!("{}", $message);27
std::process::exit(1)28
}};29
($message:expr, $err:expr) => {{30
error!("{} Reason: {}", $message, $err);31
std::process::exit(1)32
}};33
}35
#[macro_export]36
macro_rules! unwrap_result_or_abort {37
($target:expr, $message:expr) => {{38
$target.unwrap_or_else(|err| abort!($message, &err))39
}};40
}42
#[macro_export]43
macro_rules! unwrap_option_or_abort {44
($target:expr, $message:expr) => {{45
$target.unwrap_or_else(|| abort!($message))46
}};47
}49
#[macro_export]50
macro_rules! unwrap_result_or_throw {51
($target:expr, $message:expr) => {{52
match $target {53
Ok(target) => target,54
Err(_) => {55
error!("{}", $message);56
return $crate::Response::throw($message);57
}58
}59
}};60
}62
#[macro_export]63
macro_rules! unwrap_option_or_throw {64
($target:expr, $message:expr) => {{65
match $target {66
Some(target) => target,67
None => {68
error!("{}", $message);69
return $crate::Response::throw($message);70
}71
}72
}};73
}75
pub const APP_NAME: &str = "verbal";77
pub type Result<T> = std::result::Result<T, Error>;79
pub trait ToSql {80
fn to_sql(&self) -> Result<String>;81
}83
pub trait ToUrl {84
fn to_url(&self) -> Result<String>;85
}87
pub fn init_logger() {88
Builder::new()89
.format_timestamp_secs()90
.filter_module(APP_NAME, LevelFilter::Info)91
.target(Target::Stdout)92
.init();93
}
1
use data::Song;2
use sqlx::postgres::Postgres;3
use tide_compress::CompressMiddleware;4
use tide_sqlx::SQLxMiddleware;1
use verbal::abort;2
use verbal::init_logger;3
use verbal::unwrap_result_or_abort;4
use verbal::Server;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;6
#[macro_use]7
extern crate log;9
#[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(())10
async fn main() {11
init_logger();12
let server = Server::default();13
unwrap_result_or_abort!(server.run().await, "fatal server error!");14
}
1
mod auth;2
mod cors;3
mod error;4
pub use auth::AuthMiddleware;5
pub use cors::CorsMiddleware;5
pub use auth::Auth;6
pub use cors::Cors;7
pub use error::Error;
2
use sqlx::Acquire;3
use tide_sqlx::SQLxRequestExt;5
use crate::error::ErrorKind;5
use crate::model;7
use crate::response::Response;6
use crate::unwrap_option_or_throw;7
use crate::unwrap_result_or_throw;9
pub struct AuthMiddleware {}11
impl AuthMiddleware {12
pub fn new() -> Self {13
Self {}14
}15
}9
#[derive(Default)]10
pub struct Auth;12
#[tide::utils::async_trait]18
impl<State: Clone + Send + Sync + 'static> tide::Middleware<State> for AuthMiddleware {13
impl<State: Clone + Send + Sync + 'static> tide::Middleware<State> for Auth {14
async fn handle(15
&self,16
mut req: tide::Request<State>,17
next: tide::Next<'_, State>,18
) -> tide::Result {19
if req.url().path().starts_with("/api") {25
let token = match req.header("verbal-token") {26
Some(header) => header.as_str(),27
None => {28
return Response::throw(29
ErrorKind::Identity,30
"No request header 'verbal-token' provided!",31
)32
}33
};20
let token =21
unwrap_option_or_throw!(req.header("verbal-token"), "no token was provided!")22
.as_str();23
let query = format!(24
"25
SELECT account.*26
FROM account27
INNER JOIN device28
ON account.id = device.account_id40
WHERE device.token = '{}'29
WHERE device.uid = '{}'30
",31
&token,32
);33
let option_account;34
{35
let mut conn = req.sqlx_conn::<Postgres>().await;47
option_account = sqlx::query_as::<_, model::Account>(&query)48
.fetch_optional(conn.acquire().await.unwrap())49
.await50
.unwrap()51
}52
match option_account {53
Some(account) => {54
req.set_ext(account);55
}56
None => {57
return Response::throw(58
ErrorKind::Identity,59
"No account found for provided header 'verbal-token'!",60
);61
}36
option_account = unwrap_result_or_throw!(37
sqlx::query_as::<_, model::Account>(&query)38
.fetch_optional(unwrap_result_or_throw!(39
conn.acquire().await,40
"cannot acquire connection to database!"41
))42
.await,43
"cannot acquire account for given device!"44
);45
}46
req.set_ext(unwrap_option_or_throw!(47
option_account,48
"no account found for given token!"49
));50
}51
let res = next.run(req).await;52
Ok(res)
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::Response;3
#[derive(Default)]4
pub struct Error;6
#[tide::utils::async_trait]7
impl<State: Clone + Send + Sync + 'static> tide::Middleware<State> for Error {8
async fn handle(&self, req: tide::Request<State>, next: tide::Next<'_, State>) -> tide::Result {9
let res = next.run(req).await;10
if let Some(err) = res.error() {11
error!("{}", err.to_string());12
return Response::throw(&err.to_string());13
}14
Ok(res)15
}16
}
1
use serde::Deserialize;2
use serde::Serialize;3
use sqlx::FromRow;4
use std::fmt::Write;3
#[derive(Debug, Clone, FromRow)]6
use crate::Result;7
use crate::ToSql;9
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]10
pub struct Account {11
pub id: i32,6
pub username: Option<String>,12
pub name: Option<String>,13
pub language: String,8
pub is_playback_history: bool,14
}11
#[derive(Debug, Clone, FromRow)]16
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]17
pub struct Device {18
pub id: i32,14
pub token: String,19
pub uid: String,20
pub account_id: i32,21
}18
#[derive(Debug, Clone, FromRow)]23
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]24
pub struct Station {25
pub id: i32,21
pub uuid: String,26
pub uid: String,27
pub name: String,23
pub stream_url: String,24
pub votes: i32,25
pub favicon: Option<String>,28
pub url: String,29
pub icon: Option<String>,30
pub homepage: Option<String>,27
pub tags: Vec<String>,31
pub tags: Option<Vec<String>>,32
pub country: Option<String>,29
pub languages: Vec<String>,33
pub state: Option<String>,34
pub languages: Option<Vec<String>>,35
pub score: i32,36
pub is_favorite: Option<bool>,37
}33
#[derive(Debug, FromRow)]34
pub struct Like {39
#[derive(Debug, Serialize, Deserialize, FromRow)]40
pub struct Favorite {41
pub id: i32,42
pub account_id: i32,43
pub station_id: String,44
}40
// use rand::{distributions::Alphanumeric, Rng};42
// #[derive(Debug, Deserialize, Serialize, FromRow)]43
// pub struct Code {44
// pub code: String,45
// pub used: bool,46
// pub expired: bool,47
// }46
#[derive(Debug, Default, Deserialize)]47
pub struct Query {48
pub name: String,49
pub tags: Option<Vec<String>>,50
pub country: Option<String>,51
pub language: Option<String>,52
pub page: Option<i32>,53
}49
// impl Code {50
// pub fn new() -> Self {51
// let code = rand::thread_rng()52
// .sample_iter(&Alphanumeric)53
// .take(6)54
// .map(char::from)55
// .map(|c| c.to_uppercase().to_string())56
// .collect::<String>();57
// Self { code, used: false, expired: false }58
// }59
// }55
impl ToSql for Query {56
fn to_sql(&self) -> Result<String> {57
let mut sql = String::new();58
writeln!(59
sql,60
"WHERE LOWER(station.name) LIKE LOWER('%{}%')",61
self.name62
)?;63
if let Some(tags) = &self.tags {64
write!(sql, "AND station.tags = array[")?;65
for (i, tag) in tags.iter().enumerate() {66
if i > 0 {67
write!(sql, ", ")?;68
}69
write!(sql, "LOWER('{}')", tag)?;70
}71
writeln!(sql, "]")?;72
}73
if let Some(country) = &self.country {74
writeln!(sql, "AND station.country = UPPER('{}')", country)?;75
}76
if let Some(language) = &self.language {77
writeln!(sql, "AND station.languages = array[LOWER('{}')]", language)?;78
}79
Ok(sql)80
}81
}
1
use crate::error::{Error, ErrorKind};1
use crate::error::Error;2
use crate::unwrap_result_or_throw;3
use serde::Serialize;5
#[derive(Debug, Serialize)]
12
impl Response<(), ()> {13
pub fn respond(body: Result<tide::Body, tide::Error>) -> tide::Result {13
Ok(tide::Response::builder(200).body(body.unwrap()).build())14
Ok(tide::Response::builder(200)15
.body(unwrap_result_or_throw!(16
body,17
"cannot acquire response body!"18
))19
.build())20
}21
}
34
}36
impl Response<(), Error> {31
pub fn throw(error_kind: ErrorKind, message: &str) -> tide::Result {37
pub fn throw(message: &str) -> tide::Result {38
Response::respond(tide::Body::from_json(&Self {39
ok: false,40
data: None,35
error: Some(Error::new(error_kind, message)),41
error: Some(Error::new(message)),42
}))43
}44
}
1
use serde::Deserialize;3
#[derive(Debug, Clone, Deserialize)]4
pub struct Station {5
pub stationuuid: String,6
pub name: String,7
pub url: String,8
pub votes: i32,9
pub favicon: String,10
pub homepage: String,11
pub tags: String,12
pub countrycode: String,13
pub languagecodes: String,14
pub state: String,15
}
1
use async_std::io::ReadExt;2
use regex::Regex;3
use sqlx::Acquire;4
use sqlx::Postgres;5
use tide_sqlx::SQLxRequestExt;7
use crate::model;8
use crate::unwrap_option_or_throw;9
use crate::unwrap_result_or_throw;10
use crate::Response;11
use crate::ToSql;13
pub async fn do_prefetch(_: tide::Request<()>) -> tide::Result {14
Ok(tide::Response::new(200))15
}17
pub async fn get_account(req: tide::Request<()>) -> tide::Result {18
let account =19
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");20
Response::with(account)21
}23
pub async fn do_search(req: tide::Request<()>) -> tide::Result {24
let query = req.query::<model::Query>()?;25
let account =26
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");27
let sql = format!(28
r#"29
SELECT30
station.*,31
CASE32
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}33
THEN false34
ELSE true35
END AS is_favorite36
FROM station37
LEFT JOIN favorite38
ON station.id = favorite.station_id39
{conditions}40
OFFSET {offset}41
LIMIT 1042
"#,43
account_id = account.id,44
offset = query.page.unwrap_or_default() * 10,45
conditions = unwrap_result_or_throw!(query.to_sql(), "cannot parse sql statement!"),46
);47
let mut conn = req.sqlx_conn::<Postgres>().await;48
let result = sqlx::query_as::<_, model::Station>(&sql)49
.fetch_all(conn.acquire().await?)50
.await?;51
Response::with(result)52
}54
pub async fn get_song(req: tide::Request<()>) -> tide::Result {55
let station = req.query::<model::Station>()?;56
let mut response = surf::get(&station.url).header("icy-metadata", "1").await?;57
let meta_int = match response.header("icy-metaint") {58
Some(header) => header.as_str(),59
None => return Response::throw("no icy metadata header found!"),60
};61
let interval = match meta_int.parse::<usize>() {62
Ok(interval) => interval * 2,63
Err(_) => return Response::throw("icy metadata interval is not a number!"),64
};65
let mut total = 0;66
let mut bytes = Vec::new();67
let mut buf = [0; 10000];68
let mut title = None;69
loop {70
let len =71
unwrap_result_or_throw!(response.read(&mut buf).await, "cannot read stream data!");72
bytes.extend_from_slice(&buf);73
if total + len > interval {74
let metadata = String::from_utf8_lossy(&bytes);75
if let Some(cap) =76
unwrap_result_or_throw!(Regex::new("StreamTitle='([^;]*)';"), "cannot parse regex!")77
.captures_iter(&metadata)78
.next()79
{80
title = Some(cap[1].to_string());81
}82
break;83
}84
if total > interval * 2 {85
warn!("too many iterations while acquiring song title!");86
break;87
}88
total += len;89
}90
Response::with(title)91
}93
pub async fn get_favorites(req: tide::Request<()>) -> tide::Result {94
let account =95
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");96
let sql = format!(97
r#"98
SELECT99
station.*,100
true as is_favorite101
FROM station102
LEFT JOIN favorite103
ON station.id = favorite.station_id104
WHERE favorite.account_id = {account_id}105
"#,106
account_id = account.id,107
);108
let mut conn = req.sqlx_conn::<Postgres>().await;109
let result = sqlx::query_as::<_, model::Station>(&sql)110
.fetch_all(conn.acquire().await?)111
.await?;112
Response::with(result)113
}115
pub async fn add_favorite(mut req: tide::Request<()>) -> tide::Result {116
let station_id = req.body_json::<i32>().await?;117
let account =118
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");119
let sql = format!(120
r#"121
INSERT INTO122
favorite123
(account_id, station_id)124
VALUES125
({account_id}, {station_id})126
"#,127
account_id = account.id,128
station_id = station_id,129
);130
let mut conn = req.sqlx_conn::<Postgres>().await;131
sqlx::query(&sql).execute(conn.acquire().await?).await?;132
Response::with(())133
}135
pub async fn delete_favorite(mut req: tide::Request<()>) -> tide::Result {136
let station_id = req.body_json::<i32>().await?;137
let account =138
unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");139
let sql = format!(140
r#"141
DELETE FROM142
favorite143
WHERE account_id = {account_id}144
AND station_id = {station_id}145
"#,146
account_id = account.id,147
station_id = station_id,148
);149
let mut conn = req.sqlx_conn::<Postgres>().await;150
sqlx::query(&sql).execute(conn.acquire().await?).await?;151
Response::with(())152
}
1
use sqlx::postgres::Postgres;2
use tide_compress::CompressMiddleware;3
use tide_rustls::TlsListener;4
use tide_sqlx::SQLxMiddleware;6
use crate::abort;7
use crate::middleware::Auth;8
use crate::middleware::Cors;9
use crate::middleware::Error;10
use crate::route;11
use crate::unwrap_option_or_abort;12
use crate::unwrap_result_or_abort;13
use crate::Config;14
use crate::Result;15
use crate::ToUrl;17
#[derive(Default)]18
pub struct Server;20
impl Server {21
pub async fn run(&self) -> Result<()> {22
let config = unwrap_result_or_abort!(Config::acquire(), "cannot acquire config!");23
let mut app = tide::new();25
/* bind middleware */26
app.with(Error::default());27
app.with(unwrap_result_or_abort!(28
SQLxMiddleware::<Postgres>::new(&unwrap_result_or_abort!(29
config.database.to_url(),30
"cannot parse database address!"31
))32
.await,33
"cannot connect to database!"34
));35
app.with(Auth::default());36
app.with(Cors::new(&config.server.options.origin));37
app.with(CompressMiddleware::new());39
/* serve content */40
app.at("/").serve_file("www/index.html")?;41
app.at("/asset").serve_dir("www/asset/")?;42
app.at("/app").serve_dir("app/")?;44
/* handle prefetch */45
app.at("*").options(route::do_prefetch);47
/* handle api requests */48
app.at("/api/account").get(route::get_account);49
app.at("/api/search").get(route::do_search);50
app.at("/api/song").get(route::get_song);51
app.at("/api/favorite").get(route::get_favorites);52
app.at("/api/favorite").post(route::add_favorite);53
app.at("/api/favorite").delete(route::delete_favorite);55
let address =56
unwrap_result_or_abort!(config.server.to_url(), "cannot parse server address!");57
info!("starting server on {}", address);58
let listener = if config.server.is_tls() {59
app.listen(60
TlsListener::build()61
.addrs(&address)62
.cert(unwrap_option_or_abort!(63
config.server.cert_path,64
"no certificate for TLS found!"65
))66
.key(unwrap_option_or_abort!(67
config.server.key_path,68
"no key for TLS found!"69
)),70
)71
.await72
} else {73
app.listen(address).await74
};75
unwrap_result_or_abort!(listener, "cannot start server!");76
Ok(())77
}78
}
1
use async_std::io::ReadExt;2
use regex::Regex;3
use sqlx::postgres::Postgres;4
use sqlx::prelude::*;5
use tide_sqlx::SQLxRequestExt;7
use crate::api::{RadioBrowserApi, Search};8
use crate::data::{self, Song};9
use crate::error::{Error, ErrorKind, Result};10
use crate::model;12
pub struct Service {}14
impl Service {15
pub async fn search(search: Search, req: tide::Request<()>) -> Result<Vec<data::Station>> {16
let account = req.ext::<model::Account>().unwrap();17
let rest = match RadioBrowserApi::search(search).await {18
Ok(rest) => rest,19
Err(err) => return Err(err),20
};21
let query = format!(22
"23
SELECT *24
FROM \"like\"25
WHERE \"like\".account_id = '{}'26
",27
&account.id,28
);29
let mut conn = req.sqlx_conn::<Postgres>().await;30
let likes = sqlx::query_as::<_, model::Like>(&query)31
.fetch_all(conn.acquire().await.unwrap())32
.await33
.unwrap();34
let data = rest35
.iter()36
.cloned()37
.map(|item| {38
let mut data: data::Station = item.clone().into();39
data.is_favorite = likes.iter().any(|like| like.station_id == item.stationuuid);40
data41
})42
.collect::<Vec<data::Station>>();43
Ok(data)44
}46
pub async fn get_song(song: Song) -> Result<Option<String>> {47
let mut response = match surf::get(&song.url).header("icy-metadata", "1").await {48
Ok(response) => response,49
Err(_) => return Err(Error::new(ErrorKind::Fetch, "Unable to fetch metadata!")),50
};51
let meta_int = match response.header("icy-metaint") {52
Some(header) => header.as_str(),53
None => return Err(Error::new(ErrorKind::Parse, "Invalid icy metadata!")),54
};55
let interval = match meta_int.parse::<usize>() {56
Ok(value) => value * 2,57
Err(_) => {58
return Err(Error::new(59
ErrorKind::Parse,60
"Unable to parse icy metadata!",61
))62
}63
};64
let mut count = 0;65
let mut bytes = vec![];66
let mut buf = [0; 10000];67
let mut data = None;68
loop {69
let len = response.read(&mut buf).await.unwrap();70
bytes.extend_from_slice(&buf);71
if count + len > interval {72
let metadata = String::from_utf8_lossy(&bytes);73
for cap in Regex::new("StreamTitle='([^;]*)';")74
.unwrap()75
.captures_iter(&metadata)76
{77
data = Some(cap[1].to_string());78
break;79
}80
break;81
}82
count += len;83
}84
Ok(data)85
}87
pub async fn get_likes(req: tide::Request<()>) -> Result<Vec<data::Station>> {88
let account = req.ext::<model::Account>().unwrap();89
let query = format!(90
"91
SELECT *92
FROM \"like\"93
WHERE account_id = '{}'94
ORDER BY created_at DESC95
",96
&account.id,97
);98
let mut conn = req.sqlx_conn::<Postgres>().await;99
let likes = sqlx::query_as::<_, model::Like>(&query)100
.fetch_all(conn.acquire().await.unwrap())101
.await102
.unwrap();103
let uuids = likes104
.iter()105
.map(|like| &like.station_id)106
.cloned()107
.collect::<Vec<String>>();108
let rests = match RadioBrowserApi::by_uuids(uuids).await {109
Ok(rest) => rest,110
Err(err) => return Err(err),111
};112
let mut data = vec![];113
for like in likes {114
for rest in &rests {115
if like.station_id.eq(&rest.stationuuid) {116
let mut item: data::Station = rest.clone().into();117
item.is_favorite = true;118
data.push(item);119
break;120
}121
}122
}123
Ok(data)124
}126
pub async fn add_like(mut req: tide::Request<()>) -> Result<()> {127
let uuid = match req.body_json::<String>().await {128
Ok(body) => body,129
Err(_) => {130
return Err(Error::new(131
ErrorKind::Arguments,132
"No station uuid provided!",133
))134
}135
};136
let account = req.ext::<model::Account>().unwrap();137
let query = format!(138
"139
INSERT INTO \"like\"140
(account_id, station_id)141
VALUES142
({}, '{}')143
",144
&account.id, &uuid,145
);146
let mut conn = req.sqlx_conn::<Postgres>().await;147
match sqlx::query(&query)148
.execute(conn.acquire().await.unwrap())149
.await150
{151
Ok(_) => Ok(()),152
Err(err) => Err(Error::new(ErrorKind::Query, &err.to_string())),153
}154
}156
pub async fn remove_like(mut req: tide::Request<()>) -> Result<()> {157
let uuid = match req.body_json::<String>().await {158
Ok(body) => body,159
Err(_) => {160
return Err(Error::new(161
ErrorKind::Arguments,162
"No station uuid provided!",163
))164
}165
};166
let account = req.ext::<model::Account>().unwrap();167
let query = format!(168
"169
DELETE FROM \"like\"170
WHERE account_id = {}171
AND station_id = '{}'172
",173
&account.id, &uuid,174
);175
let mut conn = req.sqlx_conn::<Postgres>().await;176
match sqlx::query(&query)177
.execute(conn.acquire().await.unwrap())178
.await179
{180
Ok(_) => Ok(()),181
Err(err) => Err(Error::new(ErrorKind::Query, &err.to_string())),182
}183
}184
}
1
use regex::Regex;3
pub fn to_array(value: String) -> Vec<String> {4
value5
.split(',')6
.map(str::to_string)7
.filter(|tag| !tag.trim().is_empty())8
.collect::<Vec<String>>()9
}11
pub fn upgrade_to_https(url: String) -> String {12
if Regex::new("^http://").unwrap().is_match(&url) {13
return format!("https://verbal.fm/api/upgrade?redirect={}", &url);14
}15
url16
}