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

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

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

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

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

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

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

            
95
2159
        parse_mpv_response_data(response?)
96
2161
    }
97

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

            
106
2358
    pub(crate) async fn set_mpv_property(
107
2358
        &mut self,
108
2358
        property: &str,
109
2358
        value: Value,
110
2358
    ) -> Result<Option<Value>, MpvError> {
111
1179
        self.send_command(&[json!("set_property"), json!(property), value])
112
1179
            .await
113
1178
    }
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
5
            .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
                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
        loop {
150
2196
            tokio::select! {
151
2196
              Some(event) = self.socket.next() => {
152
14
                log::trace!("Got event: {:?}", event);
153

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

            
160
14
                self.handle_event(parsed_event).await;
161
              }
162
2196
              Some((cmd, tx)) = self.command_channel.recv() => {
163
2163
                  log::trace!("Handling command: {:?}", cmd);
164
2163
                  match cmd {
165
8
                      MpvIpcCommand::Command(command) => {
166
8
                          let refs = command.iter().map(|s| json!(s)).collect::<Vec<Value>>();
167
8
                          let response = self.send_command(refs.as_slice()).await;
168
8
                          tx.send(MpvIpcResponse(response)).unwrap()
169
                      }
170
971
                      MpvIpcCommand::GetProperty(property) => {
171
971
                          let response = self.get_mpv_property(&property).await;
172
970
                          tx.send(MpvIpcResponse(response)).unwrap()
173
                      }
174
1179
                      MpvIpcCommand::SetProperty(property, value) => {
175
1179
                          let response = self.set_mpv_property(&property, value).await;
176
1178
                          tx.send(MpvIpcResponse(response)).unwrap()
177
                      }
178
5
                      MpvIpcCommand::ObserveProperty(id, property) => {
179
5
                          let response = self.observe_property(id, &property).await;
180
5
                          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
            }
193
        }
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
4318
fn parse_mpv_response_data(value: Value) -> Result<Option<Value>, MpvError> {
201
4318
    log::trace!("Parsing mpv response data: {:?}", value);
202
4318
    let result = value
203
4318
        .as_object()
204
4318
        .ok_or(MpvError::ValueContainsUnexpectedType {
205
4318
            expected_type: "object".to_string(),
206
4318
            received: value.clone(),
207
4318
        })
208
4318
        .and_then(|o| {
209
4318
            let error = o
210
4318
                .get("error")
211
4318
                .ok_or(MpvError::MissingKeyInObject {
212
4318
                    key: "error".to_string(),
213
4318
                    map: o.clone(),
214
4318
                })?
215
4318
                .as_str()
216
4318
                .ok_or(MpvError::ValueContainsUnexpectedType {
217
4318
                    expected_type: "string".to_string(),
218
4318
                    received: o.get("error").unwrap().clone(),
219
4318
                })?;
220

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

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

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

            
236
4318
    result.map(|opt| opt.cloned())
237
4318
}