1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
use async_std::{
    io::BufReader,
    net::{SocketAddr, TcpStream, ToSocketAddrs},
    prelude::*,
};
use itertools::Itertools;
use log::info;
use std::io;

use crate::{
    filter::Filter,
    response::{self, Mixed},
    Stats, Status, Subsystem, Track,
};

/// Error
#[derive(thiserror::Error, Debug)]
pub enum Error {
    /// Server failed to parse the command
    #[error("Invalid command or arguments")]
    CommandError { msg: String },

    /// The server closed the connection
    #[error("The server closed the connection")]
    Disconnected,

    /// Represents all other cases of `std::io::Error`.
    #[error(transparent)]
    IOError(#[from] std::io::Error),

    /// Failed to parse the reply the server sent
    #[error("Invalid reply to command")]
    ResponseError { reply: String, errmsg: String },
}

/// Mpd Client
pub struct MpdClient {
    bufreader: BufReader<TcpStream>,
    version: String,
    server_address: SocketAddr,
}

impl MpdClient {
    /// Create a new MpdClient and connect to `addr`
    pub async fn new<A: ToSocketAddrs>(addr: A) -> Result<Self, Error> {
        let stream = TcpStream::connect(addr).await?;
        let server_address = stream.peer_addr()?;
        let bufreader = BufReader::new(stream);

        let mut s = Self {
            bufreader,
            version: String::new(),
            server_address,
        };

        s.read_version().await?;

        Ok(s)
    }

    /// Reconnect to server
    pub async fn reconnect(&mut self) -> Result<(), Error> {
        let stream = TcpStream::connect(self.server_address).await?;
        let bufreader = BufReader::new(stream);
        self.bufreader = bufreader;
        self.read_version().await?;

        Ok(())
    }

    async fn read_version(&mut self) -> Result<(), Error> {
        self.version = self.read_resp_line().await?;
        info!("version: {}", self.version);
        Ok(())
    }

    /// Get stats on the music database
    pub async fn stats(&mut self) -> Result<Stats, Error> {
        self.cmd("stats").await?;
        let lines = self.read_resp().await?;
        serde_yaml::from_str(&lines).map_err(|err| Error::ResponseError {
            reply: lines,
            errmsg: err.to_string(),
        })
    }

    pub async fn status(&mut self) -> Result<Status, Error> {
        self.cmd("status").await?;
        let lines = self.read_resp().await?;
        serde_yaml::from_str(&lines).map_err(|err| Error::ResponseError {
            reply: lines,
            errmsg: err.to_string(),
        })
    }

    pub async fn update(&mut self, path: Option<&str>) -> Result<i32, Error> {
        self.cmd(Cmd::new("update", path)).await?;
        let r = self.read_resp_line().await?;

        let db_version = match r.split(": ").next_tuple() {
            Some(("updating_db", dbv)) => dbv.parse().unwrap_or(0),
            _ => 0,
        };

        Ok(db_version)
    }

    pub async fn rescan(&mut self, path: Option<&str>) -> Result<i32, Error> {
        self.cmd(Cmd::new("rescan", path)).await?;
        let r = self.read_resp_line().await?;

        let db_version = match r.split(": ").next_tuple() {
            Some(("updating_db", dbv)) => dbv.parse().unwrap_or(0),
            _ => 0,
        };

        Ok(db_version)
    }

    pub async fn idle(&mut self) -> Result<Option<Subsystem>, Error> {
        self.cmd("idle").await?;
        let resp = self.read_resp().await?;
        let mut lines = resp.lines();

        let line = lines.next().unwrap_or_default();
        for unexpected_line in lines {
            log::warn!("More than one line in idle response: {}", unexpected_line);
        }

        if let Some((k, v)) = line.splitn(2, ": ").next_tuple() {
            if k != "changed" {
                log::warn!("k not changed");
                return Ok(None);
            }

            return Ok(serde_yaml::from_str(v).ok());
        }
        Ok(None)
    }

    pub async fn noidle(&mut self) -> Result<(), Error> {
        self.cmd("noidle").await?;
        self.read_ok_resp().await?;
        Ok(())
    }

    pub async fn setvol(&mut self, volume: u32) -> Result<(), Error> {
        self.cmd(Cmd::new("setvol", Some(volume))).await?;
        self.read_ok_resp().await?;
        Ok(())
    }

    pub async fn repeat(&mut self, repeat: bool) -> Result<(), Error> {
        let repeat = if repeat { 1 } else { 0 };
        self.cmd(Cmd::new("repeat", Some(repeat))).await?;
        self.read_ok_resp().await?;
        Ok(())
    }

    pub async fn random(&mut self, random: bool) -> Result<(), Error> {
        let random = if random { 1 } else { 0 };
        self.cmd(Cmd::new("random", Some(random))).await?;
        self.read_ok_resp().await?;
        Ok(())
    }

    pub async fn consume(&mut self, consume: bool) -> Result<(), Error> {
        let consume = if consume { 1 } else { 0 };
        self.cmd(Cmd::new("consume", Some(consume))).await?;
        self.read_ok_resp().await?;
        Ok(())
    }

    // Playback controls

    pub async fn play(&mut self) -> Result<(), Error> {
        self.play_pause(true).await
    }

    pub async fn playid(&mut self, id: u32) -> Result<(), Error> {
        self.cmd(Cmd::new("playid", Some(id))).await?;
        self.read_ok_resp().await?;
        Ok(())
    }

    pub async fn pause(&mut self) -> Result<(), Error> {
        self.play_pause(false).await
    }

    pub async fn play_pause(&mut self, play: bool) -> Result<(), Error> {
        let play = if play { 0 } else { 1 };
        self.cmd(Cmd::new("pause", Some(play))).await?;
        self.read_ok_resp().await?;
        Ok(())
    }

    pub async fn next(&mut self) -> Result<(), Error> {
        self.cmd("next").await?;
        self.read_ok_resp().await?;
        Ok(())
    }

    pub async fn prev(&mut self) -> Result<(), Error> {
        self.cmd("prev").await?;
        self.read_ok_resp().await?;
        Ok(())
    }

    pub async fn stop(&mut self) -> Result<(), Error> {
        self.cmd("stop").await?;
        self.read_ok_resp().await?;
        Ok(())
    }

    // Music database commands

    pub async fn listall(&mut self, path: Option<String>) -> Result<Vec<String>, Error> {
        self.cmd(Cmd::new("listall", path)).await?;

        Ok(self
            .read_resp()
            .await?
            .lines()
            .filter_map(|line| {
                if line.starts_with("file: ") {
                    Some(line[6..].to_string())
                } else {
                    None
                }
            })
            .collect())
    }

    pub async fn listallinfo(&mut self, path: Option<&str>) -> Result<Vec<Mixed>, Error> {
        self.cmd(Cmd::new("listallinfo", path)).await?;

        let resp = self.read_resp().await?;
        let r = response::mixed(&resp);
        Ok(r)
    }

    // Queue handling commands

    pub async fn queue_add(&mut self, path: &str) -> Result<(), Error> {
        self.cmd(Cmd::new("add", Some(path))).await?;
        self.read_ok_resp().await
    }

    pub async fn queue_clear(&mut self) -> Result<(), Error> {
        self.cmd("clear").await?;
        self.read_ok_resp().await
    }

    pub async fn queue(&mut self) -> Result<Vec<Track>, Error> {
        self.cmd("playlistinfo").await?;
        let resp = self.read_resp().await?;
        let vec = response::tracks(&resp);
        Ok(vec)
    }

    /// # Example
    /// ```
    /// use async_mpd::{MpdClient, Error, Tag, Filter, ToFilterExpr};
    ///
    /// #[async_std::main]
    /// async fn main() -> Result<(), Error> {
    ///     // Connect to server
    ///     let mut mpd = MpdClient::new("localhost:6600").await?;
    ///
    ///     let mut filter = Filter::new()
    ///         .and(Tag::Artist.equals("The Beatles"))
    ///         .and(Tag::Album.contains("White"));
    ///
    ///     let res = mpd.search(&filter).await?;
    ///     println!("{:?}", res);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn search(&mut self, filter: &Filter) -> Result<Vec<Track>, Error> {
        self.cmd(Cmd::new("search", filter.to_query())).await?;
        let resp = self.read_resp().await?;
        let tracks = response::tracks(&resp);
        Ok(tracks)
    }

    async fn cmd(&mut self, cmd: impl Into<Cmd>) -> io::Result<()> {
        let r = cmd.into().to_string();
        self.bufreader.get_mut().write_all(r.as_bytes()).await?;
        Ok(())
    }

    /// Read all response lines
    async fn read_resp(&mut self) -> Result<String, Error> {
        let mut v = Vec::new();

        loop {
            let mut line = String::new();

            if self.bufreader.read_line(&mut line).await? == 0 {
                return Err(Error::Disconnected);
            }

            let line = line.trim();

            if line == "OK" {
                break;
            }

            if line.starts_with("ACK ") {
                log::trace!("Cmd error: {}", line);
                return Err(Error::CommandError { msg: line.into() });
            }

            v.push(line.to_string())
        }

        Ok(v.join("\n"))
    }

    /// Expect one line response
    async fn read_resp_line(&mut self) -> Result<String, Error> {
        let mut line = String::new();
        self.bufreader.read_line(&mut line).await?;
        Ok(line.trim().to_string())
    }

    /// Read and expect OK response line
    async fn read_ok_resp(&mut self) -> Result<(), Error> {
        let mut line = String::new();
        self.bufreader.read_line(&mut line).await?;

        if &line != "OK\n" {
            return Err(Error::ResponseError {
                reply: line.to_string(),
                errmsg: "Expected OK".to_string(),
            });
        }

        Ok(())
    }
}

struct Cmd {
    cmd: &'static str,
    arg: Option<String>,
}

impl Cmd {
    fn new<T: ToString>(cmd: &'static str, arg: Option<T>) -> Self {
        Self {
            cmd,
            arg: arg.map(|a| a.to_string()),
        }
    }

    fn to_string(&self) -> String {
        if let Some(arg) = &self.arg {
            format!("{} \"{}\"\n", self.cmd, arg.to_string())
        } else {
            format!("{}\n", self.cmd)
        }
    }
}

impl From<&'static str> for Cmd {
    fn from(cmd: &'static str) -> Self {
        Self { cmd, arg: None }
    }
}