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"
17
dirs = "4.0.0"18
env_logger = "0.9.0"19
log = "0.4.17"22
reqwest = { version = "0.11.11", features = ["json"] }20
surf = "2.3.2"
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
>
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
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
use serde::Deserialize;2
use std::fmt;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",10
"https://fr1.api.radio-browser.info",11
"https://nl1.api.radio-browser.info",12
];14
#[derive(Debug, Default, Deserialize)]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 {34
pub async fn search(search: Search) -> Result<Vec<rest::Station>> {35
let uri = format!("/json/stations/search?{}", &search);36
let mut response = RadioBrowserApi::fetch(&uri).await?;37
match response.body_json::<Vec<rest::Station>>().await {38
Ok(data) => Ok(data),39
Err(err) => Err(Error::new(&err.to_string())),40
}41
}43
pub async fn by_uuids(uuids: Vec<String>) -> Result<Vec<rest::Station>> {44
let uri = format!("/json/stations/byuuid?uuids={}", &uuids.join(","));45
let mut response = RadioBrowserApi::fetch(&uri).await?;46
match response.body_json::<Vec<rest::Station>>().await {47
Ok(data) => Ok(data),48
Err(err) => Err(Error::new(&err.to_string())),49
}50
}52
async fn fetch(uri: &str) -> Result<surf::Response> {53
let mut successful_response = None;54
for api_url in API_URLS {55
let url = format!("{}{}", &api_url, &uri,);56
match surf::get(&url).await {57
Ok(response) => {58
successful_response = Some(response);59
break;60
}61
Err(err) => println!("{}", Error::new(&err.to_string())),62
}63
}64
match successful_response {65
Some(response) => Ok(response),66
None => Err(Error::new("All request attempts failed!")),67
}68
}69
}
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
}
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())
3
use log::LevelFilter;4
use std::process;6
pub mod api;7
pub mod data;6
pub mod error;7
pub mod middleware;8
pub mod model;11
pub mod rest;9
pub mod route;10
pub mod utils;12
mod config;13
mod response;14
mod server;17
mod service;16
pub use config::Config;17
pub use response::Response;18
pub use server::Server;22
pub use service::Service;20
use error::Error;
27
pub type Result<T> = std::result::Result<T, Error>;29
pub trait IntoSql {30
fn into_sql(self) -> Result<String>;31
}33
pub fn init_logger() {34
Builder::new()35
.format_timestamp_secs()
1
mod auth;2
mod cors;3
mod error;5
pub use auth::Auth;6
pub use cors::Cors;7
pub use error::Error;
26
FROM account27
INNER JOIN device28
ON account.id = device.account_id29
WHERE device.token = '{}'29
WHERE device.uid = '{}'30
",31
&token,32
);
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::IntoSql;7
use crate::Result;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>,31
pub tags: Vec<String>,32
pub country: Option<String>,29
pub languages: Vec<String>,33
pub state: Option<String>,34
pub languages: 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 IntoSql for Query {56
fn into_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 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::IntoSql;9
use crate::Response;11
pub async fn do_prefetch(_: tide::Request<()>) -> tide::Result {12
Ok(tide::Response::new(200))13
}15
pub async fn get_account(req: tide::Request<()>) -> tide::Result {16
let account = req.ext::<model::Account>().unwrap();17
Response::with(account)18
}20
pub async fn do_search(req: tide::Request<()>) -> tide::Result {21
let query = req.query::<model::Query>()?;22
let account = req.ext::<model::Account>().unwrap();23
let sql = format!(24
r#"25
SELECT26
station.*,27
CASE28
WHEN favorite.id IS NULL OR favorite.account_id != {account_id}29
THEN false30
ELSE true31
END AS is_favorite32
FROM station33
LEFT JOIN favorite34
ON station.id = favorite.station_id35
{conditions}36
OFFSET {offset}37
LIMIT 1038
"#,39
account_id = account.id,40
offset = query.page.unwrap_or_default() * 10,41
conditions = query.into_sql().unwrap(),42
);43
let mut conn = req.sqlx_conn::<Postgres>().await;44
let result = sqlx::query_as::<_, model::Station>(&sql)45
.fetch_all(conn.acquire().await?)46
.await?;47
Response::with(result)48
}50
pub async fn get_song(req: tide::Request<()>) -> tide::Result {51
let station = req.query::<model::Station>()?;52
let mut response = surf::get(&station.url).header("icy-metadata", "1").await?;53
let meta_int = match response.header("icy-metaint") {54
Some(header) => header.as_str(),55
None => return Response::throw("no icy metadata header found!"),56
};57
let interval = match meta_int.parse::<usize>() {58
Ok(interval) => interval * 2,59
Err(_) => return Response::throw("icy metadata interval is not a number!"),60
};61
let mut total = 0;62
let mut bytes = Vec::new();63
let mut buf = [0; 10000];64
let mut title = None;65
loop {66
let len = response.read(&mut buf).await.unwrap();67
bytes.extend_from_slice(&buf);68
if total + len > interval {69
let metadata = String::from_utf8_lossy(&bytes);70
if let Some(cap) = Regex::new("StreamTitle='([^;]*)';")71
.unwrap()72
.captures_iter(&metadata)73
.next()74
{75
title = Some(cap[1].to_string());76
}77
break;78
}79
if total > interval * 2 {80
warn!("too many iterations while acquiring song title!");81
break;82
}83
total += len;84
}85
Response::with(title)86
}88
pub async fn get_favorites(req: tide::Request<()>) -> tide::Result {89
let account = req.ext::<model::Account>().unwrap();90
let sql = format!(91
r#"92
SELECT93
station.*,94
true as is_favorite95
FROM station96
LEFT JOIN favorite97
ON station.id = favorite.station_id98
WHERE favorite.account_id = {account_id}99
"#,100
account_id = account.id,101
);102
let mut conn = req.sqlx_conn::<Postgres>().await;103
let result = sqlx::query_as::<_, model::Station>(&sql)104
.fetch_all(conn.acquire().await?)105
.await?;106
Response::with(result)107
}109
pub async fn add_favorite(mut req: tide::Request<()>) -> tide::Result {110
let station_id = req.body_json::<i32>().await?;111
let account = req.ext::<model::Account>().unwrap();112
let sql = format!(113
r#"114
INSERT INTO115
favorite116
(account_id, station_id)117
VALUES118
({account_id}, {station_id})119
"#,120
account_id = account.id,121
station_id = station_id,122
);123
let mut conn = req.sqlx_conn::<Postgres>().await;124
sqlx::query(&sql).execute(conn.acquire().await?).await?;125
Response::with(())126
}128
pub async fn delete_favorite(mut req: tide::Request<()>) -> tide::Result {129
let station_id = req.body_json::<i32>().await?;130
let account = req.ext::<model::Account>().unwrap();131
let sql = format!(132
r#"133
DELETE FROM134
favorite135
WHERE account_id = {account_id}136
AND station_id = {station_id}137
"#,138
account_id = account.id,139
station_id = station_id,140
);141
let mut conn = req.sqlx_conn::<Postgres>().await;142
sqlx::query(&sql).execute(conn.acquire().await?).await?;143
Response::with(())144
}
3
use tide_sqlx::SQLxMiddleware;5
use crate::abort;6
use crate::api::Search;7
use crate::data;6
use crate::middleware::Auth;7
use crate::middleware::Cors;10
use crate::model;8
use crate::middleware::Error;9
use crate::route;10
use crate::Config;12
use crate::Response;11
use crate::Result;14
use crate::Service;13
#[derive(Default)]17
pub struct Server {}14
pub struct Server;16
impl Server {17
pub async fn run(&self) -> Result<()> {
19
let mut app = tide::new();21
/* bind middleware */25
app.with(Auth::default());26
app.with(Cors::new(&config.server.options.origin));27
app.with(CompressMiddleware::new());22
app.with(Error::default());23
app.with(24
SQLxMiddleware::<Postgres>::new(&config.database.to_string())25
.await26
.unwrap(),27
);34
/* handle prefetch */35
app.at("*")36
.options(|_: tide::Request<()>| async move { Ok(tide::Response::new(200)) });28
app.with(Auth::default());29
app.with(Cors::new(&config.server.options.origin));30
app.with(CompressMiddleware::new());32
/* serve content */33
app.at("/").serve_file("www/index.html")?;34
app.at("/asset").serve_dir("www/asset/")?;35
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
});37
/* handle prefetch */38
app.at("*").options(route::do_prefetch);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
});40
/* handle api requests */41
app.at("/api/account").get(route::get_account);42
app.at("/api/search").get(route::do_search);43
app.at("/api/song").get(route::get_song);44
app.at("/api/favorite").get(route::get_favorites);45
app.at("/api/favorite").post(route::add_favorite);46
app.at("/api/favorite").delete(route::delete_favorite);48
app.listen(&config.server.to_string()).await?;49
Ok(())50
}51
}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
}
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;10
use crate::model;11
use crate::Result;13
pub struct Service {}15
impl Service {16
pub async fn search(search: Search, req: tide::Request<()>) -> Result<Vec<data::Station>> {17
let account = req.ext::<model::Account>().unwrap();18
let rest = match RadioBrowserApi::search(search).await {19
Ok(rest) => rest,20
Err(err) => return Err(err),21
};22
let query = format!(23
"24
SELECT *25
FROM \"like\"26
WHERE \"like\".account_id = '{}'27
",28
&account.id,29
);30
let mut conn = req.sqlx_conn::<Postgres>().await;31
let likes = sqlx::query_as::<_, model::Like>(&query)32
.fetch_all(conn.acquire().await.unwrap())33
.await34
.unwrap();35
let data = rest36
.iter()37
.cloned()38
.map(|item| {39
let mut data: data::Station = item.clone().into();40
data.is_favorite = likes.iter().any(|like| like.station_id == item.stationuuid);41
data42
})43
.collect::<Vec<data::Station>>();44
Ok(data)45
}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,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(),54
None => return Err(Error::new("Invalid icy metadata!")),55
};56
let interval = match meta_int.parse::<usize>() {57
Ok(value) => value * 2,58
Err(_) => return Err(Error::new("Unable to parse icy metadata!")),59
};60
let mut count = 0;61
let mut bytes = vec![];62
let mut buf = [0; 10000];63
let mut data = None;64
loop {65
let len = response.read(&mut buf).await.unwrap();66
bytes.extend_from_slice(&buf);67
if count + len > interval {68
let metadata = String::from_utf8_lossy(&bytes);69
if let Some(cap) = Regex::new("StreamTitle='([^;]*)';")70
.unwrap()71
.captures_iter(&metadata)72
.next()73
{74
data = Some(cap[1].to_string());75
}76
break;77
}78
count += len;79
}80
Ok(data)81
}83
pub async fn get_likes(req: tide::Request<()>) -> Result<Vec<data::Station>> {84
let account = req.ext::<model::Account>().unwrap();85
let query = format!(86
"87
SELECT *88
FROM \"like\"89
WHERE account_id = '{}'90
ORDER BY created_at DESC91
",92
&account.id,93
);94
let mut conn = req.sqlx_conn::<Postgres>().await;95
let likes = sqlx::query_as::<_, model::Like>(&query)96
.fetch_all(conn.acquire().await.unwrap())97
.await98
.unwrap();99
let uuids = likes100
.iter()101
.map(|like| &like.station_id)102
.cloned()103
.collect::<Vec<String>>();104
let rests = match RadioBrowserApi::by_uuids(uuids).await {105
Ok(rest) => rest,106
Err(err) => return Err(err),107
};108
let mut data = vec![];109
for like in likes {110
for rest in &rests {111
if like.station_id.eq(&rest.stationuuid) {112
let mut item: data::Station = rest.clone().into();113
item.is_favorite = true;114
data.push(item);115
break;116
}117
}118
}119
Ok(data)120
}122
pub async fn add_like(mut req: tide::Request<()>) -> Result<()> {123
let uuid = match req.body_json::<String>().await {124
Ok(body) => body,125
Err(_) => return Err(Error::new("No station uuid provided!")),126
};127
let account = req.ext::<model::Account>().unwrap();128
let query = format!(129
"130
INSERT INTO \"like\"131
(account_id, station_id)132
VALUES133
({}, '{}')134
",135
&account.id, &uuid,136
);137
let mut conn = req.sqlx_conn::<Postgres>().await;138
match sqlx::query(&query)139
.execute(conn.acquire().await.unwrap())140
.await141
{142
Ok(_) => Ok(()),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,150
Err(_) => return Err(Error::new("No station uuid provided!")),151
};152
let account = req.ext::<model::Account>().unwrap();153
let query = format!(154
"155
DELETE FROM \"like\"156
WHERE account_id = {}157
AND station_id = '{}'158
",159
&account.id, &uuid,160
);161
let mut conn = req.sqlx_conn::<Postgres>().await;162
match sqlx::query(&query)163
.execute(conn.acquire().await.unwrap())164
.await165
{166
Ok(_) => Ok(()),167
Err(err) => Err(Error::new(&err.to_string())),168
}169
}170
}
1
pub fn to_array(value: &str) -> Vec<String> {2
value3
.split(',')4
.map(str::to_string)5
.filter(|tag| !tag.trim().is_empty())6
.collect::<Vec<String>>()7
}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
}13
url.to_string()14
}