From af697ff5941e9b8706d9c86e8e449bd732bf25a9 Mon Sep 17 00:00:00 2001 From: NotAShelf Date: Thu, 12 Dec 2024 22:02:44 +0300 Subject: [PATCH] terminate IPC messages with newlines MPV will not accept them otherwise. --- src/main.rs | 46 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/src/main.rs b/src/main.rs index f4643a75..25d37233 100644 --- a/src/main.rs +++ b/src/main.rs @@ -37,25 +37,43 @@ enum CommandOptions { const SOCKET_PATH: &str = "/tmp/mpvsocket"; async fn send_ipc_command(command: &str, args: &[serde_json::Value]) -> io::Result> { debug!("Sending IPC command: {} with arguments: {:?}", command, args); - let mut socket = UnixStream::connect(SOCKET_PATH).await?; - let message = json!({ "command": [command, args] }); - let message_str = serde_json::to_string(&message)?; - socket.write_all(message_str.as_bytes()).await?; - socket.flush().await?; + match UnixStream::connect(SOCKET_PATH).await { + Ok(mut socket) => { + debug!("Connected to MPV socket successfully"); - let mut response = vec![0; 1024]; - let n = socket.read(&mut response).await?; - let response_str = String::from_utf8_lossy(&response[..n]); + let mut command_array = vec![json!(command)]; + command_array.extend_from_slice(args); + let message = json!({ "command": command_array }); - match serde_json::from_str::(&response_str) { - Ok(json_response) => { - debug!("Received response: {}", response_str); - Ok(json_response.get("data").cloned()) + let message_str = format!("{}\n", serde_json::to_string(&message)?); + debug!("Serialized message to send with newline: {}", message_str); + + socket.write_all(message_str.as_bytes()).await?; + socket.flush().await?; + debug!("Message sent and flushed"); + + let mut response = vec![0; 1024]; + let n = socket.read(&mut response).await?; + let response_str = String::from_utf8_lossy(&response[..n]); + debug!("Raw response: {}", response_str); + + match serde_json::from_str::(&response_str) { + Ok(json_response) => { + debug!("Parsed IPC response: {:?}", json_response); + Ok(json_response.get("data").cloned()) + } + + Err(e) => { + error!("Failed to parse response: {}", e); + Ok(None) + } + } } + Err(e) => { - error!("Failed to parse response: {}", e); - Ok(None) + error!("Failed to connect to MPV socket: {}", e); + Err(e) } } }