diff --git a/src/main.rs b/src/main.rs index 4a4e7d6..841fd5c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -50,12 +50,17 @@ async fn main() -> Result<(), Box> { sleep(Duration::from_secs(1)).await; let mut mpvctl = MpvCtl::connect("/tmp/recordwatchsocket").await?; + let mut end_file_listener = mpvctl.listen(&["end-file"])?; let client_name = mpvctl.get_client_name().await?; let _ = mpvctl .play_video("/home/talexander/Downloads/test.mp4") .await?; - sleep(Duration::from_secs(5)).await; + while let Some(evt) = end_file_listener.recv().await { + println!("end file event {}", evt); + } + + sleep(Duration::from_secs(50)).await; let client_name = mpvctl.get_client_name().await?; println!("done {}", client_name); diff --git a/src/mpvctl/mpvctl.rs b/src/mpvctl/mpvctl.rs index a048228..1b7f2a3 100644 --- a/src/mpvctl/mpvctl.rs +++ b/src/mpvctl/mpvctl.rs @@ -11,14 +11,17 @@ use std::{collections::BTreeMap, path::Path}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::unix::OwnedWriteHalf; use tokio::net::UnixStream; +use tokio::sync::mpsc; use tokio::sync::oneshot; type CommandDb = Arc>>>; +type EventDb = Arc>>>>; pub struct MpvCtl { socket: OwnedWriteHalf, next_request_id: u64, in_flight_requests: CommandDb, + event_listeners: EventDb, } impl MpvCtl { @@ -46,9 +49,32 @@ impl MpvCtl { socket: socket_write, next_request_id: 0, in_flight_requests: db, + event_listeners: Arc::new(Mutex::new(HashMap::new())), }) } + pub fn listen( + &mut self, + events: &[&str], + ) -> Result, Box> { + let (tx, rx): ( + tokio::sync::mpsc::Sender, + tokio::sync::mpsc::Receiver, + ) = mpsc::channel(10); + + { + let mut db_handle = self.event_listeners.lock().unwrap(); + for evt in events { + (*db_handle) + .entry(evt.to_string()) + .or_insert_with(Vec::new) + .push(tx.clone()); + } + } + + Ok(rx) + } + async fn read_loop( framed_read: &mut MpvFramed, db: &CommandDb,