Compare commits
6 Commits
Author | SHA1 | Date | |
---|---|---|---|
613f66abea
|
|||
33593c8175
|
|||
f805c7ecd3
|
|||
20c53ed153
|
|||
4465502ede
|
|||
0769229419
|
1151
Cargo.lock
generated
1151
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
39
Cargo.toml
39
Cargo.toml
@@ -9,26 +9,29 @@ readme = "README.md"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.98"
|
||||
axum = { version = "0.8.4", features = ["macros", "ws"] }
|
||||
clap = { version = "4.5.41", features = ["derive"] }
|
||||
clap-verbosity-flag = "3.0.3"
|
||||
env_logger = "0.11.8"
|
||||
regex = "1.5.4"
|
||||
lazy_static = "1.4.0"
|
||||
url = "2.2.2"
|
||||
swayipc = "3.0"
|
||||
anyhow = "1.0.82"
|
||||
axum = { version = "0.7.7", features = ["macros", "ws"] }
|
||||
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.27"
|
||||
log = "0.4.20"
|
||||
mpvipc-async = { git = "https://git.pvv.ntnu.no/Grzegorz/mpvipc-async.git", branch = "main" }
|
||||
sd-notify = "0.4.5"
|
||||
serde = { version = "1.0.219", features = ["derive"] }
|
||||
serde_json = "1.0.140"
|
||||
systemd-journal-logger = "2.2.2"
|
||||
tempfile = "3.20.0"
|
||||
tokio = { version = "1.46.1", features = ["full"] }
|
||||
tower = { version = "0.5.2", features = ["full"] }
|
||||
tower-http = { version = "0.6.6", features = ["full"] }
|
||||
tungstenite = "0.27.0"
|
||||
utoipa = { version = "5.4.0", features = ["axum_extras"] }
|
||||
utoipa-axum = "0.2.0"
|
||||
utoipa-swagger-ui = { version = "9.0.2", features = ["axum", "vendored"] }
|
||||
sd-notify = "0.4.3"
|
||||
serde = { version = "1.0.188", features = ["derive"] }
|
||||
serde_json = "1.0.105"
|
||||
systemd-journal-logger = "2.2.0"
|
||||
tempfile = "3.11.0"
|
||||
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
|
||||
|
13
README.md
13
README.md
@@ -19,3 +19,16 @@ See also https://git.pvv.ntnu.no/Grzegorz/grzegorz-clients for frontend alternat
|
||||
```sh
|
||||
RUST_LOG=greg_ng=trace,mpvipc=trace cargo run -- --mpv-socket-path /tmp/mpv.sock
|
||||
```
|
||||
|
||||
Custom api call in curl examples
|
||||
|
||||
LOL with input command. (utilizing ydotools)
|
||||
```sh
|
||||
curl -X POST -H "Content-Type: application/json" -d '{"keys": "42:1 38:1 38:0 24:1 24:0 38:1 38:0 42:0"}' http://localhost:8008/api/v2/sway/input/keys
|
||||
```
|
||||
|
||||
Launching DEFAULT_BROWSER with url, in --kiosk mode
|
||||
```sh
|
||||
curl -X POST -H "Content-Type: application/json" -d '{"url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}' http://localhost:8008/api/v2/sway/browser/launch
|
||||
```
|
||||
|
||||
|
12
flake.lock
generated
12
flake.lock
generated
@@ -2,11 +2,11 @@
|
||||
"nodes": {
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1751984180,
|
||||
"narHash": "sha256-LwWRsENAZJKUdD3SpLluwDmdXY9F45ZEgCb0X+xgOL0=",
|
||||
"lastModified": 1729256560,
|
||||
"narHash": "sha256-/uilDXvCIEs3C9l73JTACm4quuHUsIHcns1c+cHUJwA=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "9807714d6944a957c2e036f84b0ff8caf9930bc0",
|
||||
"rev": "4c2fcb090b1f3e5b47eaa7bd33913b574a11e0a0",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -29,11 +29,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1752201818,
|
||||
"narHash": "sha256-d8KczaVT8WFEZdWg//tMAbv8EDyn2YTWcJvSY8gqKBU=",
|
||||
"lastModified": 1729391507,
|
||||
"narHash": "sha256-as0I9xieJUHf7kiK2a9znDsVZQTFWhM1pLivII43Gi0=",
|
||||
"owner": "oxalica",
|
||||
"repo": "rust-overlay",
|
||||
"rev": "bd8f8329780b348fedcd37b53dbbee48c08c496d",
|
||||
"rev": "784981a9feeba406de38c1c9a3decf966d853cca",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
@@ -49,7 +49,6 @@
|
||||
nativeBuildInputs = [
|
||||
toolchain
|
||||
pkgs.mpv
|
||||
pkgs.cargo-edit
|
||||
];
|
||||
|
||||
RUST_SRC_PATH = "${toolchain}/lib/rustlib/src/rust/library";
|
||||
|
20
module.nix
20
module.nix
@@ -11,6 +11,10 @@ in
|
||||
mpvPackage = lib.mkPackageOption pkgs "mpv" { };
|
||||
|
||||
enableSway = lib.mkEnableOption "sway as the main window manager";
|
||||
|
||||
enableFirefox = lib.mkEnableOption "include fiorefox browser for external urls";
|
||||
|
||||
enableInput = lib.mkEnableOption "enable input maipulation with ydotool,";
|
||||
|
||||
enablePipewire = lib.mkEnableOption "pipewire" // { default = true; };
|
||||
|
||||
@@ -160,12 +164,27 @@ in
|
||||
pulse.enable = true;
|
||||
};
|
||||
})
|
||||
(lib.mkIf (cfg.enable && cfg.enableInput) {
|
||||
programs.ydotool = {
|
||||
enable = true;
|
||||
};
|
||||
})
|
||||
(lib.mkIf (cfg.enable && cfg.enableSway) {
|
||||
programs.sway = {
|
||||
enable = true;
|
||||
wrapperFeatures.gtk = true;
|
||||
};
|
||||
|
||||
(lib.mkIf (cfg.enableFirefox) {
|
||||
programs.firefox = {
|
||||
enable = true;
|
||||
preferences = {
|
||||
media.autoplay.default = "0";
|
||||
};
|
||||
};
|
||||
environment.sessionVariables.DEFAULT_BROWSER = "${pkgs.firefox}/bin/firefox";
|
||||
})
|
||||
|
||||
xdg.portal = {
|
||||
enable = true;
|
||||
wlr.enable = true;
|
||||
@@ -176,6 +195,7 @@ in
|
||||
users.greg = {
|
||||
isNormalUser = true;
|
||||
group = "greg";
|
||||
extraGroups [ "audio" "video" "input" "ydotool" ];
|
||||
uid = 2000;
|
||||
description = "loud gym bro";
|
||||
};
|
||||
|
@@ -1,6 +1,8 @@
|
||||
mod base;
|
||||
mod rest_wrapper_v1;
|
||||
// mod rest_wrapper_v1;
|
||||
mod rest_wrapper_v2;
|
||||
mod websocket_v1;
|
||||
|
||||
pub use rest_wrapper_v1::{rest_api_docs, rest_api_routes};
|
||||
// pub use rest_wrapper_v1::{rest_api_docs as rest_api_docs_v1, rest_api_routes as rest_api_routes_v1};
|
||||
pub use rest_wrapper_v2::{rest_api_docs as rest_api_docs_v2, rest_api_routes as rest_api_routes_v2};
|
||||
pub use websocket_v1::websocket_api;
|
||||
|
244
src/api/base.rs
244
src/api/base.rs
@@ -170,3 +170,247 @@ pub async fn playlist_set_looping(mpv: Mpv, r#loop: bool) -> anyhow::Result<()>
|
||||
.await
|
||||
.map_err(|e| e.into())
|
||||
}
|
||||
|
||||
// pub async fn sway_run_command(command: String) -> anyhow::Result<()> {
|
||||
// tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
|
||||
// let mut connection = swayipc::Connection::new()?;
|
||||
// connection.run_command(&command)?;
|
||||
// Ok(())
|
||||
// })
|
||||
// .await
|
||||
// .map_err(|e| swayipc::Error::CommandFailed(e.to_string()))?
|
||||
// }
|
||||
|
||||
//only to check if workspace exists.
|
||||
fn get_workspace_names(connection: &mut swayipc::Connection) -> anyhow::Result<Vec<String>> {
|
||||
let workspaces = connection.get_workspaces()?;
|
||||
Ok(workspaces.iter().map(|w| w.name.clone()).collect())
|
||||
}
|
||||
|
||||
pub async fn sway_get_workspace_names() -> anyhow::Result<Vec<String>> {
|
||||
tokio::task::spawn_blocking(|| -> anyhow::Result<Vec<String>> {
|
||||
let mut connection = swayipc::Connection::new()?;
|
||||
get_workspace_names(&mut connection)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| swayipc::Error::CommandFailed(e.to_string()))?
|
||||
}
|
||||
|
||||
fn is_valid_workspace(workspace: &str, connection: &mut swayipc::Connection) -> anyhow::Result<bool> {
|
||||
let workspace_names = get_workspace_names(connection)?;
|
||||
Ok(workspace_names.contains(&workspace.to_string()) ||
|
||||
workspace.parse::<u32>()
|
||||
.map(|num| num >= 1 && num <= 10)
|
||||
.unwrap_or(false))
|
||||
}
|
||||
|
||||
pub async fn sway_change_workspace(workspace: String) -> anyhow::Result<()> {
|
||||
tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
|
||||
let mut connection = swayipc::Connection::new()?;
|
||||
|
||||
if !is_valid_workspace(&workspace, &mut connection)? {
|
||||
anyhow::bail!("Invalid workspace name");
|
||||
}
|
||||
|
||||
connection.run_command(&format!("workspace {}", workspace))?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| swayipc::Error::CommandFailed(e.to_string()))?
|
||||
}
|
||||
|
||||
use url::Url;
|
||||
|
||||
pub async fn sway_launch_browser(url: &str) -> anyhow::Result<()> {
|
||||
// Validate URL
|
||||
let url = Url::parse(url)
|
||||
.map_err(|e| swayipc::Error::CommandFailed(format!("Invalid URL: {}", e)))?;
|
||||
|
||||
// Ensure URL scheme is http or https
|
||||
if url.scheme() != "http" && url.scheme() != "https" {
|
||||
anyhow::bail!("URL must use http or https protocol");
|
||||
}
|
||||
|
||||
tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
|
||||
let mut connection = swayipc::Connection::new()?;
|
||||
// connection.run_command(&format!("exec xdg-open {}", url))?;
|
||||
// connection.run_command(&format!("exec firefox --kiosk {}", url))?; //moved to firefox to pin in kiosk mode. potentially add --new-window
|
||||
|
||||
//get the DEFAULT_BROWSER env var
|
||||
let default_browser = std::env::var("DEFAULT_BROWSER").unwrap_or("firefox".to_string());
|
||||
connection.run_command(&format!("exec {} --kiosk {}", default_browser, url))?; // set default browser in kiosk mode
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| swayipc::Error::CommandFailed(e.to_string()))?
|
||||
}
|
||||
|
||||
pub async fn sway_close_workspace(workspace: String) -> anyhow::Result<()> {
|
||||
tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
|
||||
let mut connection = swayipc::Connection::new()?;
|
||||
|
||||
// Validate workspace exists
|
||||
if !is_valid_workspace(&workspace, &mut connection)? {
|
||||
anyhow::bail!("Invalid workspace name");
|
||||
}
|
||||
|
||||
// // Get workspace tree and find all nodes in target workspace
|
||||
// let tree = connection.get_tree()?;
|
||||
// let workspace_nodes = tree
|
||||
// .nodes
|
||||
// .iter()
|
||||
// .flat_map(|output| &output.nodes) // Get workspaces
|
||||
// .find(|ws| ws.name.as_ref().map_or(false, |name| name == &workspace));
|
||||
|
||||
// // Kill all nodes in workspace if found
|
||||
// if let Some(ws) = workspace_nodes {
|
||||
// for container in ws.nodes.iter() {
|
||||
// // Close each container in the workspace
|
||||
// connection.run_command(&format!("[con_id={}] kill", container.id))?;
|
||||
// }
|
||||
// }
|
||||
|
||||
// Get workspace tree and find all nodes in target workspace
|
||||
let tree = connection.get_tree()?;
|
||||
let workspace_nodes = tree
|
||||
.nodes
|
||||
.iter()
|
||||
.flat_map(|output| &output.nodes) // Get workspaces
|
||||
.find(|ws| ws.name.as_ref().map_or(false, |name| name == &workspace));
|
||||
|
||||
// Kill all non-MPV nodes in workspace if found
|
||||
if let Some(ws) = workspace_nodes {
|
||||
for container in ws.nodes.iter() {
|
||||
// Check if window is MPV
|
||||
let is_mpv = container.window_properties.as_ref()
|
||||
.map(|props| props.class.as_ref()
|
||||
.map_or(false, |class| class == "mpv"))
|
||||
.unwrap_or(false);
|
||||
|
||||
if !is_mpv {
|
||||
// Close container only if not MPV
|
||||
connection.run_command(&format!("[con_id={}] kill", container.id))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| swayipc::Error::CommandFailed(e.to_string()))?
|
||||
}
|
||||
|
||||
|
||||
use regex::Regex;
|
||||
use lazy_static::lazy_static;
|
||||
|
||||
lazy_static! {
|
||||
static ref KEYPRESS_PATTERN: Regex = Regex::new(r"^(\d+:[01]\s*)+$").unwrap();
|
||||
static ref CLEANUP_PATTERN: Regex = Regex::new(r"[^0-9: \t]").unwrap();
|
||||
}
|
||||
|
||||
fn validate_keypress_string(input: &str) -> anyhow::Result<String> {
|
||||
let cleaned = CLEANUP_PATTERN.replace_all(input, "").to_string();
|
||||
let cleaned = cleaned.trim();
|
||||
|
||||
if !KEYPRESS_PATTERN.is_match(cleaned) {
|
||||
anyhow::bail!("Invalid keypress string");
|
||||
}
|
||||
Ok(cleaned.to_string())
|
||||
}
|
||||
|
||||
//to simulate keypresses 42:1 38:1 38:0 24:1 24:0 38:1 38:0 42:0 -> LOL
|
||||
pub async fn input(keys: String) -> anyhow::Result<()> {
|
||||
let validated_input = validate_keypress_string(&keys)?;
|
||||
|
||||
tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
|
||||
let mut connection = swayipc::Connection::new()?;
|
||||
connection.run_command(&format!("exec ydotool key {}", validated_input))?;
|
||||
// instead of running through swaycmf
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| swayipc::Error::CommandFailed(e.to_string()))?
|
||||
}
|
||||
|
||||
// simulate mouse movement
|
||||
pub async fn mouse_move(x: i32, y: i32) -> anyhow::Result<()> {
|
||||
tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
|
||||
let mut connection = swayipc::Connection::new()?;
|
||||
connection.run_command(&format!("exec ydotool mousemove -x {} -y {}", x, y))?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| swayipc::Error::CommandFailed(e.to_string()))?
|
||||
}
|
||||
|
||||
|
||||
//simulate scroll
|
||||
pub async fn mouse_scroll(x: i32, y: i32) -> anyhow::Result<()> {
|
||||
tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
|
||||
let mut connection = swayipc::Connection::new()?;
|
||||
connection.run_command(&format!("exec ydotool mousemove -w -x {} -y {}", x, y))?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| swayipc::Error::CommandFailed(e.to_string()))?
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum MouseButton {
|
||||
Left,
|
||||
Right,
|
||||
Middle,
|
||||
Side,
|
||||
Extra,
|
||||
Forward,
|
||||
Back,
|
||||
Task,
|
||||
}
|
||||
|
||||
impl MouseButton {
|
||||
fn to_base_value(&self) -> u8 {
|
||||
match self {
|
||||
MouseButton::Left => 0x00,
|
||||
MouseButton::Right => 0x01,
|
||||
MouseButton::Middle => 0x02,
|
||||
MouseButton::Side => 0x03,
|
||||
MouseButton::Extra => 0x04,
|
||||
MouseButton::Forward => 0x05,
|
||||
MouseButton::Back => 0x06,
|
||||
MouseButton::Task => 0x07,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_str(s: &str) -> anyhow::Result<Self> {
|
||||
match s.to_uppercase().as_str() {
|
||||
"LEFT" => Ok(MouseButton::Left),
|
||||
"RIGHT" => Ok(MouseButton::Right),
|
||||
"MIDDLE" => Ok(MouseButton::Middle),
|
||||
"SIDE" => Ok(MouseButton::Side),
|
||||
"EXTRA" => Ok(MouseButton::Extra),
|
||||
"FORWARD" => Ok(MouseButton::Forward),
|
||||
"BACK" => Ok(MouseButton::Back),
|
||||
"TASK" => Ok(MouseButton::Task),
|
||||
_ => anyhow::bail!("Invalid mouse button"),
|
||||
}
|
||||
}
|
||||
|
||||
fn click_value(&self) -> u8 {
|
||||
self.to_base_value() | 0xC0 // Combines DOWN (0x40) and UP (0x80)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mouse_click(button: String) -> anyhow::Result<()> {
|
||||
let mouse_button = MouseButton::from_str(&button)?;
|
||||
let click_value = mouse_button.click_value();
|
||||
|
||||
tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
|
||||
let mut connection = swayipc::Connection::new()?;
|
||||
connection.run_command(&format!("exec ydotool click {:#04x}", click_value))?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| swayipc::Error::CommandFailed(e.to_string()))?
|
||||
}
|
@@ -51,7 +51,7 @@ pub fn rest_api_docs(mpv: Mpv) -> Router {
|
||||
.with_state(mpv)
|
||||
.split_for_parts();
|
||||
|
||||
router.merge(SwaggerUi::new("/docs").url("/docs/openapi.json", api))
|
||||
router.merge(SwaggerUi::new("/docs/v1").url("/docs/v1/openapi.json", api))
|
||||
}
|
||||
|
||||
// NOTE: the openapi stuff is very heavily duplicated and introduces
|
||||
|
590
src/api/rest_wrapper_v2.rs
Normal file
590
src/api/rest_wrapper_v2.rs
Normal file
@@ -0,0 +1,590 @@
|
||||
use axum::{
|
||||
extract::{Query, State},
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
routing::{delete, get, post},
|
||||
Json, Router,
|
||||
};
|
||||
use mpvipc_async::Mpv;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use utoipa::OpenApi;
|
||||
use utoipa_axum::{router::OpenApiRouter, routes};
|
||||
use utoipa_swagger_ui::SwaggerUi;
|
||||
///use futures::FutureExt;
|
||||
|
||||
use super::base;
|
||||
|
||||
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))
|
||||
// .route("/sway/command", post(sway_run_command))
|
||||
.route("/sway/workspace/close", post(sway_close_workspace_handler))
|
||||
.route("/sway/workspace/change", post(sway_change_workspace_handler))
|
||||
.route("/sway/workspace/list", get(sway_get_workspace_names_handler))
|
||||
.route("/sway/browser/launch", post(sway_launch_browser_handler))
|
||||
.route("/input/keys", post(input_handler))
|
||||
.route("/input/mouse", post(mouse_move_handler))
|
||||
.route("/input/scroll", post(mouse_scroll_handler))
|
||||
.route("/input/click", post(mouse_click_handler))
|
||||
.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/v2").url("/docs/v2/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,
|
||||
}
|
||||
|
||||
pub struct RestResponse(anyhow::Result<Value>);
|
||||
|
||||
impl From<anyhow::Result<Value>> for RestResponse {
|
||||
fn from(result: anyhow::Result<Value>) -> Self {
|
||||
Self(result.map(|value| json!({ "success": true, "error": false, "value": value })))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<anyhow::Result<()>> for RestResponse {
|
||||
fn from(result: anyhow::Result<()>) -> Self {
|
||||
Self(result.map(|_| json!({ "success": true, "error": false })))
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for RestResponse {
|
||||
fn into_response(self) -> Response {
|
||||
match self.0 {
|
||||
Ok(value) => (StatusCode::OK, Json(value)).into_response(),
|
||||
Err(err) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({ "error": err.to_string(), "errortext": err.to_string(), "success": false })),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------//
|
||||
// Boilerplate galore //
|
||||
// -------------------//
|
||||
|
||||
// TODO: These could possibly be generated with a proc macro
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::IntoParams)]
|
||||
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()
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::IntoParams)]
|
||||
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)]
|
||||
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)]
|
||||
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)]
|
||||
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>,
|
||||
) -> RestResponse {
|
||||
base::playlist_goto(mpv, query.index).await.into()
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::IntoParams)]
|
||||
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>,
|
||||
) -> RestResponse {
|
||||
match query.index {
|
||||
Some(index) => base::playlist_remove(mpv, index).await.into(),
|
||||
None => base::playlist_clear(mpv).await.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::IntoParams)]
|
||||
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>,
|
||||
) -> RestResponse {
|
||||
base::playlist_move(mpv, query.index1, query.index2)
|
||||
.await
|
||||
.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)]
|
||||
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>,
|
||||
) -> RestResponse {
|
||||
base::playlist_set_looping(mpv, query.r#loop).await.into()
|
||||
}
|
||||
|
||||
|
||||
// #[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
// struct SwayCommandBody {
|
||||
// command: String,
|
||||
// }
|
||||
|
||||
// #[utoipa::path(
|
||||
// post,
|
||||
// path = "/sway/command",
|
||||
// request_body = SwayCommandBody,
|
||||
// responses(
|
||||
// (status = 200, description = "Success", body = EmptySuccessResponse),
|
||||
// (status = 500, description = "Internal server error", body = ErrorResponse),
|
||||
// )
|
||||
// )]
|
||||
// async fn sway_run_command(Json(body): Json<SwayCommandBody>) -> RestResponse {
|
||||
// base::sway_run_command(body.command).await.map_err(anyhow::Error::new).into()
|
||||
// }
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
struct SwayBrowserBody {
|
||||
url: String,
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/sway/browser/launch",
|
||||
request_body = SwayBrowserBody,
|
||||
responses(
|
||||
(status = 200, description = "Success", body = EmptySuccessResponse),
|
||||
(status = 500, description = "Internal server error", body = ErrorResponse),
|
||||
)
|
||||
)]
|
||||
async fn sway_launch_browser_handler(Json(body): Json<SwayBrowserBody>) -> RestResponse {
|
||||
base::sway_launch_browser(&body.url).await.into()
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
struct SwayWorkspaceBody {
|
||||
workspace: String,
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/sway/workspace/close",
|
||||
request_body = SwayWorkspaceBody,
|
||||
responses(
|
||||
(status = 200, description = "Success", body = EmptySuccessResponse),
|
||||
(status = 500, description = "Internal server error", body = ErrorResponse),
|
||||
)
|
||||
)]
|
||||
async fn sway_close_workspace_handler(Json(body): Json<SwayWorkspaceBody>) -> RestResponse {
|
||||
base::sway_close_workspace(body.workspace).await.into()
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/sway/workspace/change",
|
||||
request_body = SwayWorkspaceBody,
|
||||
responses(
|
||||
(status = 200, description = "Success", body = EmptySuccessResponse),
|
||||
(status = 500, description = "Internal server error", body = ErrorResponse),
|
||||
)
|
||||
)]
|
||||
async fn sway_change_workspace_handler(Json(body): Json<SwayWorkspaceBody>) -> RestResponse {
|
||||
base::sway_change_workspace(body.workspace).await.into()
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/sway/workspace/list",
|
||||
responses(
|
||||
(status = 200, description = "Success", body = Vec<String>),
|
||||
(status = 500, description = "Internal server error", body = ErrorResponse),
|
||||
)
|
||||
)]
|
||||
async fn sway_get_workspace_names_handler() -> RestResponse {
|
||||
base::sway_get_workspace_names().await
|
||||
.map(|workspaces| json!(workspaces))
|
||||
.into()
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
struct KeyboardInput {
|
||||
keys: String,
|
||||
}
|
||||
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/input/keys",
|
||||
request_body = KeyboardInput,
|
||||
responses(
|
||||
(status = 200, description = "Success", body = Vec<String>),
|
||||
(status = 500, description = "Internal server error", body = ErrorResponse),
|
||||
)
|
||||
)]
|
||||
async fn input_handler(
|
||||
Json(payload): Json<KeyboardInput>
|
||||
) -> RestResponse {
|
||||
base::input(payload.keys)
|
||||
.await
|
||||
.map(|_| json!({}))
|
||||
.into()
|
||||
}
|
||||
|
||||
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
struct MouseMove {
|
||||
x: i32,
|
||||
y: i32,
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/input/mouse",
|
||||
request_body = MouseMove,
|
||||
responses(
|
||||
(status = 200, description = "Success", body = Vec<String>),
|
||||
(status = 500, description = "Internal server error", body = ErrorResponse),
|
||||
)
|
||||
)]
|
||||
async fn mouse_move_handler(
|
||||
Json(payload): Json<MouseMove>
|
||||
) -> RestResponse {
|
||||
base::mouse_move(payload.x, payload.y)
|
||||
.await
|
||||
.map(|_| json!({}))
|
||||
.into()
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/input/scroll",
|
||||
request_body = MouseMove,
|
||||
responses(
|
||||
(status = 200, description = "Success", body = Vec<String>),
|
||||
(status = 500, description = "Internal server error", body = ErrorResponse),
|
||||
)
|
||||
)]
|
||||
async fn mouse_scroll_handler(
|
||||
Json(payload): Json<MouseMove>
|
||||
) -> RestResponse {
|
||||
base::mouse_scroll(payload.x, payload.y)
|
||||
.await
|
||||
.map(|_| json!({}))
|
||||
.into()
|
||||
}
|
||||
|
||||
//click
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
struct MouseClick {
|
||||
button: String
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/input/click",
|
||||
request_body = MouseClick,
|
||||
responses(
|
||||
(status = 200, description = "Success", body = Vec<String>),
|
||||
(status = 500, description = "Internal server error", body = ErrorResponse),
|
||||
)
|
||||
)]
|
||||
async fn mouse_click_handler(
|
||||
Json(payload): Json<MouseClick>
|
||||
) -> RestResponse {
|
||||
base::mouse_click(payload.button)
|
||||
.await
|
||||
.map(|_| json!({}))
|
||||
.into()
|
||||
}
|
@@ -21,30 +21,20 @@ use mpvipc_async::{
|
||||
Switch,
|
||||
};
|
||||
use serde_json::{json, Value};
|
||||
use tokio::{
|
||||
select,
|
||||
sync::{mpsc, watch},
|
||||
};
|
||||
use tokio::{select, sync::watch};
|
||||
|
||||
use crate::util::{ConnectionEvent, IdPool};
|
||||
use crate::util::IdPool;
|
||||
|
||||
use super::base;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct WebsocketState {
|
||||
mpv: Mpv,
|
||||
id_pool: Arc<Mutex<IdPool>>,
|
||||
connection_counter_tx: mpsc::Sender<ConnectionEvent>,
|
||||
}
|
||||
|
||||
pub fn websocket_api(
|
||||
mpv: Mpv,
|
||||
id_pool: Arc<Mutex<IdPool>>,
|
||||
connection_counter_tx: mpsc::Sender<ConnectionEvent>,
|
||||
) -> Router {
|
||||
let state = WebsocketState {
|
||||
mpv,
|
||||
id_pool,
|
||||
connection_counter_tx,
|
||||
};
|
||||
pub fn websocket_api(mpv: Mpv, id_pool: Arc<Mutex<IdPool>>) -> Router {
|
||||
let state = WebsocketState { mpv, id_pool };
|
||||
Router::new()
|
||||
.route("/", any(websocket_handler))
|
||||
.with_state(state)
|
||||
@@ -53,11 +43,7 @@ pub fn websocket_api(
|
||||
async fn websocket_handler(
|
||||
ws: WebSocketUpgrade,
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(WebsocketState {
|
||||
mpv,
|
||||
id_pool,
|
||||
connection_counter_tx,
|
||||
}): State<WebsocketState>,
|
||||
State(WebsocketState { mpv, id_pool }): State<WebsocketState>,
|
||||
) -> impl IntoResponse {
|
||||
let mpv = mpv.clone();
|
||||
let id = match id_pool.lock().unwrap().request_id() {
|
||||
@@ -68,9 +54,7 @@ async fn websocket_handler(
|
||||
}
|
||||
};
|
||||
|
||||
ws.on_upgrade(move |socket| {
|
||||
handle_connection(socket, addr, mpv, id, id_pool, connection_counter_tx)
|
||||
})
|
||||
ws.on_upgrade(move |socket| handle_connection(socket, addr, mpv, id, id_pool))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
@@ -192,17 +176,7 @@ async fn handle_connection(
|
||||
mpv: Mpv,
|
||||
channel_id: u64,
|
||||
id_pool: Arc<Mutex<IdPool>>,
|
||||
connection_counter_tx: mpsc::Sender<ConnectionEvent>,
|
||||
) {
|
||||
match connection_counter_tx.send(ConnectionEvent::Connected).await {
|
||||
Ok(()) => {
|
||||
log::trace!("Connection count updated for {:?}", addr);
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Error updating connection count for {:?}: {:?}", addr, e);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: There is an asynchronous gap between gathering the initial state and subscribing to the properties
|
||||
// This could lead to missing events if they happen in that gap. Send initial state, but also ensure
|
||||
// that there is an additional "initial state" sent upon subscription to all properties to ensure that
|
||||
@@ -214,8 +188,7 @@ async fn handle_connection(
|
||||
"type": "initial_state",
|
||||
"value": initial_state,
|
||||
})
|
||||
.to_string()
|
||||
.into(),
|
||||
.to_string(),
|
||||
);
|
||||
|
||||
socket.send(message).await.unwrap();
|
||||
@@ -265,18 +238,6 @@ async fn handle_connection(
|
||||
log::error!("Error releasing id {} for {:?}: {:?}", channel_id, addr, e);
|
||||
}
|
||||
}
|
||||
|
||||
match connection_counter_tx
|
||||
.send(ConnectionEvent::Disconnected)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
log::trace!("Connection count updated for {:?}", addr);
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Error updating connection count for {:?}: {:?}", addr, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn connection_loop(
|
||||
@@ -289,108 +250,91 @@ async fn connection_loop(
|
||||
let mut event_stream = mpv.get_event_stream().await;
|
||||
loop {
|
||||
select! {
|
||||
id_count = id_count_watch_receiver.changed() => {
|
||||
if let Err(e) = id_count {
|
||||
anyhow::bail!("Error reading id count watch receiver for {:?}: {:?}", addr, e);
|
||||
}
|
||||
id_count = id_count_watch_receiver.changed() => {
|
||||
if let Err(e) = id_count {
|
||||
anyhow::bail!("Error reading id count watch receiver for {:?}: {:?}", addr, e);
|
||||
}
|
||||
|
||||
let message = Message::Text(json!({
|
||||
"type": "connection_count",
|
||||
"value": id_count_watch_receiver.borrow().clone(),
|
||||
}).to_string());
|
||||
|
||||
socket.send(message).await?;
|
||||
}
|
||||
message = socket.recv() => {
|
||||
log::trace!("Received command from {:?}: {:?}", addr, message);
|
||||
|
||||
let ws_message_content = message
|
||||
.ok_or(anyhow::anyhow!("Event stream ended for {:?}", addr))
|
||||
.and_then(|message| {
|
||||
match message {
|
||||
Ok(message) => Ok(message),
|
||||
err => Err(anyhow::anyhow!("Error reading message for {:?}: {:?}", addr, err)),
|
||||
}
|
||||
})?;
|
||||
|
||||
if let Message::Close(_) = ws_message_content {
|
||||
log::trace!("Closing connection for {:?}", addr);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Message::Ping(xs) = ws_message_content {
|
||||
log::trace!("Ponging {:?} with {:?}", addr, xs);
|
||||
socket.send(Message::Pong(xs)).await?;
|
||||
continue;
|
||||
}
|
||||
|
||||
let message_content = match ws_message_content {
|
||||
Message::Text(text) => text,
|
||||
m => anyhow::bail!("Unexpected message type: {:?}", m),
|
||||
};
|
||||
|
||||
let message_json = match serde_json::from_str::<Value>(&message_content) {
|
||||
Ok(json) => json,
|
||||
Err(e) => anyhow::bail!("Error parsing message from {:?}: {:?}", addr, e),
|
||||
};
|
||||
|
||||
log::trace!("Handling command from {:?}: {:?}", addr, message_json);
|
||||
|
||||
// TODO: handle errors
|
||||
match handle_message(message_json, mpv.clone(), channel_id).await {
|
||||
Ok(Some(response)) => {
|
||||
log::trace!("Handled command from {:?} successfully, sending response", addr);
|
||||
let message = Message::Text(json!({
|
||||
"type": "response",
|
||||
"value": response,
|
||||
}).to_string());
|
||||
socket.send(message).await?;
|
||||
}
|
||||
Ok(None) => {
|
||||
log::trace!("Handled command from {:?} successfully", addr);
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Error handling message from {:?}: {:?}", addr, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
event = event_stream.next() => {
|
||||
match event {
|
||||
Some(Ok(event)) => {
|
||||
log::trace!("Sending event to {:?}: {:?}", addr, event);
|
||||
let message = Message::Text(json!({
|
||||
"type": "connection_count",
|
||||
"value": id_count_watch_receiver.borrow().clone(),
|
||||
}).to_string().into(),);
|
||||
|
||||
"type": "event",
|
||||
"value": event,
|
||||
}).to_string());
|
||||
socket.send(message).await?;
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
log::error!("Error reading event stream for {:?}: {:?}", addr, e);
|
||||
anyhow::bail!("Error reading event stream for {:?}: {:?}", addr, e);
|
||||
}
|
||||
None => {
|
||||
log::trace!("Event stream ended for {:?}", addr);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
message = socket.recv() => {
|
||||
log::trace!("Received command from {:?}: {:?}", addr, message);
|
||||
|
||||
let ws_message_content = match message {
|
||||
Some(Ok(message)) => message,
|
||||
|
||||
None => {
|
||||
log::debug!("Connection closed for {:?}", addr);
|
||||
return Ok(());
|
||||
},
|
||||
|
||||
Some(Err(e)) => {
|
||||
let inner_error = e.into_inner();
|
||||
if inner_error
|
||||
.downcast_ref::<tungstenite::error::Error>()
|
||||
.is_some_and(|e| match *e {
|
||||
tungstenite::error::Error::Protocol(tungstenite::error::ProtocolError::ResetWithoutClosingHandshake) => true,
|
||||
_ => false,
|
||||
}) {
|
||||
log::warn!("Connection reset without closing handshake for {:?}", addr);
|
||||
return Ok(());
|
||||
} else {
|
||||
log::error!("Error reading message for {:?}: {:?}", addr, inner_error);
|
||||
anyhow::bail!("Error reading message for {:?}: {:?}", addr, inner_error);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
if let Message::Close(_) = ws_message_content {
|
||||
log::trace!("Closing connection for {:?}", addr);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Message::Ping(xs) = ws_message_content {
|
||||
log::trace!("Ponging {:?} with {:?}", addr, xs);
|
||||
socket.send(Message::Pong(xs)).await?;
|
||||
continue;
|
||||
}
|
||||
|
||||
let message_content = match ws_message_content {
|
||||
Message::Text(text) => text,
|
||||
m => anyhow::bail!("Unexpected message type: {:?}", m),
|
||||
};
|
||||
|
||||
let message_json = match serde_json::from_str::<Value>(&message_content) {
|
||||
Ok(json) => json,
|
||||
Err(e) => anyhow::bail!("Error parsing message from {:?}: {:?}", addr, e),
|
||||
};
|
||||
|
||||
log::trace!("Handling command from {:?}: {:?}", addr, message_json);
|
||||
|
||||
// TODO: handle errors
|
||||
match handle_message(message_json, mpv.clone(), channel_id).await {
|
||||
Ok(Some(response)) => {
|
||||
log::trace!("Handled command from {:?} successfully, sending response", addr);
|
||||
let message = Message::Text(json!({
|
||||
"type": "response",
|
||||
"value": response,
|
||||
}).to_string().into(),);
|
||||
socket.send(message).await?;
|
||||
}
|
||||
Ok(None) => {
|
||||
log::trace!("Handled command from {:?} successfully", addr);
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Error handling message from {:?}: {:?}", addr, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
event = event_stream.next() => {
|
||||
match event {
|
||||
Some(Ok(event)) => {
|
||||
log::trace!("Sending event to {:?}: {:?}", addr, event);
|
||||
let message = Message::Text(json!({
|
||||
"type": "event",
|
||||
"value": event,
|
||||
}).to_string().into(),);
|
||||
socket.send(message).await?;
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
log::error!("Error reading event stream for {:?}: {:?}", addr, e);
|
||||
anyhow::bail!("Error reading event stream for {:?}: {:?}", addr, e);
|
||||
}
|
||||
None => {
|
||||
log::trace!("Event stream ended for {:?}", addr);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -413,6 +357,16 @@ pub enum WSCommand {
|
||||
Shuffle,
|
||||
SetSubtitleTrack { track: Option<usize> },
|
||||
SetLooping { value: bool },
|
||||
// SwayCommand { command: String },
|
||||
SwayLaunchBrowser { url: String },
|
||||
SwayCloseWorkspace { workspace: String },
|
||||
SwayChangeWorkspace { workspace: String },
|
||||
SwayGetWorkspaces,
|
||||
// New input commands
|
||||
InputKeys { keys: String },
|
||||
MouseMove { x: i32, y: i32 },
|
||||
MouseScroll { x: i32, y: i32 },
|
||||
MouseClick { button: String },
|
||||
}
|
||||
|
||||
async fn handle_message(
|
||||
@@ -503,5 +457,51 @@ async fn handle_message(
|
||||
.await?;
|
||||
Ok(None)
|
||||
}
|
||||
// WSCommand::SwayCommand { command } => {
|
||||
// base::sway_run_command(command).await?;
|
||||
// Ok(None)
|
||||
// }
|
||||
WSCommand::SwayLaunchBrowser { url } => {
|
||||
base::sway_launch_browser(&url).await?;
|
||||
Ok(None)
|
||||
}
|
||||
WSCommand::SwayCloseWorkspace { workspace } => {
|
||||
base::sway_close_workspace(workspace).await?;
|
||||
Ok(None)
|
||||
}
|
||||
WSCommand::SwayChangeWorkspace { workspace } => {
|
||||
base::sway_change_workspace(workspace).await?;
|
||||
Ok(None)
|
||||
}
|
||||
WSCommand::SwayGetWorkspaces => {
|
||||
let workspaces = base::sway_get_workspace_names().await?;
|
||||
Ok(Some(json!(workspaces)))
|
||||
}
|
||||
WSCommand::InputKeys { keys } => {
|
||||
base::input(keys)
|
||||
.await
|
||||
.map(|_| json!({}))
|
||||
.context("Failed to execute input command")?;
|
||||
Ok(None)
|
||||
}
|
||||
WSCommand::MouseMove { x, y } => {
|
||||
let _ = base::mouse_move(x, y)
|
||||
.await
|
||||
.map(|_| json!({}));
|
||||
Ok(None)
|
||||
}
|
||||
WSCommand::MouseScroll { x, y } => {
|
||||
let _ = base::mouse_scroll(x, y)
|
||||
.await
|
||||
.map(|_| json!({}));
|
||||
Ok(None)
|
||||
}
|
||||
WSCommand::MouseClick { button } => {
|
||||
let _ = base::mouse_click(button)
|
||||
.await
|
||||
.map(|_| json!({}));
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
135
src/main.rs
135
src/main.rs
@@ -11,8 +11,8 @@ use std::{
|
||||
};
|
||||
use systemd_journal_logger::JournalLog;
|
||||
use tempfile::NamedTempFile;
|
||||
use tokio::{sync::mpsc, task::JoinHandle};
|
||||
use util::{ConnectionEvent, IdPool};
|
||||
use tokio::task::JoinHandle;
|
||||
use util::IdPool;
|
||||
|
||||
mod api;
|
||||
mod mpv_setup;
|
||||
@@ -94,37 +94,23 @@ async fn setup_systemd_watchdog_thread() -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send_play_status(
|
||||
systemd: bool,
|
||||
playing: bool,
|
||||
current_song: &Option<String>,
|
||||
connection_count: u64,
|
||||
) {
|
||||
let status = &format!(
|
||||
"[CONN: {}] {} {:?}",
|
||||
connection_count,
|
||||
if playing { "[PLAY]" } else { "[STOP]" },
|
||||
if let Some(song) = current_song {
|
||||
song
|
||||
} else {
|
||||
""
|
||||
}
|
||||
);
|
||||
|
||||
if systemd {
|
||||
sd_notify::notify(false, &[sd_notify::NotifyState::Status(status)]).unwrap_or_else(|e| {
|
||||
log::warn!("Failed to update systemd status with current song: {}", e)
|
||||
});
|
||||
} else {
|
||||
log::info!("{}", status);
|
||||
}
|
||||
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 start_status_notifier_thread(
|
||||
systemd: bool,
|
||||
mpv: Mpv,
|
||||
mut connection_counter_rx: mpsc::Receiver<ConnectionEvent>,
|
||||
) -> anyhow::Result<JoinHandle<()>> {
|
||||
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;
|
||||
@@ -134,53 +120,30 @@ async fn start_status_notifier_thread(
|
||||
|
||||
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);
|
||||
let mut connection_count = 0;
|
||||
|
||||
send_play_status(systemd, playing, ¤t_song, connection_count);
|
||||
systemd_update_play_status(playing, ¤t_song);
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
Some(Ok(Event::PropertyChange { name, data, .. })) = event_stream.next() => {
|
||||
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
|
||||
);
|
||||
}
|
||||
if let Some(Ok(Event::PropertyChange { name, data, .. })) = event_stream.next().await {
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
send_play_status(systemd, playing, ¤t_song, connection_count)
|
||||
}
|
||||
|
||||
Some(connection_counter_update) = connection_counter_rx.recv() => {
|
||||
log::trace!("Received connection counter update: {}", connection_counter_update);
|
||||
|
||||
match connection_count.checked_add_signed(connection_counter_update.to_i8().into()) {
|
||||
Some(new_count) => connection_count = new_count,
|
||||
None => {
|
||||
log::warn!("Invalid connection count: trying to add {} to {}", connection_counter_update.to_i8(), connection_count);
|
||||
log::warn!("Resetting connection count to 0");
|
||||
connection_count = 0;
|
||||
}
|
||||
}
|
||||
|
||||
match connection_count {
|
||||
0 => log::debug!("No connections"),
|
||||
_ => log::debug!("Connection count: {}", connection_count),
|
||||
}
|
||||
|
||||
send_play_status(systemd, playing, ¤t_song, connection_count);
|
||||
}
|
||||
systemd_update_play_status(playing, ¤t_song)
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -243,10 +206,9 @@ async fn main() -> anyhow::Result<()> {
|
||||
.await
|
||||
.context("Failed to connect to mpv")?;
|
||||
|
||||
let (connection_counter_tx, connection_counter_rx) = mpsc::channel(10);
|
||||
|
||||
let status_notifier_thread_handle =
|
||||
start_status_notifier_thread(systemd_mode, mpv.clone(), connection_counter_rx).await?;
|
||||
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);
|
||||
@@ -269,12 +231,11 @@ async fn main() -> anyhow::Result<()> {
|
||||
let id_pool = Arc::new(Mutex::new(IdPool::new_with_max_limit(1024)));
|
||||
|
||||
let app = Router::new()
|
||||
.nest("/api", api::rest_api_routes(mpv.clone()))
|
||||
.nest(
|
||||
"/ws",
|
||||
api::websocket_api(mpv.clone(), id_pool.clone(), connection_counter_tx.clone()),
|
||||
)
|
||||
.merge(api::rest_api_docs(mpv.clone()))
|
||||
// .nest("/api/v1", api::rest_api_routes_v1(mpv.clone()))
|
||||
.nest("/api/v2", api::rest_api_routes_v2(mpv.clone()))
|
||||
.nest("/ws", api::websocket_api(mpv.clone(), id_pool.clone()))
|
||||
// .merge(api::rest_api_docs_v1(mpv.clone()))
|
||||
.merge(api::rest_api_docs_v2(mpv.clone()))
|
||||
.into_make_service_with_connect_info::<SocketAddr>();
|
||||
|
||||
let listener = match tokio::net::TcpListener::bind(&socket_addr)
|
||||
@@ -317,11 +278,6 @@ async fn main() -> anyhow::Result<()> {
|
||||
shutdown(mpv, Some(proc)).await;
|
||||
result?;
|
||||
}
|
||||
result = status_notifier_thread_handle => {
|
||||
log::info!("Status notifier thread exited unexpectedly, shutting dow");
|
||||
shutdown(mpv, Some(proc)).await;
|
||||
result?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tokio::select! {
|
||||
@@ -334,11 +290,6 @@ async fn main() -> anyhow::Result<()> {
|
||||
shutdown(mpv.clone(), None).await;
|
||||
result?;
|
||||
}
|
||||
result = status_notifier_thread_handle => {
|
||||
log::info!("Status notifier thread exited unexpectedly, shutting down");
|
||||
shutdown(mpv.clone(), None).await;
|
||||
result?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -36,7 +36,9 @@ pub fn create_mpv_config_file(args_config_file: Option<String>) -> anyhow::Resul
|
||||
Ok(tmpfile)
|
||||
}
|
||||
|
||||
pub async fn connect_to_mpv(args: &MpvConnectionArgs<'_>) -> anyhow::Result<(Mpv, Option<Child>)> {
|
||||
pub async fn connect_to_mpv<'a>(
|
||||
args: &MpvConnectionArgs<'a>,
|
||||
) -> anyhow::Result<(Mpv, Option<Child>)> {
|
||||
log::debug!("Connecting to mpv");
|
||||
|
||||
debug_assert!(
|
||||
|
@@ -1,5 +1,3 @@
|
||||
mod connection_counter;
|
||||
mod id_pool;
|
||||
|
||||
pub use connection_counter::ConnectionEvent;
|
||||
pub use id_pool::IdPool;
|
||||
|
@@ -1,25 +0,0 @@
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum ConnectionEvent {
|
||||
Connected,
|
||||
Disconnected,
|
||||
}
|
||||
|
||||
impl ConnectionEvent {
|
||||
pub fn to_i8(self) -> i8 {
|
||||
match self {
|
||||
ConnectionEvent::Connected => 1,
|
||||
ConnectionEvent::Disconnected => -1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ConnectionEvent {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
ConnectionEvent::Connected => write!(f, "Connected"),
|
||||
ConnectionEvent::Disconnected => write!(f, "Disconnected"),
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user