extract API logic into generic functions, and wrap REST API around

This commit is contained in:
Oystein Kristoffer Tveit 2024-04-15 23:24:47 +02:00
parent bc1a386b80
commit f5cb5480a7
Signed by: oysteikt
GPG Key ID: 9F2F7D8250F35146
5 changed files with 371 additions and 343 deletions

View File

@ -1,310 +1,4 @@
use std::sync::Arc;
use tokio::sync::Mutex;
mod base;
mod rest_wrapper;
use axum::{
extract::{Query, State},
response::IntoResponse,
routing::{delete, get, post},
Json, Router,
};
use mpvipc::{
Mpv, NumberChangeOptions, Playlist, PlaylistAddOptions, PlaylistAddTypeOptions, SeekOptions,
Switch,
};
use serde::Deserialize;
use serde_json::{json, Value};
type Result<T, E = crate::app_error::AppError> = std::result::Result<T, E>;
pub fn api_routes(mpv: Mpv) -> Router {
Router::new()
.route("/", get(index))
.route("/load", post(loadfile))
.route("/play", get(play_get))
.route("/play", post(play_set))
.route("/volume", get(volume_get))
.route("/volume", post(volume_set))
.route("/time", get(time_get))
.route("/time", post(time_set))
.route("/playlist", get(playlist_get))
.route("/playlist/next", post(playlist_next))
.route("/playlist/previous", post(playlist_previous))
.route("/playlist/goto", post(playlist_goto))
.route("/playlist/remove", delete(playlist_remove_or_clear))
.route("/playlist/move", post(playlist_goto))
.route("/playlist/shuffle", post(shuffle))
.route("/playlist/loop", get(playlist_get_looping))
.route("/playlist/loop", post(playlist_set_looping))
.with_state(Arc::new(Mutex::new(mpv)))
}
async fn index() -> &'static str {
"Hello friend, I hope you're having a lovely day"
}
#[derive(Debug, Deserialize)]
struct APIRequestLoadFile {
// Link to the resource to enqueue
path: String,
}
/// Add item to playlist
async fn loadfile(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(request): Query<APIRequestLoadFile>,
) -> Result<impl IntoResponse> {
log::trace!("POST /load {:?}", request);
mpv.lock().await.playlist_add(
request.path.as_str(),
PlaylistAddTypeOptions::File,
PlaylistAddOptions::Append,
)?;
Ok(Json(json!({
"status": "true".to_string(),
"error": false,
})))
}
/// Check whether the player is paused or playing
async fn play_get(State(mpv): State<Arc<Mutex<Mpv>>>) -> Result<impl IntoResponse> {
log::trace!("GET /play");
let paused: bool = mpv.lock().await.get_property("pause")?;
Ok(Json(json!({
"value": paused,
"error": false,
})))
}
#[derive(Debug, Deserialize)]
struct APIRequestPlay {
value: bool,
}
/// Set whether the player is paused or playing
async fn play_set(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(request): Query<APIRequestPlay>,
) -> Result<impl IntoResponse> {
log::trace!("POST /play {:?}", request);
mpv.lock().await.set_property("pause", request.value)?;
Ok(Json(json!({
"error": false,
})))
}
/// Get the current player volume
async fn volume_get(State(mpv): State<Arc<Mutex<Mpv>>>) -> Result<impl IntoResponse> {
log::trace!("GET /volume");
let volume: f64 = mpv.lock().await.get_property("volume")?;
Ok(Json(json!({
"value": volume,
"error": false,
})))
}
#[derive(Debug, Deserialize)]
struct APIRequestVolume {
value: f64,
}
/// Set the player volume
async fn volume_set(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(request): Query<APIRequestVolume>,
) -> Result<impl IntoResponse> {
log::trace!("POST /volume {:?}", request);
mpv.lock()
.await
.set_volume(request.value, NumberChangeOptions::Absolute)?;
Ok(Json(json!({
"error": false,
})))
}
/// Get current playback position
async fn time_get(State(mpv): State<Arc<Mutex<Mpv>>>) -> Result<impl IntoResponse> {
log::trace!("GET /time");
let current: f64 = mpv.lock().await.get_property("time-pos")?;
let remaining: f64 = mpv.lock().await.get_property("time-remaining")?;
let total = current + remaining;
Ok(Json(json!({
"value": {
"current": current,
"remaining": remaining,
"total": total,
},
"error": false,
})))
}
#[derive(Debug, Deserialize)]
struct APIRequestTime {
pos: Option<f64>,
percent: Option<f64>,
}
/// Set playback position
async fn time_set(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(request): Query<APIRequestTime>,
) -> Result<impl IntoResponse> {
log::trace!("POST /time {:?}", request);
if request.pos.is_some() && request.percent.is_some() {
return Err(crate::app_error::AppError(anyhow::anyhow!(
"pos and percent cannot be provided at the same time"
)));
}
if let Some(pos) = request.pos {
mpv.lock().await.seek(pos, SeekOptions::Absolute)?;
} else if let Some(percent) = request.percent {
mpv.lock()
.await
.seek(percent, SeekOptions::AbsolutePercent)?;
} else {
return Err(crate::app_error::AppError(anyhow::anyhow!(
"Either pos or percent must be provided"
)));
};
Ok(Json(json!({
"error": false,
})))
}
/// Get the current playlist
async fn playlist_get(State(mpv): State<Arc<Mutex<Mpv>>>) -> Result<impl IntoResponse> {
log::trace!("GET /playlist");
let playlist: Playlist = mpv.lock().await.get_playlist()?;
let is_playing: bool = mpv.lock().await.get_property("pause")?;
let items: Vec<Value> = playlist
.0
.iter()
.enumerate()
.map(|(i, item)| {
json!({
"index": i,
"current": item.current,
"playing": is_playing,
"filename": item.filename,
"data": {
"fetching": true,
}
})
})
.collect();
Ok(Json(json!({
"value": items,
"error": false,
})))
}
/// Skip to the next item in the playlist
async fn playlist_next(State(mpv): State<Arc<Mutex<Mpv>>>) -> Result<impl IntoResponse> {
log::trace!("POST /playlist/next");
Ok(Json(json!({
"status": mpv.lock().await.next().is_ok().to_string(),
"error": false,
})))
}
/// Go back to the previous item in the playlist
async fn playlist_previous(State(mpv): State<Arc<Mutex<Mpv>>>) -> Result<impl IntoResponse> {
log::trace!("POST /playlist/previous");
Ok(Json(json!({
"status": mpv.lock().await.prev().is_ok().to_string(),
"error": false,
})))
}
#[derive(Debug, Deserialize)]
struct APIRequestPlaylistGoto {
index: usize,
}
/// Go chosen item in the playlist
async fn playlist_goto(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(request): Query<APIRequestPlaylistGoto>,
) -> Result<impl IntoResponse> {
log::trace!("POST /playlist/goto {:?}", request);
Ok(Json(json!({
"status": mpv.lock().await.playlist_play_id(request.index).is_ok().to_string(),
"error": false,
})))
}
/// Clears single item or whole playlist
async fn playlist_remove_or_clear(State(mpv): State<Arc<Mutex<Mpv>>>) -> Result<impl IntoResponse> {
log::trace!("DELETE /playlist/remove");
Ok(Json(json!({
"status": mpv.lock().await.playlist_clear().is_ok().to_string(),
"error": false,
})))
}
/// Shuffle the playlist
async fn shuffle(State(mpv): State<Arc<Mutex<Mpv>>>) -> Result<impl IntoResponse> {
log::trace!("POST /playlist/shuffle");
Ok(Json(json!({
"status": mpv.lock().await.playlist_shuffle().is_ok().to_string(),
"error": false,
})))
}
/// See whether it loops the playlist or not
async fn playlist_get_looping(State(mpv): State<Arc<Mutex<Mpv>>>) -> Result<impl IntoResponse> {
log::trace!("GET /playlist/loop");
// TODO: this needs to be updated in the next version of the API
// let loop_file: bool = mpv.lock().await.get_property("loop-file").unwrap();
let loop_playlist: bool = mpv.lock().await.get_property("loop-playlist")?;
Ok(Json(json!({
"value": loop_playlist,
"error": false,
})))
}
#[derive(Debug, Deserialize)]
struct APIRequestPlaylistSetLooping {
r#loop: bool,
}
async fn playlist_set_looping(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(request): Query<APIRequestPlaylistSetLooping>,
) -> Result<impl IntoResponse> {
log::trace!("POST /playlist/loop {:?}", request);
if request.r#loop {
mpv.lock().await.set_loop_playlist(Switch::On)?;
} else {
mpv.lock().await.set_loop_playlist(Switch::Off)?;
}
Ok(Json(json!({
"status": request.r#loop.to_string(),
"error": false,
})))
}
pub use rest_wrapper::rest_api_routes;

182
src/api/base.rs Normal file
View File

@ -0,0 +1,182 @@
use std::sync::Arc;
use mpvipc::{
Mpv, NumberChangeOptions, PlaylistAddOptions, PlaylistAddTypeOptions, SeekOptions, Switch,
};
use serde_json::json;
use tokio::sync::Mutex;
/// Add item to playlist
pub async fn loadfile(mpv: Arc<Mutex<Mpv>>, path: &str) -> anyhow::Result<()> {
mpv.lock().await.playlist_add(
path,
PlaylistAddTypeOptions::File,
PlaylistAddOptions::Append,
)?;
Ok(())
}
/// Check whether the player is paused or playing
pub async fn play_get(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<serde_json::Value> {
let paused: bool = mpv.lock().await.get_property("pause")?;
Ok(json!({
"value": paused,
}))
}
/// Set whether the player is paused or playing
pub async fn play_set(mpv: Arc<Mutex<Mpv>>, value: bool) -> anyhow::Result<()> {
mpv.lock().await.set_property("pause", value)?;
Ok(())
}
/// Get the current player volume
pub async fn volume_get(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<serde_json::Value> {
let volume: f64 = mpv.lock().await.get_property("volume")?;
Ok(json!({
"value": volume,
}))
}
/// Set the player volume
pub async fn volume_set(
mpv: Arc<Mutex<Mpv>>,
// Query(request): Query<APIRequestVolume>,
value: f64,
) -> anyhow::Result<()> {
mpv.lock()
.await
.set_volume(value, NumberChangeOptions::Absolute)?;
Ok(())
}
/// Get current playback position
pub async fn time_get(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<serde_json::Value> {
let current: f64 = mpv.lock().await.get_property("time-pos")?;
let remaining: f64 = mpv.lock().await.get_property("time-remaining")?;
let total = current + remaining;
Ok(json!({
"value": {
"current": current,
"remaining": remaining,
"total": total,
},
}))
}
/// Set playback position
pub async fn time_set(
mpv: Arc<Mutex<Mpv>>,
pos: Option<f64>,
percent: Option<f64>,
) -> anyhow::Result<()> {
if pos.is_some() && percent.is_some() {
anyhow::bail!("pos and percent cannot be provided at the same time");
}
if let Some(pos) = pos {
mpv.lock().await.seek(pos, SeekOptions::Absolute)?;
} else if let Some(percent) = percent {
mpv.lock()
.await
.seek(percent, SeekOptions::AbsolutePercent)?;
} else {
anyhow::bail!("Either pos or percent must be provided");
};
Ok(())
}
/// Get the current playlist
pub async fn playlist_get(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<serde_json::Value> {
let playlist: mpvipc::Playlist = mpv.lock().await.get_playlist()?;
let is_playing: bool = mpv.lock().await.get_property("pause")?;
let items: Vec<serde_json::Value> = playlist
.0
.iter()
.enumerate()
.map(|(i, item)| {
json!({
"index": i,
"current": item.current,
"playing": is_playing,
"filename": item.filename,
"data": {
"fetching": true,
}
})
})
.collect();
Ok(json!({
"value": items,
}))
}
/// Skip to the next item in the playlist
pub async fn playlist_next(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<serde_json::Value> {
Ok(json!({
"status": mpv.lock().await.next().is_ok().to_string(),
}))
}
/// Go back to the previous item in the playlist
pub async fn playlist_previous(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<serde_json::Value> {
Ok(json!({
"status": mpv.lock().await.prev().is_ok().to_string(),
}))
}
/// Go chosen item in the playlist
pub async fn playlist_goto(
mpv: Arc<Mutex<Mpv>>,
index: usize,
) -> anyhow::Result<serde_json::Value> {
Ok(json!({
"status": mpv.lock().await.playlist_play_id(index).is_ok().to_string(),
}))
}
/// Clears single item or whole playlist
pub async fn playlist_remove_or_clear(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<serde_json::Value> {
Ok(json!({
"status": mpv.lock().await.playlist_clear().is_ok().to_string(),
}))
}
/// Shuffle the playlist
pub async fn shuffle(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<serde_json::Value> {
Ok(json!({
"status": mpv.lock().await.playlist_shuffle().is_ok().to_string(),
}))
}
/// See whether it loops the playlist or not
pub async fn playlist_get_looping(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<serde_json::Value> {
let loop_playlist: bool = mpv.lock().await.get_property("loop-playlist")?;
Ok(json!({
"value": loop_playlist,
}))
}
pub async fn playlist_set_looping(
mpv: Arc<Mutex<Mpv>>,
r#loop: bool,
) -> anyhow::Result<serde_json::Value> {
if r#loop {
mpv.lock().await.set_loop_playlist(Switch::On)?;
} else {
mpv.lock().await.set_loop_playlist(Switch::Off)?;
}
Ok(json!({
"status": r#loop.to_string(),
}))
}

177
src/api/rest_wrapper.rs Normal file
View File

@ -0,0 +1,177 @@
use std::sync::Arc;
use axum::{
extract::{Query, State},
http::StatusCode,
response::IntoResponse,
routing::{delete, get, post},
Json, Router,
};
use mpvipc::Mpv;
use tokio::sync::Mutex;
use super::base;
pub fn rest_api_routes(mpv: Arc<Mutex<Mpv>>) -> Router {
Router::new()
// .route("/", get(index))
.route("/load", post(loadfile))
.route("/play", get(play_get))
.route("/play", post(play_set))
.route("/volume", get(volume_get))
.route("/volume", post(volume_set))
.route("/time", get(time_get))
.route("/time", post(time_set))
.route("/playlist", get(playlist_get))
.route("/playlist/next", post(playlist_next))
.route("/playlist/previous", post(playlist_previous))
.route("/playlist/goto", post(playlist_goto))
.route("/playlist/remove", delete(playlist_remove_or_clear))
.route("/playlist/move", post(playlist_goto))
.route("/playlist/shuffle", post(shuffle))
.route("/playlist/loop", get(playlist_get_looping))
.route("/playlist/loop", post(playlist_set_looping))
.with_state(mpv)
}
pub struct RestResponse(anyhow::Result<serde_json::Value>);
impl From<anyhow::Result<serde_json::Value>> for RestResponse {
fn from(result: anyhow::Result<serde_json::Value>) -> Self {
Self(result)
}
}
impl From<anyhow::Result<()>> for RestResponse {
fn from(result: anyhow::Result<()>) -> Self {
Self(result.map(|_| serde_json::json!({ "status": "ok", "error": false })))
}
}
impl IntoResponse for RestResponse {
fn into_response(self) -> axum::response::Response {
match self.0 {
Ok(value) => (StatusCode::OK, Json(value)).into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Internal server error: {}", err),
)
.into_response(),
}
}
}
// -------------------//
// Boilerplate galore //
// -------------------//
// TODO: These could possibly be generated with a proc macro
#[derive(serde::Deserialize)]
struct LoadFileArgs {
path: String,
}
async fn loadfile(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(query): Query<LoadFileArgs>,
) -> RestResponse {
base::loadfile(mpv, &query.path).await.into()
}
async fn play_get(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::play_get(mpv).await.into()
}
#[derive(serde::Deserialize)]
struct PlaySetArgs {
value: bool,
}
async fn play_set(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(query): Query<PlaySetArgs>,
) -> RestResponse {
base::play_set(mpv, query.value).await.into()
}
async fn volume_get(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::volume_get(mpv).await.into()
}
#[derive(serde::Deserialize)]
struct VolumeSetArgs {
value: f64,
}
async fn volume_set(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(query): Query<VolumeSetArgs>,
) -> RestResponse {
base::volume_set(mpv, query.value).await.into()
}
async fn time_get(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::time_get(mpv).await.into()
}
#[derive(serde::Deserialize)]
struct TimeSetArgs {
pos: Option<f64>,
percent: Option<f64>,
}
async fn time_set(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(query): Query<TimeSetArgs>,
) -> RestResponse {
base::time_set(mpv, query.pos, query.percent).await.into()
}
async fn playlist_get(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::playlist_get(mpv).await.into()
}
async fn playlist_next(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::playlist_next(mpv).await.into()
}
async fn playlist_previous(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::playlist_previous(mpv).await.into()
}
#[derive(serde::Deserialize)]
struct PlaylistGotoArgs {
index: usize,
}
async fn playlist_goto(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(query): Query<PlaylistGotoArgs>,
) -> RestResponse {
base::playlist_goto(mpv, query.index).await.into()
}
async fn playlist_remove_or_clear(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::playlist_remove_or_clear(mpv).await.into()
}
async fn shuffle(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::shuffle(mpv).await.into()
}
async fn playlist_get_looping(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::playlist_get_looping(mpv).await.into()
}
#[derive(serde::Deserialize)]
struct PlaylistSetLoopingArgs {
value: bool,
}
async fn playlist_set_looping(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(query): Query<PlaylistSetLoopingArgs>,
) -> RestResponse {
base::playlist_set_looping(mpv, query.value).await.into()
}

View File

@ -1,29 +0,0 @@
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
// Make our own error that wraps `anyhow::Error`.
pub struct AppError(pub anyhow::Error);
// Tell axum how to convert `AppError` into a response.
impl IntoResponse for AppError {
fn into_response(self) -> Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", self.0),
)
.into_response()
}
}
// This enables using `?` on functions that return `Result<_, anyhow::Error>` to turn them into
// `Result<_, AppError>`. That way you don't need to do that manually.
impl<E> From<E> for AppError
where
E: Into<anyhow::Error>,
{
fn from(err: E) -> Self {
Self(err.into())
}
}

View File

@ -6,11 +6,14 @@ use std::{
fs::create_dir_all,
net::{IpAddr, SocketAddr},
path::Path,
sync::Arc,
};
use tokio::{
process::{Child, Command},
sync::Mutex,
};
use tokio::process::{Child, Command};
mod api;
mod app_error;
#[derive(Parser)]
struct Args {
@ -121,8 +124,8 @@ async fn resolve(host: &str) -> anyhow::Result<IpAddr> {
let addr = format!("{}:0", host);
let addresses = tokio::net::lookup_host(addr).await?;
addresses
.filter(|addr| addr.is_ipv4())
.next()
.into_iter()
.find(|addr| addr.is_ipv4())
.map(|addr| addr.ip())
.ok_or_else(|| anyhow::anyhow!("Failed to resolve address"))
}
@ -143,7 +146,8 @@ async fn main() -> anyhow::Result<()> {
let addr = SocketAddr::new(resolve(&args.host).await?, args.port);
log::info!("Starting API on {}", addr);
let app = Router::new().nest("/api", api::api_routes(mpv));
let mpv = Arc::new(Mutex::new(mpv));
let app = Router::new().nest("/api", api::rest_api_routes(mpv));
if let Some(mut proc) = proc {
tokio::select! {