mpd-easy 0.2.1

A wrapper around the `mpd` crate simplifying common tasks.
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
use std::fmt;
use std::path::{Path, PathBuf};
use std::time::Duration;

use eyre::WrapErr;
use serde::Serialize;

use crate::{
    range,
    range::INVALID_RANGE,
    song::Current,
    song::Finder,
    song::Listing,
    song::Playlist,
    song::Playlists,
    song::Song,
    song::TrackList,
    stats::Output,
    stats::Outputs,
    stats::Stats,
    status::Status,
    time, {OnOff, OutputFormat},
};

const NO_OUT: String = String::new();

#[derive(PartialEq)]
enum Direction {
    Forward,
    Reverse,
}

#[derive(Serialize)]
pub struct Versions {
    mpd: String,
    mp_cli: String,
}

impl fmt::Display for Versions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "mpd={}\nmp-cli={}", self.mpd, self.mp_cli)
    }
}

pub struct Client {
    client: mpd::Client,
    format: OutputFormat,
}

impl Client {
    pub fn new(
        bind_to_address: &str,
        port: &str,
        format: Option<OutputFormat>,
    ) -> eyre::Result<Client> {
        let format = format.unwrap_or(OutputFormat::Json);
        let client = mpd::Client::connect(format!("{bind_to_address}:{port}"))
            .wrap_err("Error connecting to mpd server".to_string())?;

        Ok(Self { client, format })
    }

    //
    // queue related commands
    //
    pub fn add(&mut self, path: &str) -> eyre::Result<Option<String>> {
        let music_dir = self.client.music_directory()?;

        let absolute_path = if path.starts_with(&music_dir) {
            path.to_string()
        } else {
            PathBuf::from(&music_dir)
                .join(path)
                .to_str()
                .unwrap()
                .to_string()
        };

        let mut finder = Finder::new(music_dir);

        finder.find(Path::new(Path::new(&absolute_path)))?;

        for file in finder.found {
            let song = mpd::song::Song {
                file: file.relative_path,
                ..Default::default()
            };

            self.client
                .push(song.clone())
                .wrap_err(format!("unkown or inalid path: {}", song.file))?;
        }

        Ok(None)
    }

    pub fn crop(&mut self) -> eyre::Result<Option<String>> {
        // determine current song position
        // remove all songs before current song
        // remove all songs from 1 onwards
        let status = self.status()?;
        let current_position = status.position;
        let length = status.queue_count;

        if length < 1 {
            return self.current_status();
        }

        self.client.delete(0..current_position)?;
        // it doesn't matter that the range is out of bounds
        self.client.delete(1..length)?;

        self.current_status()
    }

    pub fn del(
        &mut self,
        position: Option<u32>,
    ) -> eyre::Result<Option<String>> {
        let position = match position {
            Some(position) => position,
            None => self.status()?.position,
        };

        self.client.delete(position)?;

        self.current_status()
    }

    //
    // playback related commands
    //
    pub fn current(&mut self) -> eyre::Result<Option<String>> {
        let current = Current::from(self.status()?);

        let response = match self.format {
            OutputFormat::Json => serde_json::to_string(&current)?,
            OutputFormat::Text => current.to_string(),
            OutputFormat::None => NO_OUT,
        };

        Ok(Some(response))
    }

    pub fn play(
        &mut self,
        position: Option<u32>,
    ) -> eyre::Result<Option<String>> {
        if position.is_none() {
            self.client.play()?;
            return self.current_status();
        }
        // TODO: this is super hacky, can't find a "jump" in rust-mpd

        // pause
        // get current position
        // next/prev to desired position
        // play

        let position = position.unwrap();
        let current_position = self.status()?.position;

        self.pause()?;

        if current_position > position {
            for _ in (position..current_position).rev() {
                self.prev()?;
            }
        } else {
            for _ in (current_position..position).rev() {
                self.next()?;
            }
        }

        self.client.play()?;

        self.current_status()
    }

    // allowing because this follows an external api naming convention
    #[allow(clippy::should_implement_trait)]
    pub fn next(&mut self) -> eyre::Result<Option<String>> {
        self.client.next()?;

        self.current_status()
    }

    pub fn prev(&mut self) -> eyre::Result<Option<String>> {
        self.client.prev()?;

        self.current_status()
    }

    pub fn pause(&mut self) -> eyre::Result<Option<String>> {
        self.client.pause(true)?;

        self.current_status()
    }

    pub fn pause_if_playing(&mut self) -> eyre::Result<Option<String>> {
        match self.client.status()?.state {
            mpd::State::Play => self.pause(),
            mpd::State::Pause | mpd::State::Stop => Err(eyre::eyre!("")),
        }
    }

    pub fn cdprev(&mut self) -> eyre::Result<Option<String>> {
        let default_duration = Duration::from_secs(0);
        let status = &self.client.status()?;
        let current = status.elapsed.unwrap_or(default_duration).as_secs();

        if current < 3 {
            self.prev()
        } else {
            let place = match status.song {
                Some(ref song) => song.pos,
                None => 0,
            };
            self.client.seek(place, 0)?;

            self.current_status()
        }
    }

    pub fn toggle(&mut self) -> eyre::Result<Option<String>> {
        match self.client.status()?.state {
            mpd::State::Play => self.pause(),
            mpd::State::Pause | mpd::State::Stop => self.play(None),
        }
    }

    pub fn stop(&mut self) -> eyre::Result<Option<String>> {
        self.client.stop()?;

        self.current_status()
    }

    pub fn seek(&mut self, position: &str) -> eyre::Result<Option<String>> {
        let current_status = self.status()?;

        // valid position syntax: [+-][HH:MM:SS]|<0-100>%
        let place = if position.contains('%') {
            let position = position.replace('%', "");

            let percent = position.parse::<u8>().wrap_err(format!(
                "\"{position}\" must be a value between 0 and 100"
            ))?;
            if percent > 100 {
                return Err(eyre::eyre!(
                    "\"{position}\" must be a value between 0 and 100"
                ));
            }

            let length = current_status.track_length.as_secs;
            let percent = i64::from(percent);

            length * percent / 100
        } else if position.contains('+') || position.contains('-') {
            current_status.elapsed.compute_offset(position)
        } else {
            time::Time::from(position.to_string()).as_secs
        };

        let position = self.status()?.position;

        self.client.seek(position, place)?;

        self.stats()
    }

    pub fn seekthrough(
        &mut self,
        position: &str,
    ) -> eyre::Result<Option<String>> {
        let mut direction = Direction::Forward;

        // valid position syntax: [+-][HH:MM:SS]
        let mut place = if position.contains('%') {
            return Err(eyre::eyre!(
                "seekthrough does not support percentage based seeking"
            ));
        } else {
            // if `-` present then back otherwise assume forward
            if position.contains('-') {
                direction = Direction::Reverse;
            }
            time::Time::from(position.to_string()).as_secs
        };

        let queue = self.client.queue()?;
        let start = usize::try_from(self.status()?.position)?;
        let mut elapsed = self.status()?.elapsed.as_secs;

        match direction {
            Direction::Forward => {
                for song in queue.iter().cycle().skip(start) {
                    let current_song_duration =
                        i64::try_from(song.duration.unwrap().as_secs())?;
                    let remainder = current_song_duration - elapsed - place;

                    // seek position fits the current song
                    if remainder >= 0 {
                        let position = song.place.unwrap().id;
                        self.client.seek(position, elapsed + place)?;
                        break;
                    }

                    place = remainder.abs();
                    elapsed = 0;
                }
            }
            Direction::Reverse => {
                // queue is reversed so we need to start from the end
                let start = queue.len() - start - 1;

                for song in queue.iter().rev().cycle().skip(start) {
                    let current_song_duration =
                        i64::try_from(song.duration.unwrap().as_secs())?;

                    let remainder = if elapsed > 0 {
                        elapsed - place
                    } else {
                        current_song_duration - place
                    };

                    // seek position fits the current song
                    if remainder >= 0 {
                        let position = song.place.unwrap().id;
                        self.client.seek(position, remainder)?;
                        break;
                    }

                    place = remainder.abs();
                    elapsed = 0;
                }
            }
        }

        self.stats()
    }

    //
    // playlist related commands
    //

    pub fn clear(&mut self) -> eyre::Result<Option<String>> {
        self.client.clear()?;

        self.current_status()
    }

    pub fn outputs(&mut self) -> eyre::Result<Option<String>> {
        let outputs = self.client.outputs()?;
        let outputs: Vec<Output> =
            outputs.into_iter().map(Output::from).collect();
        let outputs = Outputs { outputs };

        let response = match self.format {
            OutputFormat::Json => serde_json::to_string(&outputs)?,
            OutputFormat::Text => outputs.to_string(),
            OutputFormat::None => NO_OUT,
        };

        Ok(Some(response))
    }

    fn output_for(&mut self, name_or_id: &str) -> Result<u32, eyre::Error> {
        let id: u32 = if let Ok(parsed_id) = name_or_id.parse::<u32>() {
            parsed_id
        } else {
            self.client
                .outputs()?
                .iter()
                .find(|&o| o.name == name_or_id)
                .ok_or_else(|| eyre::eyre!("unknown output: {}", name_or_id))?
                .id
        };

        Ok(id)
    }

    fn enable_or_disable(
        &mut self,
        enable: bool,
        args: Vec<String>,
    ) -> eyre::Result<Option<String>> {
        let mut only = false;
        let mut outputs = Vec::new();

        for arg in args {
            if arg == "only" {
                only = true;
            } else {
                outputs.push(arg);
            }
        }

        if only {
            // first disable all outputs
            for output in self.client.outputs()? {
                self.client.output(output, enable)?;
            }
        }

        for name_or_id in outputs {
            let id = self.output_for(&name_or_id)?;

            self.client.output(id, enable)?;
        }

        self.outputs()
    }

    pub fn enable(
        &mut self,
        args: Vec<String>,
    ) -> eyre::Result<Option<String>> {
        self.enable_or_disable(true, args)
    }

    pub fn disable(
        &mut self,
        args: Vec<String>,
    ) -> eyre::Result<Option<String>> {
        self.enable_or_disable(false, args)
    }

    pub fn toggle_output(
        &mut self,
        args: Vec<String>,
    ) -> eyre::Result<Option<String>> {
        if args.is_empty() {
            return Err(eyre::eyre!("no outputs given"));
        }

        for name_or_id in args {
            let id = self.output_for(&name_or_id)?;

            self.client.out_toggle(id)?;
        }

        self.outputs()
    }

    pub fn queued(&mut self) -> eyre::Result<Option<String>> {
        if let Some(song) =
            self.client.queue().map_err(|e| eyre::eyre!(e))?.first()
        {
            // safe to unwrap because we know we have a song
            let current = Current::from(Song {
                inner: song.clone(),
            });

            let response = match self.format {
                OutputFormat::Json => serde_json::to_string(&current)?,
                OutputFormat::Text => current.to_string(),
                OutputFormat::None => NO_OUT,
            };

            Ok(Some(response))
        } else {
            Ok(None)
        }
    }

    pub fn shuffle(&mut self) -> eyre::Result<Option<String>> {
        self.client.shuffle(..)?;

        self.current_status()
    }

    pub fn lsplaylists(&mut self) -> eyre::Result<Option<String>> {
        let playlists = self.client.playlists()?;
        let playlists: Vec<Playlist> = playlists
            .into_iter()
            .map(|p| Playlist::from(p.name))
            .collect();
        let playlists = Playlists { playlists };

        let response = match self.format {
            OutputFormat::Json => serde_json::to_string(&playlists)?,
            OutputFormat::Text => playlists.to_string(),
            OutputFormat::None => NO_OUT,
        };

        Ok(Some(response))
    }

    pub fn load(
        &mut self,
        name: &String,
        range: Option<String>,
    ) -> eyre::Result<Option<String>> {
        match range {
            Some(range_str) => {
                let range_or_index = range::Parser::new(&range_str)?;

                if !range_or_index.is_range {
                    return Err(eyre::eyre!(INVALID_RANGE));
                }

                self.client.load(name, range_or_index.range)?;
            }
            None => {
                self.client.load(name, ..)?;
            }
        }

        Ok(Some(format!("loading: {name}")))
    }

    /// Retrieves a list of song files from a given directory
    fn files_for(
        &mut self,
        file: Option<&str>,
    ) -> Result<Vec<String>, eyre::Error> {
        let all_files = Listing::from(self.client.listall()?);

        let files = if let Some(ref file) = file {
            // TODO: this is inefficient but it's the only way I see at the moment
            all_files
                .listing
                .iter()
                .filter(|song| song.starts_with(file))
                .cloned()
                .collect::<Vec<_>>()
        } else {
            all_files.listing.clone()
        };

        Ok(files)
    }

    pub fn insert(&mut self, uri: &str) -> eyre::Result<Option<String>> {
        let files = self.files_for(Some(uri))?;

        for file in &files {
            let song = mpd::song::Song {
                file: file.to_string(),
                ..Default::default()
            };

            self.client.insert(song, 0)?;
        }

        Ok(None)
    }

    pub fn prio(
        &mut self,
        priority: &str,
        position_or_range: &str,
    ) -> eyre::Result<Option<String>> {
        let priority = u8::try_from(priority.parse::<u32>()?).wrap_err(
            format!("\"{priority}\" must be a value between 0 and 255"),
        )?;

        let queue_size = u32::try_from(self.client.queue()?.len())?;
        let position_or_range = range::Parser::new(position_or_range)?;

        if position_or_range.index > queue_size {
            return Err(eyre::eyre!(
                "position ({}) must be less than or equal to the queue length {}",
                position_or_range.index,
                queue_size,
            ));
        }

        if position_or_range.is_range {
            self.client.priority(position_or_range.range, priority)?;
        } else {
            self.client.priority(position_or_range.index, priority)?;
        };

        Ok(None)
    }

    pub fn playlist(
        &mut self,
        name: Option<String>,
    ) -> eyre::Result<Option<String>> {
        // if given a name list songs in that playlist
        // if `None` list songs in current playlist
        let songs = match name {
            Some(name) => self.client.playlist(&name)?,
            None => self.client.queue()?,
        };

        let songs: Vec<Current> = songs
            .into_iter()
            .map(|s| Current::from(Song { inner: s }))
            .collect();
        let track_list = TrackList { songs };

        let response = match self.format {
            OutputFormat::Json => serde_json::to_string(&track_list)?,
            OutputFormat::Text => track_list.to_string(),
            OutputFormat::None => NO_OUT,
        };

        Ok(Some(response))
    }

    pub fn listall(
        &mut self,
        file: Option<&str>,
    ) -> eyre::Result<Option<String>> {
        let files = Listing::from(self.files_for(file)?);

        let response = match self.format {
            OutputFormat::Json => serde_json::to_string(&files)?,
            OutputFormat::Text => files.to_string(),
            OutputFormat::None => NO_OUT,
        };

        Ok(Some(response))
    }

    pub fn ls(
        &mut self,
        directory: Option<&str>,
    ) -> eyre::Result<Option<String>> {
        let directory = directory.unwrap_or("");
        let listing = self.client.listfiles(directory)?;
        let filter_for = if let Some(entry) = listing.first() {
            entry.0.as_str()
        } else {
            "directory"
        };

        let results = Listing::from(
            listing
                .clone()
                .into_iter()
                .filter(|(key, _)| key == filter_for)
                .map(|(_, value)| {
                    PathBuf::from(&directory)
                        .join(value)
                        .to_str()
                        .unwrap()
                        .to_string()
                })
                .collect::<Vec<String>>(),
        );

        let response = match self.format {
            OutputFormat::Json => serde_json::to_string(&results)?,
            OutputFormat::Text => results.to_string(),
            OutputFormat::None => NO_OUT,
        };

        Ok(Some(response))
    }

    pub fn repeat(
        &mut self,
        state: Option<OnOff>,
    ) -> eyre::Result<Option<String>> {
        let state = match state {
            Some(state) => state == OnOff::On,
            None => !self.client.status()?.repeat,
        };

        self.client.repeat(state)?;

        self.current_status()
    }

    pub fn random(
        &mut self,
        state: Option<OnOff>,
    ) -> eyre::Result<Option<String>> {
        let state = match state {
            Some(state) => state == OnOff::On,
            None => !self.client.status()?.random,
        };

        self.client.random(state)?;

        self.current_status()
    }

    pub fn single(
        &mut self,
        state: Option<OnOff>,
    ) -> eyre::Result<Option<String>> {
        let state = match state {
            Some(state) => state == OnOff::On,
            None => !self.client.status()?.single,
        };

        self.client.single(state)?;

        self.current_status()
    }

    // TODO: better name or abstraction?
    pub fn _search(
        &mut self,
        tag: &str,
        query: &str,
    ) -> eyre::Result<Vec<mpd::Song>> {
        let term = mpd::Term::Tag(tag.into());
        let mut binding = mpd::Query::new();
        let songs = binding.and(term, query);

        Ok(self.client.search(songs, None)?)
    }

    // TODO: better name or abstraction?
    pub fn _find(
        &mut self,
        tag: &str,
        query: &str,
    ) -> eyre::Result<Vec<mpd::Song>> {
        let term = mpd::Term::Tag(tag.into());
        let mut binding = mpd::Query::new();
        let songs = binding.and(term, query);

        Ok(self.client.search(songs, None)?)
    }

    pub fn search(
        &mut self,
        tag: &str,
        query: &str,
    ) -> eyre::Result<Option<String>> {
        let songs = self._search(tag, query)?;
        let files = Listing::from(songs);

        let response = match self.format {
            OutputFormat::Json => serde_json::to_string(&files)?,
            OutputFormat::Text => files.to_string(),
            OutputFormat::None => NO_OUT,
        };

        Ok(Some(response))
    }

    pub fn search_add(
        &mut self,
        tag: &str,
        query: &str,
    ) -> eyre::Result<Option<String>> {
        let songs = self._search(tag, query)?;

        for song in songs {
            self.client
                .push(song.clone())
                .wrap_err(format!("unkown or inalid path: {}", song.file))?;
        }

        Ok(None)
    }

    pub fn find(
        &mut self,
        tag: &str,
        query: &str,
    ) -> eyre::Result<Option<String>> {
        let songs = self._find(tag, query)?;
        let files = Listing::from(songs);

        let response = match self.format {
            OutputFormat::Json => serde_json::to_string(&files)?,
            OutputFormat::Text => files.to_string(),
            OutputFormat::None => NO_OUT,
        };

        Ok(Some(response))
    }

    pub fn find_add(
        &mut self,
        tag: &str,
        query: &str,
    ) -> eyre::Result<Option<String>> {
        let songs = self._find(tag, query)?;

        for song in songs {
            self.client
                .push(song.clone())
                .wrap_err(format!("unkown or inalid path: {}", song.file))?;
        }

        Ok(None)
    }

    pub fn list(&mut self, tag: &str) -> eyre::Result<Option<String>> {
        let term = mpd::Term::Tag(tag.into());
        let query = mpd::Query::new();

        let results = self.client.list(&term, &query)?;
        let files = Listing::from(results);

        let response = match self.format {
            OutputFormat::Json => serde_json::to_string(&files)?,
            OutputFormat::Text => files.to_string(),
            OutputFormat::None => NO_OUT,
        };

        Ok(Some(response))
    }

    pub fn consume(
        &mut self,
        state: Option<OnOff>,
    ) -> eyre::Result<Option<String>> {
        let state = match state {
            Some(state) => state == OnOff::On,
            None => !self.client.status()?.consume,
        };

        self.client.consume(state)?;

        self.current_status()
    }

    pub fn crossfade(
        &mut self,
        seconds: Option<String>,
    ) -> eyre::Result<Option<String>> {
        let crossfade = match seconds {
            Some(secs) => secs.parse::<i64>().wrap_err(format!(
                "\"{secs}\" is not 0 or a positive number"
            ))?,
            None => 0,
        };

        self.client
            .crossfade(crossfade)
            .wrap_err(format!("\"{crossfade}\" is too large"))?;

        Ok(Some(format!("crossfade: {crossfade}")))
    }

    pub fn version(&mut self) -> eyre::Result<Option<String>> {
        let mpd = format!(
            "{}.{}.{}",
            self.client.version.0, self.client.version.1, self.client.version.2
        );
        let mp_cli = env!("CARGO_PKG_VERSION").to_string();

        let versions = Versions { mpd, mp_cli };

        let response = match self.format {
            OutputFormat::Json => serde_json::to_string(&versions)?,
            OutputFormat::Text => versions.to_string(),
            OutputFormat::None => NO_OUT,
        };

        Ok(Some(response))
    }

    pub fn stats(&mut self) -> eyre::Result<Option<String>> {
        let stats = Stats::new(self.client.stats()?);

        let response = match self.format {
            OutputFormat::Json => serde_json::to_string(&stats)?,
            OutputFormat::Text => stats.to_string(),
            OutputFormat::None => NO_OUT,
        };

        Ok(Some(response))
    }

    pub fn save(&mut self, name: &str) -> eyre::Result<Option<String>> {
        self.client
            .save(name)
            .wrap_err(format!("Playlist already exists: {name}"))?;

        Ok(None)
    }

    pub fn rm(&mut self, name: &str) -> eyre::Result<Option<String>> {
        self.client
            .pl_remove(name)
            .wrap_err(format!("Unknown playlist: {name}"))?;

        Ok(None)
    }

    //
    // volume related commands
    //

    pub fn set_volume(&mut self, input: &str) -> eyre::Result<Option<String>> {
        let current = self.client.status()?.volume;

        let target = match input {
            matched if matched.starts_with('+') => {
                if let Ok(volume) = matched[1..].parse::<i8>() {
                    current.checked_add(volume).unwrap_or(100).min(100)
                } else {
                    panic!("Invalid volume increment, must be between 1-100")
                }
            }
            matched if matched.starts_with('-') => {
                if let Ok(volume) = matched[1..].parse::<i8>() {
                    current.checked_sub(volume).unwrap_or(100).max(0)
                } else {
                    panic!("Invalid volume increment, must be between 1-100")
                }
            }
            _ => input.parse::<i8>().unwrap_or(0),
        };

        self.client
            .volume(target)
            .map(|()| None)
            .map_err(eyre::Report::from)
    }

    //
    // output related commands
    //

    pub fn status(&mut self) -> eyre::Result<Status> {
        let status = self.client.status()?;

        let volume = status.volume.to_string();

        let current_song = self.client.currentsong()?;

        let artist = current_song
            .as_ref()
            .and_then(|song| song.artist.as_ref())
            .map_or(String::new(), ToString::to_string);

        let album = current_song
            .as_ref()
            .and_then(|song| {
                song.tags
                    .iter()
                    .find(|&(key, _)| key.to_lowercase() == "album")
            })
            .map_or_else(String::new, |(_, value)| value.clone());

        let title = current_song
            .as_ref()
            .and_then(|song| song.title.as_ref())
            .map_or(String::new(), ToString::to_string);

        let position = match status.song {
            Some(song) => song.pos,
            None => 0,
        };

        let time = crate::time::Track::from(status.time);

        let file_path =
            self.client.currentsong()?.map(|song| song.file.clone());

        Ok(Status {
            volume,
            state: crate::status::State::from(status.state),
            artist,
            album,
            title,
            position,
            queue_count: status.queue_len,
            elapsed: time.elapsed,
            track_length: time.total,
            repeat: OnOff::from(status.repeat),
            random: OnOff::from(status.random),
            single: OnOff::from(status.single),
            consume: OnOff::from(status.consume),
            file_path,
        })
    }

    pub fn current_status(&mut self) -> eyre::Result<Option<String>> {
        let status = self.status()?;
        let response = match self.format {
            OutputFormat::Json => serde_json::to_string(&status)?,
            OutputFormat::Text => format!("{status}"),
            OutputFormat::None => NO_OUT,
        };

        Ok(Some(response))
    }
}