1 Commits

Author SHA1 Message Date
9838d8e8f0 WIP: aide OpenAPI docs 2024-04-16 18:21:26 +02:00
9 changed files with 547 additions and 645 deletions

1
.envrc
View File

@@ -1 +0,0 @@
use flake

625
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -6,15 +6,26 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
aide = { version = "0.13.3", features = [
"axum",
"axum-extra",
"axum-extra-query",
"axum-ws",
"macros",
"scalar",
] }
anyhow = "1.0.82" anyhow = "1.0.82"
axum = { version = "0.6.20", features = ["macros"] } axum = { version = "0.6.20", features = ["macros", "ws"] }
axum-jsonschema = { version = "0.8.0", features = ["aide"] }
axum-macros = "0.4.1"
clap = { version = "4.4.1", features = ["derive"] } clap = { version = "4.4.1", features = ["derive"] }
env_logger = "0.10.0" env_logger = "0.10.0"
futures = "0.3.30"
log = "0.4.20" log = "0.4.20"
mpvipc-async = { path = "../mpvipc-async" } mpvipc = "1.3.0"
schemars = "0.8.16"
serde = { version = "1.0.188", features = ["derive"] } serde = { version = "1.0.188", features = ["derive"] }
serde_json = "1.0.105" serde_json = "1.0.105"
serde_urlencoded = "0.7.1"
tokio = { version = "1.32.0", features = ["full"] } tokio = { version = "1.32.0", features = ["full"] }
tower = { version = "0.4.13", features = ["full"] } tower = { version = "0.4.13", features = ["full"] }
tower-http = { version = "0.4.3", features = ["full"] } tower-http = { version = "0.4.3", features = ["full"] }

View File

@@ -1,3 +1,24 @@
# Greg-ng # Greg-ng
New implementation of https://github.com/Programvareverkstedet/grzegorz New implementation of https://github.com/Programvareverkstedet/grzegorz
## Feature wishlist
- [ ] Feature parity with old grzegorz
- [X] Rest API
- [ ] Rest API docs
- [ ] Metadata fetcher
- [ ] Init mpv with image of grzegorz
- [ ] Save playlists to machine
- [ ] Cache playlist contents to disk
- [ ] Expose service through mpd protocol
- [ ] Users with playlists and songs (and auth?)
- [ ] Some kind of fair scheduling for each user
- [ ] Max time to avoid playlist songs
- [ ] Expose video/media stream so others can listen at home
- [ ] Syncope support >:)
- [ ] Jitsi support >:)))
- [ ] Show other media while playing music, like grafana or bustimes
- [ ] Soft shuffle
- [ ] Libre.fm integration
- [ ] Karaoke mode lmao

48
flake.lock generated
View File

@@ -1,48 +0,0 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1722421184,
"narHash": "sha256-/DJBI6trCeVnasdjUo9pbnodCLZcFqnVZiLUfqLH4jA=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "9f918d616c5321ad374ae6cb5ea89c9e04bf3e58",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs",
"rust-overlay": "rust-overlay"
}
},
"rust-overlay": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1722651535,
"narHash": "sha256-2uRmNwxe3CO5h7PfvqXrRe8OplXaEdwhqOUtaF13rpU=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "56d83ca6f3c557647476f3720426a7615c22b860",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

View File

@@ -1,41 +0,0 @@
{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
rust-overlay.url = "github:oxalica/rust-overlay";
rust-overlay.inputs.nixpkgs.follows = "nixpkgs";
};
outputs = { self, nixpkgs, rust-overlay }:
let
systems = [
"x86_64-linux"
"aarch64-linux"
"x86_64-darwin"
"aarch64-darwin"
"armv7l-linux"
];
forAllSystems = f: nixpkgs.lib.genAttrs systems (system: let
pkgs = import nixpkgs {
inherit system;
overlays = [
(import rust-overlay)
];
};
rust-bin = rust-overlay.lib.mkRustBin { } pkgs.buildPackages;
toolchain = rust-bin.stable.latest.default;
in f system pkgs toolchain);
in {
devShells = forAllSystems (system: pkgs: toolchain: {
default = pkgs.mkShell {
nativeBuildInputs = [
toolchain
pkgs.mpv
];
RUST_SRC_PATH = "${toolchain}/lib/rustlib/src/rust/library";
};
});
};
}

View File

@@ -1,61 +1,62 @@
use mpvipc_async::{ use std::sync::Arc;
LoopProperty, Mpv, MpvExt, NumberChangeOptions, PlaylistAddOptions, PlaylistAddTypeOptions,
SeekOptions, Switch, use log::trace;
use mpvipc::{
Mpv, NumberChangeOptions, PlaylistAddOptions, PlaylistAddTypeOptions, SeekOptions, Switch,
}; };
use serde_json::{json, Value}; use serde_json::{json, Value};
use tokio::sync::Mutex;
/// Add item to playlist /// Add item to playlist
pub async fn loadfile(mpv: Mpv, path: &str) -> anyhow::Result<()> { pub async fn loadfile(mpv: Arc<Mutex<Mpv>>, path: &str) -> anyhow::Result<()> {
log::trace!("api::loadfile({:?})", path); trace!("api::loadfile({:?})", path);
mpv.playlist_add( mpv.lock().await.playlist_add(
path, path,
PlaylistAddTypeOptions::File, PlaylistAddTypeOptions::File,
PlaylistAddOptions::Append, PlaylistAddOptions::Append,
) )?;
.await?;
Ok(()) Ok(())
} }
/// Check whether the player is paused or playing /// Check whether the player is paused or playing
pub async fn play_get(mpv: Mpv) -> anyhow::Result<Value> { pub async fn play_get(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<Value> {
log::trace!("api::play_get()"); trace!("api::play_get()");
let paused: bool = !mpv.is_playing().await?; let paused: bool = mpv.lock().await.get_property("pause")?;
Ok(json!(!paused)) Ok(json!(!paused))
} }
/// Set whether the player is paused or playing /// Set whether the player is paused or playing
pub async fn play_set(mpv: Mpv, should_play: bool) -> anyhow::Result<()> { pub async fn play_set(mpv: Arc<Mutex<Mpv>>, should_play: bool) -> anyhow::Result<()> {
log::trace!("api::play_set({:?})", should_play); trace!("api::play_set({:?})", should_play);
mpv.set_playback(if should_play { Switch::On } else { Switch::Off }) mpv.lock()
.await .await
.set_property("pause", !should_play)
.map_err(|e| e.into()) .map_err(|e| e.into())
} }
/// Get the current player volume /// Get the current player volume
pub async fn volume_get(mpv: Mpv) -> anyhow::Result<Value> { pub async fn volume_get(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<Value> {
log::trace!("api::volume_get()"); trace!("api::volume_get()");
let volume: f64 = mpv.get_volume().await?; let volume: f64 = mpv.lock().await.get_property("volume")?;
Ok(json!(volume)) Ok(json!(volume))
} }
/// Set the player volume /// Set the player volume
pub async fn volume_set(mpv: Mpv, value: f64) -> anyhow::Result<()> { pub async fn volume_set(mpv: Arc<Mutex<Mpv>>, value: f64) -> anyhow::Result<()> {
log::trace!("api::volume_set({:?})", value); trace!("api::volume_set({:?})", value);
mpv.set_volume(value, NumberChangeOptions::Absolute) mpv.lock()
.await .await
.set_volume(value, NumberChangeOptions::Absolute)
.map_err(|e| e.into()) .map_err(|e| e.into())
} }
/// Get current playback position /// Get current playback position
pub async fn time_get(mpv: Mpv) -> anyhow::Result<Value> { pub async fn time_get(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<Value> {
log::trace!("api::time_get()"); trace!("api::time_get()");
let current: Option<f64> = mpv.get_time_pos().await?; let current: f64 = mpv.lock().await.get_property("time-pos")?;
let remaining: Option<f64> = mpv.get_time_remaining().await?; let remaining: f64 = mpv.lock().await.get_property("time-remaining")?;
let total = match (current, remaining) { let total = current + remaining;
(Some(c), Some(r)) => Some(c + r),
(_, _) => None,
};
Ok(json!({ Ok(json!({
"current": current, "current": current,
@@ -65,16 +66,22 @@ pub async fn time_get(mpv: Mpv) -> anyhow::Result<Value> {
} }
/// Set playback position /// Set playback position
pub async fn time_set(mpv: Mpv, pos: Option<f64>, percent: Option<f64>) -> anyhow::Result<()> { pub async fn time_set(
log::trace!("api::time_set({:?}, {:?})", pos, percent); mpv: Arc<Mutex<Mpv>>,
pos: Option<f64>,
percent: Option<f64>,
) -> anyhow::Result<()> {
trace!("api::time_set({:?}, {:?})", pos, percent);
if pos.is_some() && percent.is_some() { if pos.is_some() && percent.is_some() {
anyhow::bail!("pos and percent cannot be provided at the same time"); anyhow::bail!("pos and percent cannot be provided at the same time");
} }
if let Some(pos) = pos { if let Some(pos) = pos {
mpv.seek(pos, SeekOptions::Absolute).await?; mpv.lock().await.seek(pos, SeekOptions::Absolute)?;
} else if let Some(percent) = percent { } else if let Some(percent) = percent {
mpv.seek(percent, SeekOptions::AbsolutePercent).await?; mpv.lock()
.await
.seek(percent, SeekOptions::AbsolutePercent)?;
} else { } else {
anyhow::bail!("Either pos or percent must be provided"); anyhow::bail!("Either pos or percent must be provided");
}; };
@@ -83,10 +90,10 @@ pub async fn time_set(mpv: Mpv, pos: Option<f64>, percent: Option<f64>) -> anyho
} }
/// Get the current playlist /// Get the current playlist
pub async fn playlist_get(mpv: Mpv) -> anyhow::Result<Value> { pub async fn playlist_get(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<Value> {
log::trace!("api::playlist_get()"); trace!("api::playlist_get()");
let playlist: mpvipc_async::Playlist = mpv.get_playlist().await?; let playlist: mpvipc::Playlist = mpv.lock().await.get_playlist()?;
let is_playing: bool = mpv.is_playing().await?; let is_playing: bool = mpv.lock().await.get_property("pause")?;
let items: Vec<Value> = playlist let items: Vec<Value> = playlist
.0 .0
@@ -97,7 +104,7 @@ pub async fn playlist_get(mpv: Mpv) -> anyhow::Result<Value> {
"index": i, "index": i,
"current": item.current, "current": item.current,
"playing": is_playing, "playing": is_playing,
"filename": item.title.as_ref().unwrap_or(&item.filename), "filename": item.filename,
"data": { "data": {
"fetching": true, "fetching": true,
} }
@@ -109,64 +116,74 @@ pub async fn playlist_get(mpv: Mpv) -> anyhow::Result<Value> {
} }
/// Skip to the next item in the playlist /// Skip to the next item in the playlist
pub async fn playlist_next(mpv: Mpv) -> anyhow::Result<()> { pub async fn playlist_next(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<()> {
log::trace!("api::playlist_next()"); trace!("api::playlist_next()");
mpv.next().await.map_err(|e| e.into()) mpv.lock().await.next().map_err(|e| e.into())
} }
/// Go back to the previous item in the playlist /// Go back to the previous item in the playlist
pub async fn playlist_previous(mpv: Mpv) -> anyhow::Result<()> { pub async fn playlist_previous(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<()> {
log::trace!("api::playlist_previous()"); trace!("api::playlist_previous()");
mpv.prev().await.map_err(|e| e.into()) mpv.lock().await.prev().map_err(|e| e.into())
} }
/// Go chosen item in the playlist /// Go chosen item in the playlist
pub async fn playlist_goto(mpv: Mpv, index: usize) -> anyhow::Result<()> { pub async fn playlist_goto(mpv: Arc<Mutex<Mpv>>, index: usize) -> anyhow::Result<()> {
log::trace!("api::playlist_goto({:?})", index); trace!("api::playlist_goto({:?})", index);
mpv.playlist_play_id(index).await.map_err(|e| e.into()) mpv.lock()
.await
.playlist_play_id(index)
.map_err(|e| e.into())
} }
/// Clears the playlist /// Clears the playlist
pub async fn playlist_clear(mpv: Mpv) -> anyhow::Result<()> { pub async fn playlist_clear(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<()> {
log::trace!("api::playlist_clear()"); trace!("api::playlist_clear()");
mpv.playlist_clear().await.map_err(|e| e.into()) mpv.lock().await.playlist_clear().map_err(|e| e.into())
} }
/// Remove an item from the playlist by index /// Remove an item from the playlist by index
pub async fn playlist_remove(mpv: Mpv, index: usize) -> anyhow::Result<()> { pub async fn playlist_remove(mpv: Arc<Mutex<Mpv>>, index: usize) -> anyhow::Result<()> {
log::trace!("api::playlist_remove({:?})", index); trace!("api::playlist_remove({:?})", index);
mpv.playlist_remove_id(index).await.map_err(|e| e.into()) mpv.lock()
.await
.playlist_remove_id(index)
.map_err(|e| e.into())
} }
/// Move an item in the playlist from one index to another /// Move an item in the playlist from one index to another
pub async fn playlist_move(mpv: Mpv, from: usize, to: usize) -> anyhow::Result<()> { pub async fn playlist_move(mpv: Arc<Mutex<Mpv>>, from: usize, to: usize) -> anyhow::Result<()> {
log::trace!("api::playlist_move({:?}, {:?})", from, to); trace!("api::playlist_move({:?}, {:?})", from, to);
mpv.playlist_move_id(from, to).await.map_err(|e| e.into()) mpv.lock()
.await
.playlist_move_id(from, to)
.map_err(|e| e.into())
} }
/// Shuffle the playlist /// Shuffle the playlist
pub async fn shuffle(mpv: Mpv) -> anyhow::Result<()> { pub async fn shuffle(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<()> {
log::trace!("api::shuffle()"); trace!("api::shuffle()");
mpv.playlist_shuffle().await.map_err(|e| e.into()) mpv.lock().await.playlist_shuffle().map_err(|e| e.into())
} }
/// See whether it loops the playlist or not /// See whether it loops the playlist or not
pub async fn playlist_get_looping(mpv: Mpv) -> anyhow::Result<Value> { pub async fn playlist_get_looping(mpv: Arc<Mutex<Mpv>>) -> anyhow::Result<Value> {
log::trace!("api::playlist_get_looping()"); trace!("api::playlist_get_looping()");
let loop_playlist = mpv.lock().await.get_property_string("loop-playlist")? == "inf";
let loop_status = match mpv.playlist_is_looping().await? { Ok(json!(loop_playlist))
LoopProperty::No => false,
LoopProperty::Inf => true,
LoopProperty::N(_) => true,
};
Ok(json!(loop_status))
} }
pub async fn playlist_set_looping(mpv: Mpv, r#loop: bool) -> anyhow::Result<()> { pub async fn playlist_set_looping(mpv: Arc<Mutex<Mpv>>, r#loop: bool) -> anyhow::Result<()> {
log::trace!("api::playlist_set_looping({:?})", r#loop); trace!("api::playlist_set_looping({:?})", r#loop);
if r#loop {
mpv.set_loop_playlist(if r#loop { Switch::On } else { Switch::Off }) mpv.lock()
.await .await
.map_err(|e| e.into()) .set_loop_playlist(Switch::On)
.map_err(|e| e.into())
} else {
mpv.lock()
.await
.set_loop_playlist(Switch::Off)
.map_err(|e| e.into())
}
} }

View File

@@ -1,36 +1,26 @@
use std::{ops::Deref, sync::Arc};
use aide::{axum::IntoApiResponse, operation::OperationIo, OperationOutput};
use axum_jsonschema::JsonSchemaRejection;
use axum::{ use axum::{
extract::{Query, State}, async_trait, extract::{rejection::{FailedToDeserializeQueryString, QueryRejection}, FromRequest, FromRequestParts, State}, http::{request::Parts, StatusCode}, response::{IntoResponse, Response}, routing::{delete, get, post}, Json, Router
http::StatusCode,
response::{IntoResponse, Response},
routing::{delete, get, post},
Json, Router,
}; };
use mpvipc_async::Mpv; use mpvipc::Mpv;
use schemars::JsonSchema;
use serde::{de::DeserializeOwned, Serialize};
use serde_json::{json, Value}; use serde_json::{json, Value};
use tokio::sync::Mutex;
use super::base; use super::base;
pub fn rest_api_routes(mpv: Mpv) -> Router { // #[derive(FromRequest, OperationIo)]
Router::new() // #[from_request(via(axum_jsonschema::Json), rejection(RestResponse))]
.route("/load", post(loadfile)) // #[aide(
.route("/play", get(play_get)) // input_with = "axum_jsonschema::Json<T>",
.route("/play", post(play_set)) // output_with = "axum_jsonschema::Json<T>",
.route("/volume", get(volume_get)) // json_schema
.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", delete(playlist_remove_or_clear))
.route("/playlist/move", post(playlist_move))
.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<Value>); pub struct RestResponse(anyhow::Result<Value>);
impl From<anyhow::Result<Value>> for RestResponse { impl From<anyhow::Result<Value>> for RestResponse {
@@ -51,100 +41,203 @@ impl IntoResponse for RestResponse {
Ok(value) => (StatusCode::OK, Json(value)).into_response(), Ok(value) => (StatusCode::OK, Json(value)).into_response(),
Err(err) => ( Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ "error": err.to_string(), "errortext": err.to_string(), "success": false })), Json(json!({ "error": err.to_string(), "success": false })),
) )
.into_response(), .into_response(),
} }
} }
} }
impl aide::OperationOutput for RestResponse {
type Inner = anyhow::Result<Value>;
}
/// -------
// impl<T> aide::OperationInput for Query<T> {}
// #[derive(FromRequest, OperationIo)]
// #[from_request(via(axum_jsonschema::Json), rejection(RestResponse))]
// #[aide(
// input_with = "axum_jsonschema::Json<T>",
// output_with = "axum_jsonschema::Json<T>",
// json_schema
// )]
// pub struct Json<T>(pub T);
// impl<T> IntoResponse for Json<T>
// where
// T: Serialize,
// {
// fn into_response(self) -> axum::response::Response {
// axum::Json(self.0).into_response()
// }
// }
#[derive(OperationIo)]
#[aide(json_schema)]
pub struct Query<T>(pub T);
#[async_trait]
impl <T, S> FromRequestParts<S> for Query<T>
where
T: JsonSchema + DeserializeOwned,
S: Send + Sync,
{
type Rejection = QueryRejection;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let axum::extract::Query(query) = axum::extract::Query::try_from_uri(&parts.uri)?;
Ok(Query(query))
}
}
impl<T> Deref for Query<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub fn rest_api_route_docs(mpv: Arc<Mutex<Mpv>>) -> Router {
use aide::axum::ApiRouter;
use aide::axum::routing::{delete, get, post};
let mut api = aide::openapi::OpenApi::default();
let x = ApiRouter::new()
// .api_route("/load", get(loadfile))
.api_route("/play", get(play_get))
.finish_api(&mut api);
// .with_state(mpv);
todo!()
}
// ----------
pub fn rest_api_routes(mpv: Arc<Mutex<Mpv>>) -> Router {
Router::new()
.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", delete(playlist_remove_or_clear))
.route("/playlist/move", post(playlist_move))
.route("/playlist/shuffle", post(shuffle))
.route("/playlist/loop", get(playlist_get_looping))
.route("/playlist/loop", post(playlist_set_looping))
.with_state(mpv)
}
// -------------------// // -------------------//
// Boilerplate galore // // Boilerplate galore //
// -------------------// // -------------------//
// TODO: These could possibly be generated with a proc macro // TODO: These could possibly be generated with a proc macro
#[derive(serde::Deserialize)] #[derive(serde::Deserialize, JsonSchema)]
struct LoadFileArgs { struct LoadFileArgs {
path: String, path: String,
} }
async fn loadfile(State(mpv): State<Mpv>, Query(query): Query<LoadFileArgs>) -> RestResponse { #[axum::debug_handler]
async fn loadfile(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(query): Query<LoadFileArgs>,
) -> RestResponse {
base::loadfile(mpv, &query.path).await.into() base::loadfile(mpv, &query.path).await.into()
} }
async fn play_get(State(mpv): State<Mpv>) -> RestResponse { async fn play_get(State(mpv): State<Arc<Mutex<Mpv>>>) -> impl IntoApiResponse {
base::play_get(mpv).await.into() RestResponse::from(base::play_get(mpv).await)
} }
#[derive(serde::Deserialize)] #[derive(serde::Deserialize, JsonSchema)]
struct PlaySetArgs { struct PlaySetArgs {
play: String, play: String,
} }
async fn play_set(State(mpv): State<Mpv>, Query(query): Query<PlaySetArgs>) -> RestResponse { async fn play_set(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(query): Query<PlaySetArgs>,
) -> RestResponse {
let play = query.play.to_lowercase() == "true"; let play = query.play.to_lowercase() == "true";
base::play_set(mpv, play).await.into() base::play_set(mpv, play).await.into()
} }
async fn volume_get(State(mpv): State<Mpv>) -> RestResponse { async fn volume_get(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::volume_get(mpv).await.into() base::volume_get(mpv).await.into()
} }
#[derive(serde::Deserialize)] #[derive(serde::Deserialize, JsonSchema)]
struct VolumeSetArgs { struct VolumeSetArgs {
volume: f64, volume: f64,
} }
async fn volume_set(State(mpv): State<Mpv>, Query(query): Query<VolumeSetArgs>) -> RestResponse { async fn volume_set(
State(mpv): State<Arc<Mutex<Mpv>>>,
Query(query): Query<VolumeSetArgs>,
) -> RestResponse {
base::volume_set(mpv, query.volume).await.into() base::volume_set(mpv, query.volume).await.into()
} }
async fn time_get(State(mpv): State<Mpv>) -> RestResponse { async fn time_get(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::time_get(mpv).await.into() base::time_get(mpv).await.into()
} }
#[derive(serde::Deserialize)] #[derive(serde::Deserialize, JsonSchema)]
struct TimeSetArgs { struct TimeSetArgs {
pos: Option<f64>, pos: Option<f64>,
percent: Option<f64>, percent: Option<f64>,
} }
async fn time_set(State(mpv): State<Mpv>, Query(query): Query<TimeSetArgs>) -> RestResponse { 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() base::time_set(mpv, query.pos, query.percent).await.into()
} }
async fn playlist_get(State(mpv): State<Mpv>) -> RestResponse { async fn playlist_get(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::playlist_get(mpv).await.into() base::playlist_get(mpv).await.into()
} }
async fn playlist_next(State(mpv): State<Mpv>) -> RestResponse { async fn playlist_next(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::playlist_next(mpv).await.into() base::playlist_next(mpv).await.into()
} }
async fn playlist_previous(State(mpv): State<Mpv>) -> RestResponse { async fn playlist_previous(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::playlist_previous(mpv).await.into() base::playlist_previous(mpv).await.into()
} }
#[derive(serde::Deserialize)] #[derive(serde::Deserialize, JsonSchema)]
struct PlaylistGotoArgs { struct PlaylistGotoArgs {
index: usize, index: usize,
} }
async fn playlist_goto( async fn playlist_goto(
State(mpv): State<Mpv>, State(mpv): State<Arc<Mutex<Mpv>>>,
Query(query): Query<PlaylistGotoArgs>, Query(query): Query<PlaylistGotoArgs>,
) -> RestResponse { ) -> RestResponse {
base::playlist_goto(mpv, query.index).await.into() base::playlist_goto(mpv, query.index).await.into()
} }
#[derive(serde::Deserialize)] #[derive(serde::Deserialize, JsonSchema)]
struct PlaylistRemoveOrClearArgs { struct PlaylistRemoveOrClearArgs {
index: Option<usize>, index: Option<usize>,
} }
async fn playlist_remove_or_clear( async fn playlist_remove_or_clear(
State(mpv): State<Mpv>, State(mpv): State<Arc<Mutex<Mpv>>>,
Query(query): Query<PlaylistRemoveOrClearArgs>, Query(query): Query<PlaylistRemoveOrClearArgs>,
) -> RestResponse { ) -> RestResponse {
match query.index { match query.index {
@@ -153,14 +246,14 @@ async fn playlist_remove_or_clear(
} }
} }
#[derive(serde::Deserialize)] #[derive(serde::Deserialize, JsonSchema)]
struct PlaylistMoveArgs { struct PlaylistMoveArgs {
index1: usize, index1: usize,
index2: usize, index2: usize,
} }
async fn playlist_move( async fn playlist_move(
State(mpv): State<Mpv>, State(mpv): State<Arc<Mutex<Mpv>>>,
Query(query): Query<PlaylistMoveArgs>, Query(query): Query<PlaylistMoveArgs>,
) -> RestResponse { ) -> RestResponse {
base::playlist_move(mpv, query.index1, query.index2) base::playlist_move(mpv, query.index1, query.index2)
@@ -168,21 +261,21 @@ async fn playlist_move(
.into() .into()
} }
async fn shuffle(State(mpv): State<Mpv>) -> RestResponse { async fn shuffle(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::shuffle(mpv).await.into() base::shuffle(mpv).await.into()
} }
async fn playlist_get_looping(State(mpv): State<Mpv>) -> RestResponse { async fn playlist_get_looping(State(mpv): State<Arc<Mutex<Mpv>>>) -> RestResponse {
base::playlist_get_looping(mpv).await.into() base::playlist_get_looping(mpv).await.into()
} }
#[derive(serde::Deserialize)] #[derive(serde::Deserialize, JsonSchema)]
struct PlaylistSetLoopingArgs { struct PlaylistSetLoopingArgs {
r#loop: bool, r#loop: bool,
} }
async fn playlist_set_looping( async fn playlist_set_looping(
State(mpv): State<Mpv>, State(mpv): State<Arc<Mutex<Mpv>>>,
Query(query): Query<PlaylistSetLoopingArgs>, Query(query): Query<PlaylistSetLoopingArgs>,
) -> RestResponse { ) -> RestResponse {
base::playlist_set_looping(mpv, query.r#loop).await.into() base::playlist_set_looping(mpv, query.r#loop).await.into()

View File

@@ -1,16 +1,20 @@
use anyhow::Context; use anyhow::Context;
use axum::{Router, Server}; use axum::{Router, Server};
use clap::Parser; use clap::Parser;
use futures::StreamExt; use mpvipc::Mpv;
use mpvipc_async::{parse_property, Mpv, MpvExt, Switch};
use std::{ use std::{
fs::create_dir_all, fs::create_dir_all,
net::{IpAddr, SocketAddr}, net::{IpAddr, SocketAddr},
path::Path, path::Path,
sync::Arc,
};
use tokio::{
process::{Child, Command},
sync::Mutex,
}; };
use tokio::process::{Child, Command};
mod api; mod api;
mod mpv_broker;
#[derive(Parser)] #[derive(Parser)]
struct Args { struct Args {
@@ -81,9 +85,9 @@ async fn connect_to_mpv(args: &MpvConnectionArgs) -> anyhow::Result<(Mpv, Option
.arg(format!("--input-ipc-server={}", &args.socket_path)) .arg(format!("--input-ipc-server={}", &args.socket_path))
.arg("--idle") .arg("--idle")
.arg("--force-window") .arg("--force-window")
.arg("--fullscreen") // .arg("--fullscreen")
// .arg("--no-terminal") // .arg("--no-terminal")
.arg("--load-unsafe-playlists") // .arg("--load-unsafe-playlists")
.arg("--keep-open") // Keep last frame of video on end of video .arg("--keep-open") // Keep last frame of video on end of video
.spawn() .spawn()
.context("Failed to start mpv")?, .context("Failed to start mpv")?,
@@ -109,7 +113,7 @@ async fn connect_to_mpv(args: &MpvConnectionArgs) -> anyhow::Result<(Mpv, Option
} }
Ok(( Ok((
Mpv::connect(&args.socket_path).await.context(format!( Mpv::connect(&args.socket_path).context(format!(
"Failed to connect to mpv socket: {}", "Failed to connect to mpv socket: {}",
&args.socket_path &args.socket_path
))?, ))?,
@@ -143,64 +147,25 @@ async fn main() -> anyhow::Result<()> {
let addr = SocketAddr::new(resolve(&args.host).await?, args.port); let addr = SocketAddr::new(resolve(&args.host).await?, args.port);
log::info!("Starting API on {}", addr); log::info!("Starting API on {}", addr);
let app = Router::new().nest("/api", api::rest_api_routes(mpv.clone())); let mpv = Arc::new(Mutex::new(mpv));
let app = Router::new().nest("/api", api::rest_api_routes(mpv));
if let Some(mut proc) = proc { if let Some(mut proc) = proc {
tokio::select! { tokio::select! {
exit_status = proc.wait() => { exit_status = proc.wait() => {
log::warn!("mpv process exited with status: {}", exit_status?); log::warn!("mpv process exited with status: {}", exit_status?);
mpv.disconnect().await?;
}
_ = tokio::signal::ctrl_c() => {
log::info!("Received Ctrl-C, exiting");
mpv.disconnect().await?;
proc.kill().await?;
}
/* DEBUG */
_ = async {
let mut event_stream = mpv.get_event_stream().await;
mpv.set_playback(Switch::Off).await.unwrap();
mpv.observe_property(1, "volume").await.unwrap();
mpv.observe_property(2, "pause").await.unwrap();
mpv.observe_property(3, "time-pos").await.unwrap();
mpv.observe_property(4, "duration").await.unwrap();
mpv.observe_property(5, "playlist").await.unwrap();
mpv.observe_property(6, "playlist-pos").await.unwrap();
mpv.observe_property(7, "tick").await.unwrap();
mpv.observe_property(8, "eof-reached").await.unwrap();
mpv.observe_property(9, "speed").await.unwrap();
mpv.observe_property(10, "filename").await.unwrap();
mpv.observe_property(11, "media-title").await.unwrap();
mpv.observe_property(12, "loop-file").await.unwrap();
mpv.observe_property(13, "loop-playlist").await.unwrap();
mpv.observe_property(14, "mute").await.unwrap();
loop {
let event = event_stream.next().await;
if let Some(Ok(event)) = event {
match &event {
mpvipc_async::Event::PropertyChange { name, data, id } => {
let parsed_event_property = parse_property(name, data.clone());
log::info!("PropertyChange({}): {:#?}", id, parsed_event_property);
}
event => {
log::info!("Event: {:?}", event);
}
}
}
}
} => {
} }
/* END_DEBUG */ _ = tokio::signal::ctrl_c() => {
result = async { log::info!("Received Ctrl-C, exiting");
proc.kill().await?;
}
result = async {
match Server::try_bind(&addr.clone()).context("Failed to bind server") { match Server::try_bind(&addr.clone()).context("Failed to bind server") {
Ok(server) => server.serve(app.into_make_service()).await.context("Failed to serve app"), Ok(server) => server.serve(app.into_make_service()).await.context("Failed to serve app"),
Err(err) => Err(err), Err(err) => Err(err),
} }
} => { } => {
log::info!("API server exited"); log::info!("API server exited");
mpv.disconnect().await?;
proc.kill().await?; proc.kill().await?;
result?; result?;
} }
@@ -209,11 +174,9 @@ async fn main() -> anyhow::Result<()> {
tokio::select! { tokio::select! {
_ = tokio::signal::ctrl_c() => { _ = tokio::signal::ctrl_c() => {
log::info!("Received Ctrl-C, exiting"); log::info!("Received Ctrl-C, exiting");
mpv.disconnect().await?;
} }
_ = Server::bind(&addr.clone()).serve(app.into_make_service()) => { _ = Server::bind(&addr.clone()).serve(app.into_make_service()) => {
log::info!("API server exited"); log::info!("API server exited");
mpv.disconnect().await?;
} }
} }
} }