|
|
|
@ -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<Mutex<HashMap<u64, oneshot::Sender<serde_json::Value>>>>;
|
|
|
|
|
type EventDb = Arc<Mutex<HashMap<String, Vec<mpsc::Sender<serde_json::Value>>>>>;
|
|
|
|
|
|
|
|
|
|
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<mpsc::Receiver<serde_json::Value>, Box<dyn std::error::Error>> {
|
|
|
|
|
let (tx, rx): (
|
|
|
|
|
tokio::sync::mpsc::Sender<serde_json::Value>,
|
|
|
|
|
tokio::sync::mpsc::Receiver<serde_json::Value>,
|
|
|
|
|
) = 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,
|
|
|
|
|