1
//! IPC handling thread/task. Handles communication between [`Mpv`](crate::Mpv) instances and mpv's unix socket
2

            
3
use futures::{SinkExt, StreamExt};
4
use serde_json::{json, Value};
5
use tokio::{
6
    net::UnixStream,
7
    sync::{broadcast, mpsc, oneshot},
8
};
9
use tokio_util::codec::{Framed, LinesCodec};
10

            
11
use crate::MpvError;
12

            
13
/// Container for all state that regards communication with the mpv IPC socket
14
/// and message passing with [`Mpv`](crate::Mpv) controllers.
15
pub(crate) struct MpvIpc {
16
    socket: Framed<UnixStream, LinesCodec>,
17
    command_channel: mpsc::Receiver<(MpvIpcCommand, oneshot::Sender<MpvIpcResponse>)>,
18
    event_channel: broadcast::Sender<MpvIpcEvent>,
19
}
20

            
21
/// Commands that can be sent to [`MpvIpc`]
22
#[derive(Debug, Clone, PartialEq, Eq)]
23
pub(crate) enum MpvIpcCommand {
24
    Command(Vec<String>),
25
    GetProperty(String),
26
    SetProperty(String, Value),
27
    ObserveProperty(usize, String),
28
    UnobserveProperty(usize),
29
    Exit,
30
}
31

            
32
/// [`MpvIpc`]'s response to a [`MpvIpcCommand`].
33
#[derive(Debug)]
34
pub(crate) struct MpvIpcResponse(pub(crate) Result<Option<Value>, MpvError>);
35

            
36
/// A deserialized and partially parsed event from mpv.
37
#[derive(Debug, Clone)]
38
pub(crate) struct MpvIpcEvent(pub(crate) Value);
39

            
40
impl MpvIpc {
41
42
    pub(crate) fn new(
42
42
        socket: UnixStream,
43
42
        command_channel: mpsc::Receiver<(MpvIpcCommand, oneshot::Sender<MpvIpcResponse>)>,
44
42
        event_channel: broadcast::Sender<MpvIpcEvent>,
45
42
    ) -> Self {
46
42
        MpvIpc {
47
42
            socket: Framed::new(socket, LinesCodec::new()),
48
42
            command_channel,
49
42
            event_channel,
50
42
        }
51
42
    }
52

            
53
4510
    pub(crate) async fn send_command(
54
4510
        &mut self,
55
4510
        command: &[Value],
56
4510
    ) -> Result<Option<Value>, MpvError> {
57
2255
        let ipc_command = json!({ "command": command });
58
2255
        let ipc_command_str =
59
2255
            serde_json::to_string(&ipc_command).map_err(MpvError::JsonParseError)?;
60

            
61
2255
        log::trace!("Sending command: {}", ipc_command_str);
62

            
63
2255
        self.socket
64
2255
            .send(ipc_command_str)
65
15
            .await
66
2255
            .map_err(|why| MpvError::MpvSocketConnectionError(why.to_string()))?;
67

            
68
2251
        let response = loop {
69
2253
            let response = self
70
2253
                .socket
71
2253
                .next()
72
2251
                .await
73
2251
                .ok_or(MpvError::MpvSocketConnectionError(
74
2251
                    "Could not receive response from mpv".to_owned(),
75
2251
                ))?
76
2251
                .map_err(|why| MpvError::MpvSocketConnectionError(why.to_string()))?;
77

            
78
2251
            let parsed_response =
79
2251
                serde_json::from_str::<Value>(&response).map_err(MpvError::JsonParseError);
80
2251

            
81
2251
            if parsed_response
82
2251
                .as_ref()
83
2251
                .ok()
84
2251
                .and_then(|v| v.as_object().map(|o| o.contains_key("event")))
85
2251
                .unwrap_or(false)
86
            {
87
                self.handle_event(parsed_response).await;
88
            } else {
89
2251
                break parsed_response;
90
2251
            }
91
2251
        };
92
2251

            
93
2251
        log::trace!("Received response: {:?}", response);
94

            
95
2251
        parse_mpv_response_data(response?)
96
2253
    }
97

            
98
1936
    pub(crate) async fn get_mpv_property(
99
1936
        &mut self,
100
1936
        property: &str,
101
1936
    ) -> Result<Option<Value>, MpvError> {
102
968
        self.send_command(&[json!("get_property"), json!(property)])
103
975
            .await
104
967
    }
105

            
106
2552
    pub(crate) async fn set_mpv_property(
107
2552
        &mut self,
108
2552
        property: &str,
109
2552
        value: Value,
110
2552
    ) -> Result<Option<Value>, MpvError> {
111
1276
        self.send_command(&[json!("set_property"), json!(property), value])
112
1279
            .await
113
1275
    }
114

            
115
10
    pub(crate) async fn observe_property(
116
10
        &mut self,
117
10
        id: usize,
118
10
        property: &str,
119
10
    ) -> Result<Option<Value>, MpvError> {
120
5
        self.send_command(&[json!("observe_property"), json!(id), json!(property)])
121
6
            .await
122
5
    }
123

            
124
    pub(crate) async fn unobserve_property(
125
        &mut self,
126
        id: usize,
127
    ) -> Result<Option<Value>, MpvError> {
128
        self.send_command(&[json!("unobserve_property"), json!(id)])
129
            .await
130
    }
131

            
132
28
    async fn handle_event(&mut self, event: Result<Value, MpvError>) {
133
14
        match &event {
134
14
            Ok(event) => {
135
14
                log::trace!("Parsed event: {:?}", event);
136
14
                if let Err(broadcast::error::SendError(_)) =
137
14
                    self.event_channel.send(MpvIpcEvent(event.to_owned()))
138
                {
139
                    log::trace!("Failed to send event to channel, ignoring");
140
14
                }
141
            }
142
            Err(e) => {
143
                log::trace!("Error parsing event, ignoring:\n  {:?}\n  {:?}", &event, e);
144
            }
145
        }
146
14
    }
147

            
148
42
    pub(crate) async fn run(mut self) -> Result<(), MpvError> {
149
2288
        loop {
150
2288
            tokio::select! {
151
              Some(event) = self.socket.next() => {
152
                log::trace!("Got event: {:?}", event);
153

            
154
                let parsed_event = event
155
                    .map_err(|why| MpvError::MpvSocketConnectionError(why.to_string()))
156
                    .and_then(|event|
157
14
                        serde_json::from_str::<Value>(&event)
158
14
                        .map_err(MpvError::JsonParseError));
159

            
160
                self.handle_event(parsed_event).await;
161
              }
162
              Some((cmd, tx)) = self.command_channel.recv() => {
163
                  log::trace!("Handling command: {:?}", cmd);
164
                  match cmd {
165
                      MpvIpcCommand::Command(command) => {
166
6
                          let refs = command.iter().map(|s| json!(s)).collect::<Vec<Value>>();
167
                          let response = self.send_command(refs.as_slice()).await;
168
                          tx.send(MpvIpcResponse(response)).unwrap()
169
                      }
170
                      MpvIpcCommand::GetProperty(property) => {
171
                          let response = self.get_mpv_property(&property).await;
172
                          tx.send(MpvIpcResponse(response)).unwrap()
173
                      }
174
                      MpvIpcCommand::SetProperty(property, value) => {
175
                          let response = self.set_mpv_property(&property, value).await;
176
                          tx.send(MpvIpcResponse(response)).unwrap()
177
                      }
178
                      MpvIpcCommand::ObserveProperty(id, property) => {
179
                          let response = self.observe_property(id, &property).await;
180
                          tx.send(MpvIpcResponse(response)).unwrap()
181
                      }
182
                      MpvIpcCommand::UnobserveProperty(id) => {
183
                          let response = self.unobserve_property(id).await;
184
                          tx.send(MpvIpcResponse(response)).unwrap()
185
                      }
186
                      MpvIpcCommand::Exit => {
187
                        tx.send(MpvIpcResponse(Ok(None))).unwrap();
188
                        return Ok(());
189
                      }
190
                  }
191
              }
192
2288
            }
193
2288
        }
194
    }
195
}
196

            
197
/// This function does the most basic JSON parsing and error handling
198
/// for status codes and errors that all responses from mpv are
199
/// expected to contain.
200
4502
fn parse_mpv_response_data(value: Value) -> Result<Option<Value>, MpvError> {
201
4502
    log::trace!("Parsing mpv response data: {:?}", value);
202
4502
    let result = value
203
4502
        .as_object()
204
4502
        .ok_or(MpvError::ValueContainsUnexpectedType {
205
4502
            expected_type: "object".to_string(),
206
4502
            received: value.clone(),
207
4502
        })
208
4502
        .and_then(|o| {
209
4502
            let error = o
210
4502
                .get("error")
211
4502
                .ok_or(MpvError::MissingKeyInObject {
212
4502
                    key: "error".to_string(),
213
4502
                    map: o.clone(),
214
4502
                })?
215
4502
                .as_str()
216
4502
                .ok_or(MpvError::ValueContainsUnexpectedType {
217
4502
                    expected_type: "string".to_string(),
218
4502
                    received: o.get("error").unwrap().clone(),
219
4502
                })?;
220

            
221
4502
            let data = o.get("data");
222
4502

            
223
4502
            Ok((error, data))
224
4502
        })
225
4502
        .and_then(|(error, data)| match error {
226
4502
            "success" => Ok(data),
227
270
            err => Err(MpvError::MpvError(err.to_string())),
228
4502
        });
229
4502

            
230
4502
    match &result {
231
4232
        Ok(v) => log::trace!("Successfully parsed mpv response data: {:?}", v),
232
270
        Err(e) => log::trace!("Error parsing mpv response data: {:?}", e),
233
    }
234

            
235
4502
    result.map(|opt| opt.cloned())
236
4502
}