mparsed 0.2.0

Structs and logic to deserialize mpd (music player daemon) responses with serde
Documentation
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
use serde::de;
use std::collections::HashMap;
mod error;
use error::{Error, MpdResult};
use itertools::Itertools;
mod structs;
pub use structs::{File, Position, State, Stats, Status, Track, UnitResponse};

// some unprintable character to separate repeated keys
const SEPARATOR: char = '\x02';

/// Parse an interator of string slices into `T`,
/// returning Ok(T) if the data could be deserialized and the MPD response ended with `OK` or
/// `Error` if the deserialization failed or MPD sent an error message.
///
/// ```
/// # use mparsed::{Track, parse_response};
/// # use std::time::Duration;
/// let response = "file: 01 Track.flac
/// Last-Modified: 2018-03-07T13:11:43Z
/// duration: 123.45
/// Pos: 1
/// Id: 2
/// OK";
/// let parsed: Track = parse_response(response.lines()).unwrap();
///
/// assert_eq!(parsed.file, String::from("01 Track.flac"));
/// assert_eq!(parsed.duration, Some(Duration::from_secs_f64(123.45)));
/// ```
///
/// For responses that contain multiple instances of a struct (like playlists), see
/// [`parse_response_vec`].
///
/// [`parse_response_vec`]: fn.parse_response_vec.html
pub fn parse_response<'a, I: Iterator<Item = &'a str>, T: de::DeserializeOwned>(input: I) -> MpdResult<T> {
  let mut map: HashMap<String, String> = HashMap::new();
  for line in input {
    if line.starts_with("OK") {
      break;
    } else if let Some(message) = line.strip_prefix("ACK") {
      return Err(Error::from_str(message.trim()));
    }

    match line.splitn(2, ": ").next_tuple() {
      Some((k, v)) => {
        if let Some(existing) = map.get_mut(k) {
          existing.push(SEPARATOR);
          existing.push_str(v);
        } else {
          map.insert(k.to_string(), v.to_string());
        }
      }
      _ => panic!("invalid response line: {:?}", line),
    }
  }
  // Eventually, I’d like to use my own deserializer instead of envy
  Ok(envy::from_iter(map).unwrap())
}

/// Parse an iterator of string slices into a vector of `T`, splitting at any occurence of `first_key`.
/// One possible use for this is the `playlistinfo` command which returns all items in the current
/// playlist, where the `file: ` key denotes the start of a new item.
///
/// ## Multiple values for `first_key`
/// In some cases, like the `listfiles` command, there are multiple possible values for `first_key`,
/// so a vector can be specified.
/// ```
/// # use mparsed::{parse_response_vec, File};
/// let response = "file: A track.flac
/// size: 123456
/// Last-Modified: 2019-12-17T08:51:37Z
/// directory: A directory
/// Last-Modified: 2015-01-30T14:53:03Z
/// OK";
/// let files: Vec<File> = parse_response_vec(response.lines(), &vec!["file: ", "directory: "]).unwrap();
///
/// assert_eq!(files.len(), 2);
/// assert_eq!(files[0].name, String::from("A track.flac"));
/// assert!(files[1].is_directory());
/// ```
pub fn parse_response_vec<'a, I: Iterator<Item = &'a str>, T: de::DeserializeOwned>(input: I, first_keys: &[&str]) -> MpdResult<Vec<T>> {
  input
    .peekable()
    .batching(|it| {
      let mut v = match it.next() {
        // if the response is empty or we’ve reached the end,
        // we receive only the `OK` line.
        Some("OK") => return None,
        // otherwise this is the file attribute and thus the first key-value of this track
        Some(s) => vec![s],
        _ => return None,
      };
      // Only peek here in case we encounter the first key (e.g. `file:`) line which we still need for the next track.
      while let Some(l) = it.peek() {
        if first_keys.iter().any(|s| l.starts_with(s)) {
          return Some(v);
        }
        if l.starts_with("OK") {
          return Some(v);
        }
        v.push(it.next().unwrap());
      }
      None
    })
    .map(|b| parse_response(b.into_iter()))
    .collect()
}

/// Parse the `playlist` command, a list of key-value pairs, as a vector of filenames.
/// The playlist index of each item is *not* included because, if needed,
/// it can easily be added with `.enumerate()`.
pub fn parse_playlist<'a, I: Iterator<Item = &'a str>>(input: I) -> MpdResult<Vec<&'a str>> {
  input
    // `iter.scan((), |(), item| predicate(item))` is equivalent to map_while(predicate),
    // but the latter isn’t stabilized (yet).
    .scan((), |(), s| match s.splitn(2, ' ').next_tuple() {
      Some(("OK", _)) | None => None, // Covers OK with message and without
      Some(("ACK", err)) => Some(Err(Error::from_str(err))),
      Some((_, filename)) => Some(Ok(filename)),
    })
    .collect()
}

#[cfg(test)]
mod tests {
  use super::*;
  use chrono::DateTime;
  use std::time::Duration;

  #[test]
  fn track_de_test() {
    let input_str = "file: American Pie.flac
Last-Modified: 2019-12-16T21:38:54Z
Album: American Pie
Artist: Don McLean
Date: 1979
Genre: Rock
Title: American Pie
Track: 1
Time: 512
duration: 512.380
Pos: 1367
Id: 1368
OK";
    let t: Track = parse_response(input_str.lines()).unwrap();
    assert_eq!(
      t,
      Track {
        file: "American Pie.flac".to_string(),
        last_modified: Some(DateTime::parse_from_rfc3339("2019-12-16T21:38:54Z").unwrap()),
        album: Some("American Pie".to_string()),
        artist: Some("Don McLean".to_string()),
        date: Some(1979),
        genre: Some("Rock".to_string()),
        title: Some("American Pie".to_string()),
        track: Some(Position {
          item_position: 1,
          total_items: None,
        }),
        duration: Some(Duration::from_secs_f64(512.380)),
        pos: 1367,
        id: 1368,
        ..Track::default()
      }
    );
  }

  #[test]
  fn repeated_field_test() {
    let input_str = r#"file: 06 Symphonie No. 41 en ut majeur, K. 551 _Jupiter_ I. Allegro Vivace.flac
Last-Modified: 2018-11-11T09:01:54Z
Album: Symphonies n°40 & n°41
AlbumArtist: Wolfgang Amadeus Mozart; Royal Philharmonic Orchestra, Jane Glover
AlbumArtistSort: Mozart, Wolfgang Amadeus; Royal Philharmonic Orchestra, Glover, Jane
Artist: Wolfgang Amadeus Mozart
ArtistSort: Mozart, Wolfgang Amadeus
Composer: Wolfgang Amadeus Mozart
Date: 2005
Disc: 1
Disc: 1
MUSICBRAINZ_ALBUMARTISTID: b972f589-fb0e-474e-b64a-803b0364fa75
MUSICBRAINZ_ALBUMID: 688d9252-f897-4ab6-879d-5cb83bb71087
MUSICBRAINZ_ARTISTID: b972f589-fb0e-474e-b64a-803b0364fa75
MUSICBRAINZ_RELEASETRACKID: 54a2632f-fa98-3713-bd75-d7effc03d0b1
MUSICBRAINZ_TRACKID: 2dd10dd8-e8de-4479-a092-9a04c2760fd6
OriginalDate: 1993
Title: Symphonie No. 41 en ut majeur, K. 551 "Jupiter": I. Allegro Vivace
Track: 6
Track: 6
Time: 683
Performer: Royal Philharmonic Orchestra
duration: 682.840
Performer: Jane Glover
Pos: 3439
Id: 3440
OK"#;
    let t: Track = parse_response(input_str.lines()).unwrap();
    assert_eq!(
      t,
      Track {
        file: "06 Symphonie No. 41 en ut majeur, K. 551 _Jupiter_ I. Allegro Vivace.flac".to_string(),
        last_modified: Some(DateTime::parse_from_rfc3339("2018-11-11T09:01:54Z").unwrap()),
        album: Some("Symphonies n°40 & n°41".to_string()),
        artist: Some("Wolfgang Amadeus Mozart".to_string()),
        artist_sort: Some("Mozart, Wolfgang Amadeus".to_string()),
        album_artist: Some("Wolfgang Amadeus Mozart; Royal Philharmonic Orchestra, Jane Glover".to_string()),
        album_artist_sort: Some("Mozart, Wolfgang Amadeus; Royal Philharmonic Orchestra, Glover, Jane".to_string()),
        composer: Some("Wolfgang Amadeus Mozart".to_string()),
        date: Some(2005),
        original_date: Some(1993),
        title: Some("Symphonie No. 41 en ut majeur, K. 551 \"Jupiter\": I. Allegro Vivace".to_string()),
        disc: Some(Position {
          item_position: 1,
          total_items: Some(1),
        }),
        track: Some(Position {
          item_position: 6,
          total_items: Some(6),
        }),
        duration: Some(Duration::from_secs_f64(682.840)),
        pos: 3439,
        id: 3440,
        performers: vec!["Royal Philharmonic Orchestra".to_string(), "Jane Glover".to_string()],
        musicbrainz_albumartistid: Some("b972f589-fb0e-474e-b64a-803b0364fa75".to_string()),
        musicbrainz_albumid: Some("688d9252-f897-4ab6-879d-5cb83bb71087".to_string()),
        musicbrainz_artistid: Some("b972f589-fb0e-474e-b64a-803b0364fa75".to_string()),
        musicbrainz_releasetrackid: Some("54a2632f-fa98-3713-bd75-d7effc03d0b1".to_string()),
        musicbrainz_trackid: Some("2dd10dd8-e8de-4479-a092-9a04c2760fd6".to_string()),
        ..Track::default()
      }
    );
  }
  #[test]
  fn de_status_test() {
    let input_str = "volume: 74
repeat: 0
random: 1
single: 0
consume: 0
playlist: 6
playlistlength: 5364
mixrampdb: 0.000000
state: play
song: 3833
songid: 3834
time: 70:164
elapsed: 69.642
bitrate: 702
duration: 163.760
audio: 44100:16:2
nextsong: 4036
nextsongid: 4037
OK";
    let s: Status = parse_response(input_str.lines()).unwrap();
    assert_eq!(
      s,
      Status {
        volume: Some(74),
        random: true,
        playlist: 6,
        playlistlength: 5364,
        mixrampdb: 0.0,
        state: State::Play,
        song: Some(3833),
        songid: Some(3834),
        elapsed: Some(Duration::from_secs_f64(69.642)),
        bitrate: Some(702),
        duration: Some(Duration::from_secs_f64(163.760)),
        audio: Some(String::from("44100:16:2")),
        nextsong: Some(4036),
        nextsongid: Some(4037),
        ..Status::default()
      }
    );
  }
  #[test]
  fn de_playlistinfo_test() {
    let input_str = "file: 137 A New World.mp3
Last-Modified: 2018-03-07T13:11:43Z
Artist: Arata Iiyoshi
Title: A New World
Album: Pokemon Mystery Dungeon: Explorers of Sky
duration: 225.802
Pos: 1000
Id: 6365
file: 139 Thoughts For Friends.mp3
Last-Modified: 2018-03-07T13:11:43Z
Artist: Arata Iiyoshi
Title: Thoughts For Friends
Album: Pokemon Mystery Dungeon: Explorers of Sky
duration: 66.560
Pos: 1001
Id: 6366
file: 140 A Message On the Wind.mp3
Last-Modified: 2018-03-07T13:11:43Z
Artist: Arata Iiyoshi
Title: A Message On the Wind
Album: Pokemon Mystery Dungeon: Explorers of Sky
duration: 50.155
Pos: 1002
Id: 6367
OK";
    let queue = parse_response_vec(input_str.lines(), &vec!["file: "]);
    let first_track = Track {
      file: "137 A New World.mp3".into(),
      title: Some("A New World".into()),
      artist: Some("Arata Iiyoshi".into()),
      album: Some("Pokemon Mystery Dungeon: Explorers of Sky".into()),
      last_modified: Some(DateTime::parse_from_rfc3339("2018-03-07T13:11:43Z").unwrap()),
      duration: Some(Duration::from_secs_f64(225.802)),
      pos: 1000,
      id: 6365,
      ..Track::default()
    };
    assert_eq!(
      queue,
      Ok(vec![
        first_track.clone(),
        Track {
          file: "139 Thoughts For Friends.mp3".into(),
          title: Some("Thoughts For Friends".into()),
          duration: Some(Duration::from_secs_f64(66.56)),
          pos: 1001,
          id: 6366,
          ..first_track.clone()
        },
        Track {
          file: "140 A Message On the Wind.mp3".into(),
          title: Some("A Message On the Wind".into()),
          duration: Some(Duration::from_secs_f64(50.155)),
          pos: 1002,
          id: 6367,
          ..first_track
        },
      ])
    );

    let queue = parse_response_vec("OK".lines(), &vec!["file: "]);
    assert_eq!(queue, Ok(Vec::<Track>::new()));
  }

  #[test]
  fn de_stats_test() {
    let input_str = "uptime: 23691
playtime: 11288
artists: 2841
albums: 2455
songs: 40322
db_playtime: 11620284
db_update: 1588433046
OK";
    let s: Stats = parse_response(input_str.lines()).unwrap();
    assert_eq!(
      s,
      Stats {
        uptime: Duration::from_secs(23691),
        playtime: Duration::from_secs(11288),
        artists: 2841,
        albums: 2455,
        songs: 40322,
        db_playtime: Duration::from_secs(11620284),
        db_update: 1588433046,
      }
    );
  }

  #[test]
  fn de_unit_response_test() {
    let success = "OK";
    let r: Result<UnitResponse, _> = parse_response(success.lines());
    assert_eq!(r, Ok(UnitResponse {}));

    let failure = r#"ACK [2@0] {consume} wrong number of arguments for "consume""#;
    let r: Result<UnitResponse, _> = parse_response(failure.lines());
    assert_eq!(
      r,
      Err(error::Error::from_str(r#"[2@0] {consume} wrong number of arguments for "consume""#))
    );
  }

  #[test]
  fn parse_playlist_test() {
    let input = "0:file: Brent Barkman & Maribeth Solomon/Sunless Sea (2015)/01 Opening Screen.flac
1:file: Brent Barkman & Maribeth Solomon/Sunless Sea (2015)/02 Wolfstack Lights.flac
2:file: Brent Barkman & Maribeth Solomon/Sunless Sea (2015)/03 Submergio Viol.flac
3:file: Brent Barkman & Maribeth Solomon/Sunless Sea (2015)/08 Dark Sailing.flac
4:file: Brent Barkman & Maribeth Solomon/Sunless Sea (2015)/17 The Sea Does Not Forgive.flac
5:file: Brent Barkman & Maribeth Solomon/Sunless Sea (2015)/18 Hope Is an Anchor.flac
OK";

    match parse_playlist(input.lines()) {
      Err(_) => panic!("Should not be an error"),
      Ok(tracks) => assert_eq!(
        tracks,
        vec![
          "Brent Barkman & Maribeth Solomon/Sunless Sea (2015)/01 Opening Screen.flac",
          "Brent Barkman & Maribeth Solomon/Sunless Sea (2015)/02 Wolfstack Lights.flac",
          "Brent Barkman & Maribeth Solomon/Sunless Sea (2015)/03 Submergio Viol.flac",
          "Brent Barkman & Maribeth Solomon/Sunless Sea (2015)/08 Dark Sailing.flac",
          "Brent Barkman & Maribeth Solomon/Sunless Sea (2015)/17 The Sea Does Not Forgive.flac",
          "Brent Barkman & Maribeth Solomon/Sunless Sea (2015)/18 Hope Is an Anchor.flac",
        ]
      ),
    }

    let input = "ACK [] {playlistinfo} something went wrong";
    match parse_playlist(input.lines()) {
      Ok(_) => panic!("Should have failed"),
      Err(e) => assert_eq!(e.message, "[] {playlistinfo} something went wrong"),
    }
  }

  #[test]
  fn file_list_test() {
    let input = "file: 11 奏(かなで)(original スキマスイッチ).flac
size: 18948052
Last-Modified: 2019-12-17T08:51:37Z
directory: Scans
Last-Modified: 2015-01-30T14:53:03Z
file: 15 風ハ旅スル(スマートフォンゲーム「風パズル 黒猫と白猫の夢見た世界」テーマ曲).flac
size: 13058417
Last-Modified: 2019-12-17T08:51:41Z
OK";
    let parsed: Vec<File> = parse_response_vec(input.lines(), &vec!["file: ", "directory: "]).unwrap();
    assert_eq!(
      parsed,
      vec![
        File {
          name: "11 奏(かなで)(original スキマスイッチ).flac".into(),
          last_modified: DateTime::parse_from_rfc3339("2019-12-17T08:51:37Z").unwrap(),
          size: 18948052
        },
        File {
          name: "Scans".into(),
          last_modified: DateTime::parse_from_rfc3339("2015-01-30T14:53:03Z").unwrap(),
          size: 0
        },
        File {
          name: "15 風ハ旅スル(スマートフォンゲーム「風パズル 黒猫と白猫の夢見た世界」テーマ曲).flac".into(),
          last_modified: DateTime::parse_from_rfc3339("2019-12-17T08:51:41Z").unwrap(),
          size: 13058417
        },
      ]
    );
    assert_eq!(
      parsed.iter().map(|f| f.is_directory()).collect::<Vec<_>>(),
      vec![false, true, false],
    );
  }
}