1 Commits

Author SHA1 Message Date
361c683b5f WIP: aide OpenAPI docs 2024-10-20 23:59:02 +02:00
9 changed files with 863 additions and 549 deletions

922
Cargo.lock generated

File diff suppressed because it is too large Load Diff

@ -9,25 +9,34 @@ readme = "README.md"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
aide = { version = "0.13.4", features = [
"axum",
"axum-extra",
"axum-extra-query",
"axum-extra-form",
"axum-ws",
"macros",
"scalar",
] }
anyhow = "1.0.82"
axum = { version = "0.7.7", 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-verbosity-flag = "2.2.2"
env_logger = "0.10.0"
futures = "0.3.31"
log = "0.4.20"
mpvipc-async = { git = "https://git.pvv.ntnu.no/Projects/mpvipc-async.git", rev = "v0.1.0" }
mpvipc-async = { git = "https://git.pvv.ntnu.no/oysteikt/mpvipc-async.git", rev = "v0.1.0" }
sd-notify = "0.4.3"
schemars = "0.8.16"
serde = { version = "1.0.188", features = ["derive"] }
serde_json = "1.0.105"
systemd-journal-logger = "2.2.0"
tempfile = "3.11.0"
serde_urlencoded = "0.7.1"
tokio = { version = "1.32.0", features = ["full"] }
tower = { version = "0.4.13", features = ["full"] }
tower-http = { version = "0.4.3", features = ["full"] }
utoipa = { version = "5.1.3", features = ["axum_extras"] }
utoipa-axum = "0.1.2"
utoipa-swagger-ui = { version = "8.0.3", features = ["axum", "vendored"] }
[profile.release]
strip = true

@ -22,7 +22,6 @@ rustPlatform.buildRustPackage rec {
])
(type == "regular" && lib.elem baseName [
"flake.nix"
"flake.lock"
"default.nix"
"module.nix"
".envrc"

@ -38,9 +38,7 @@
package = self.packages.${system}.greg-ng-wrapped;
in {
type = "app";
program = toString (pkgs.writeShellScript "greg-ng" ''
${lib.getExe package} --mpv-socket-path /tmp/greg-ng-mpv.sock -vvvv
'');
program = lib.getExe package;
};
});

@ -135,20 +135,18 @@ in
ProtectKernelModules = true;
ProtectKernelTunables = true;
ProtectProc = "invisible";
# I'll figure it out sometime
# ProtectSystem = "full";
ProtectSystem = "full";
RemoveIPC = true;
UMask = "0077";
RestrictNamespaces = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
SystemCallArchitectures = "native";
# Something brokey
# SystemCallFilter = [
# "@system-service"
# "~@privileged"
# "~@resources"
# ];
SystemCallFilter = [
"@system-service"
"~@privileged"
"~@resources"
];
};
};
})

@ -1,4 +1,4 @@
mod base;
mod rest_wrapper_v1;
pub use rest_wrapper_v1::{rest_api_docs, rest_api_routes};
pub use rest_wrapper_v1::rest_api_routes;

@ -1,17 +1,16 @@
use std::ops::Deref;
use aide::{axum::IntoApiResponse, operation::OperationIo, OperationOutput};
use axum_jsonschema::JsonSchemaRejection;
use axum::{
extract::{Query, State},
http::StatusCode,
response::{IntoResponse, Response},
routing::{delete, get, post},
Json, Router,
async_trait, extract::{rejection::{FailedToDeserializeQueryString, QueryRejection}, FromRequest, FromRequestParts, State}, http::{request::Parts, StatusCode}, response::{IntoResponse, Response}, routing::{delete, get, post}, Json, Router
};
use mpvipc_async::Mpv;
use schemars::JsonSchema;
use serde::{de::DeserializeOwned, Serialize};
use serde_json::{json, Value};
use utoipa::OpenApi;
use utoipa_axum::{router::OpenApiRouter, routes};
use utoipa_swagger_ui::SwaggerUi;
use super::base;
pub fn rest_api_routes(mpv: Mpv) -> Router {
@ -35,64 +34,13 @@ pub fn rest_api_routes(mpv: Mpv) -> Router {
.with_state(mpv)
}
pub fn rest_api_docs(mpv: Mpv) -> Router {
let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi())
.routes(routes!(loadfile))
.routes(routes!(play_get, play_set))
.routes(routes!(volume_get, volume_set))
.routes(routes!(time_get, time_set))
.routes(routes!(playlist_get, playlist_remove_or_clear))
.routes(routes!(playlist_next))
.routes(routes!(playlist_previous))
.routes(routes!(playlist_goto))
.routes(routes!(playlist_move))
.routes(routes!(playlist_get_looping, playlist_set_looping))
.routes(routes!(shuffle))
.with_state(mpv)
.split_for_parts();
router.merge(SwaggerUi::new("/docs").url("/docs/openapi.json", api))
}
// NOTE: the openapi stuff is very heavily duplicated and introduces
// a lot of maintenance overhead and boilerplate. It should theoretically
// be possible to infer a lot of this from axum, but I haven't found a
// good library that does this and works properly yet (I have tried some
// but they all had issues). Feel free to replace this with a better solution.
#[derive(OpenApi)]
#[openapi(info(
description = "The legacy Grzegorz Brzeczyszczykiewicz API, used to control a running mpv instance",
version = "1.0.0",
))]
struct ApiDoc;
#[derive(serde::Serialize, utoipa::ToSchema)]
struct EmptySuccessResponse {
success: bool,
error: bool,
}
#[derive(serde::Serialize, utoipa::ToSchema)]
struct SuccessResponse {
#[schema(example = true)]
success: bool,
#[schema(example = false)]
error: bool,
#[schema(example = json!({ some: "arbitrary json value" }))]
value: Value,
}
#[derive(serde::Serialize, utoipa::ToSchema)]
struct ErrorResponse {
#[schema(example = "error....")]
error: String,
#[schema(example = "error....")]
errortext: String,
#[schema(example = false)]
success: bool,
}
// #[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 RestResponse(anyhow::Result<Value>);
impl From<anyhow::Result<Value>> for RestResponse {
@ -120,183 +68,169 @@ impl IntoResponse for RestResponse {
}
}
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: 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: 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 //
// -------------------//
// TODO: These could possibly be generated with a proc macro
#[derive(serde::Deserialize, utoipa::IntoParams)]
#[derive(serde::Deserialize, JsonSchema)]
struct LoadFileArgs {
path: String,
}
/// Add item to playlist
#[utoipa::path(
post,
path = "/load",
params(LoadFileArgs),
responses(
(status = 200, description = "Success", body = EmptySuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn loadfile(State(mpv): State<Mpv>, Query(query): Query<LoadFileArgs>) -> RestResponse {
base::loadfile(mpv, &query.path).await.into()
}
/// Check whether the player is paused or playing
#[utoipa::path(
get,
path = "/play",
responses(
(status = 200, description = "Success", body = SuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn play_get(State(mpv): State<Mpv>) -> RestResponse {
base::play_get(mpv).await.into()
async fn play_get(State(mpv): State<Mpv>) -> impl IntoApiResponse {
RestResponse::from(base::play_get(mpv).await)
}
#[derive(serde::Deserialize, utoipa::IntoParams)]
#[derive(serde::Deserialize, JsonSchema)]
struct PlaySetArgs {
play: String,
}
/// Set whether the player is paused or playing
#[utoipa::path(
post,
path = "/play",
params(PlaySetArgs),
responses(
(status = 200, description = "Success", body = EmptySuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn play_set(State(mpv): State<Mpv>, Query(query): Query<PlaySetArgs>) -> RestResponse {
let play = query.play.to_lowercase() == "true";
base::play_set(mpv, play).await.into()
}
/// Get the current player volume
#[utoipa::path(
get,
path = "/volume",
responses(
(status = 200, description = "Success", body = SuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn volume_get(State(mpv): State<Mpv>) -> RestResponse {
base::volume_get(mpv).await.into()
}
#[derive(serde::Deserialize, utoipa::IntoParams)]
#[derive(serde::Deserialize, JsonSchema)]
struct VolumeSetArgs {
volume: f64,
}
/// Set the player volume
#[utoipa::path(
post,
path = "/volume",
params(VolumeSetArgs),
responses(
(status = 200, description = "Success", body = EmptySuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn volume_set(State(mpv): State<Mpv>, Query(query): Query<VolumeSetArgs>) -> RestResponse {
base::volume_set(mpv, query.volume).await.into()
}
/// Get current playback position
#[utoipa::path(
get,
path = "/time",
responses(
(status = 200, description = "Success", body = SuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn time_get(State(mpv): State<Mpv>) -> RestResponse {
base::time_get(mpv).await.into()
}
#[derive(serde::Deserialize, utoipa::IntoParams)]
#[derive(serde::Deserialize, JsonSchema)]
struct TimeSetArgs {
pos: Option<f64>,
percent: Option<f64>,
}
/// Set playback position
#[utoipa::path(
post,
path = "/time",
params(TimeSetArgs),
responses(
(status = 200, description = "Success", body = EmptySuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn time_set(State(mpv): State<Mpv>, Query(query): Query<TimeSetArgs>) -> RestResponse {
base::time_set(mpv, query.pos, query.percent).await.into()
}
/// Get the current playlist
#[utoipa::path(
get,
path = "/playlist",
responses(
(status = 200, description = "Success", body = SuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn playlist_get(State(mpv): State<Mpv>) -> RestResponse {
base::playlist_get(mpv).await.into()
}
/// Go to the next item in the playlist
#[utoipa::path(
post,
path = "/playlist/next",
responses(
(status = 200, description = "Success", body = EmptySuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn playlist_next(State(mpv): State<Mpv>) -> RestResponse {
base::playlist_next(mpv).await.into()
}
/// Go back to the previous item in the playlist
#[utoipa::path(
post,
path = "/playlist/previous",
responses(
(status = 200, description = "Success", body = EmptySuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn playlist_previous(State(mpv): State<Mpv>) -> RestResponse {
base::playlist_previous(mpv).await.into()
}
#[derive(serde::Deserialize, utoipa::IntoParams)]
#[derive(serde::Deserialize, JsonSchema)]
struct PlaylistGotoArgs {
index: usize,
}
/// Go to a specific item in the playlist
#[utoipa::path(
post,
path = "/playlist/goto",
params(PlaylistGotoArgs),
responses(
(status = 200, description = "Success", body = EmptySuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn playlist_goto(
State(mpv): State<Mpv>,
Query(query): Query<PlaylistGotoArgs>,
@ -304,21 +238,11 @@ async fn playlist_goto(
base::playlist_goto(mpv, query.index).await.into()
}
#[derive(serde::Deserialize, utoipa::IntoParams)]
#[derive(serde::Deserialize, JsonSchema)]
struct PlaylistRemoveOrClearArgs {
index: Option<usize>,
}
/// Clears a single item or the entire playlist
#[utoipa::path(
delete,
path = "/playlist",
params(PlaylistRemoveOrClearArgs),
responses(
(status = 200, description = "Success", body = EmptySuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn playlist_remove_or_clear(
State(mpv): State<Mpv>,
Query(query): Query<PlaylistRemoveOrClearArgs>,
@ -329,22 +253,12 @@ async fn playlist_remove_or_clear(
}
}
#[derive(serde::Deserialize, utoipa::IntoParams)]
#[derive(serde::Deserialize, JsonSchema)]
struct PlaylistMoveArgs {
index1: usize,
index2: usize,
}
/// Move a playlist item to a different position
#[utoipa::path(
post,
path = "/playlist/move",
params(PlaylistMoveArgs),
responses(
(status = 200, description = "Success", body = EmptySuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn playlist_move(
State(mpv): State<Mpv>,
Query(query): Query<PlaylistMoveArgs>,
@ -354,47 +268,19 @@ async fn playlist_move(
.into()
}
/// Shuffle the playlist
#[utoipa::path(
post,
path = "/playlist/shuffle",
responses(
(status = 200, description = "Success", body = EmptySuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn shuffle(State(mpv): State<Mpv>) -> RestResponse {
base::shuffle(mpv).await.into()
}
/// Check whether the playlist is looping
#[utoipa::path(
get,
path = "/playlist/loop",
responses(
(status = 200, description = "Success", body = SuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn playlist_get_looping(State(mpv): State<Mpv>) -> RestResponse {
base::playlist_get_looping(mpv).await.into()
}
#[derive(serde::Deserialize, utoipa::IntoParams)]
#[derive(serde::Deserialize, JsonSchema)]
struct PlaylistSetLoopingArgs {
r#loop: bool,
}
/// Set whether the playlist should loop
#[utoipa::path(
post,
path = "/playlist/loop",
params(PlaylistSetLoopingArgs),
responses(
(status = 200, description = "Success", body = EmptySuccessResponse),
(status = 500, description = "Internal server error", body = ErrorResponse),
)
)]
async fn playlist_set_looping(
State(mpv): State<Mpv>,
Query(query): Query<PlaylistSetLoopingArgs>,

@ -1,17 +1,16 @@
use anyhow::Context;
use axum::Router;
use axum::{Router, Server};
use clap::Parser;
use clap_verbosity_flag::Verbosity;
use futures::StreamExt;
use mpv_setup::{connect_to_mpv, create_mpv_config_file, show_grzegorz_image};
use mpvipc_async::{Event, Mpv, MpvDataType, MpvExt};
use mpvipc_async::Mpv;
use std::net::{IpAddr, SocketAddr};
use systemd_journal_logger::JournalLog;
use tempfile::NamedTempFile;
use tokio::task::JoinHandle;
mod api;
mod mpv_setup;
// mod mpv_broker;
#[derive(Parser)]
struct Args {
@ -89,74 +88,10 @@ async fn setup_systemd_watchdog_thread() -> anyhow::Result<()> {
Ok(())
}
fn systemd_update_play_status(playing: bool, current_song: &Option<String>) {
sd_notify::notify(
false,
&[sd_notify::NotifyState::Status(&format!(
"{} {:?}",
if playing { "[PLAY]" } else { "[STOP]" },
if let Some(song) = current_song {
song
} else {
""
}
))],
)
.unwrap_or_else(|e| log::warn!("Failed to update systemd status with current song: {}", e));
}
async fn setup_systemd_notifier(mpv: Mpv) -> anyhow::Result<JoinHandle<()>> {
let handle = tokio::spawn(async move {
log::debug!("Starting systemd notifier thread");
let mut event_stream = mpv.get_event_stream().await;
mpv.observe_property(100, "media-title").await.unwrap();
mpv.observe_property(100, "pause").await.unwrap();
let mut current_song: Option<String> = mpv.get_property("media-title").await.unwrap();
let mut playing = !mpv.get_property("pause").await.unwrap().unwrap_or(false);
systemd_update_play_status(playing, &current_song);
loop {
match event_stream.next().await {
Some(Ok(Event::PropertyChange { name, data, .. })) => {
match (name.as_str(), data) {
("media-title", Some(MpvDataType::String(s))) => {
current_song = Some(s);
}
("media-title", None) => {
current_song = None;
}
("pause", Some(MpvDataType::Bool(b))) => {
playing = !b;
}
(event_name, _) => {
log::trace!(
"Received unexpected property change on systemd notifier thread: {}",
event_name
);
}
}
systemd_update_play_status(playing, &current_song)
}
_ => {}
}
}
});
Ok(handle)
}
async fn shutdown(mpv: Mpv, proc: Option<tokio::process::Child>) {
log::info!("Shutting down");
sd_notify::notify(false, &[sd_notify::NotifyState::Stopping]).unwrap_or_else(|e| {
log::warn!(
"Failed to notify systemd that the service is stopping: {}",
e
)
});
sd_notify::notify(false, &[sd_notify::NotifyState::Stopping])
.unwrap_or_else(|e| log::warn!("Failed to notify systemd that the service is stopping: {}", e));
mpv.disconnect()
.await
@ -204,10 +139,6 @@ async fn main() -> anyhow::Result<()> {
.await
.context("Failed to connect to mpv")?;
if systemd_mode {
setup_systemd_notifier(mpv.clone()).await?;
}
if let Err(e) = show_grzegorz_image(mpv.clone()).await {
log::warn!("Could not show Grzegorz image: {}", e);
}
@ -226,15 +157,11 @@ async fn main() -> anyhow::Result<()> {
let socket_addr = SocketAddr::new(addr, args.port);
log::info!("Starting API on {}", socket_addr);
let app = Router::new()
.nest("/api", api::rest_api_routes(mpv.clone()))
.merge(api::rest_api_docs(mpv.clone()));
let listener = match tokio::net::TcpListener::bind(&socket_addr)
.await
let app = Router::new().nest("/api", api::rest_api_routes(mpv.clone()));
let server = match Server::try_bind(&socket_addr.clone())
.context(format!("Failed to bind API server to '{}'", &socket_addr))
{
Ok(listener) => listener,
Ok(server) => server,
Err(e) => {
log::error!("{}", e);
shutdown(mpv, proc).await;
@ -265,7 +192,7 @@ async fn main() -> anyhow::Result<()> {
log::info!("Received Ctrl-C, exiting");
shutdown(mpv, Some(proc)).await;
}
result = axum::serve(listener, app.into_make_service()) => {
result = server.serve(app.into_make_service()) => {
log::info!("API server exited");
shutdown(mpv, Some(proc)).await;
result?;
@ -277,7 +204,7 @@ async fn main() -> anyhow::Result<()> {
log::info!("Received Ctrl-C, exiting");
shutdown(mpv.clone(), None).await;
}
result = axum::serve(listener, app.into_make_service()) => {
result = server.serve(app.into_make_service()) => {
log::info!("API server exited");
shutdown(mpv.clone(), None).await;
result?;

@ -11,9 +11,6 @@ const DEFAULT_MPV_CONFIG_CONTENT: &str = include_str!("../assets/default-mpv.con
const THE_MAN_PNG: &[u8] = include_bytes!("../assets/the_man.png");
// https://mpv.io/manual/master/#options-ytdl
const YTDL_HOOK_ARGS: [&str; 2] = ["try_ytdl_first=yes", "thumbnails=none"];
pub fn create_mpv_config_file(args_config_file: Option<String>) -> anyhow::Result<NamedTempFile> {
let file_content = if let Some(path) = args_config_file {
if !Path::new(&path).exists() {
@ -81,13 +78,6 @@ pub async fn connect_to_mpv<'a>(
.arg("--force-window")
.arg("--fullscreen")
.arg("--no-config")
.arg("--ytdl=yes")
.args(
YTDL_HOOK_ARGS
.into_iter()
.map(|x| format!("--script-opts=ytdl_hook-{}", x))
.collect::<Vec<_>>(),
)
.arg(format!(
"--include={}",
&args.config_file.path().to_string_lossy()
@ -142,3 +132,4 @@ pub async fn show_grzegorz_image(mpv: Mpv) -> anyhow::Result<()> {
Ok(())
}