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
use crate::errors::{MelodyErrors, MelodyErrorsKind};
use crate::song::{Playlist, Song};
use crate::utils::fmt_duration;
use rand::seq::SliceRandom;
use rand::thread_rng;
use rodio;
use std::fmt;
use std::fs::File;
use std::io::{BufReader, Write};
use tabwriter::TabWriter;

/// Music Player Status
/// Showing the status of the Music player
#[derive(Clone, Debug)]
pub enum MusicPlayerStatus {
    /// Music player has stopped
    /// Contains the previous song if any
    Stopped(Option<Song>),
    /// Now playing: song
    NowPlaying(Song),
    /// Paused: Song
    Paused(Song),
}

/// Displays the following
/// [Paused] : {Song} @ Time stamp
/// [Now Playing] : Song
/// [Stopped] : Last Played - Song
/// [Stopped]
impl fmt::Display for MusicPlayerStatus {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use crate::MusicPlayerStatus::*;
        match self.clone() {
            Paused(song) => write!(f, "[Paused] : {} @ {}", song, fmt_duration(&song.elapsed())),
            NowPlaying(song) => write!(f, "[Now Playing] : {}", song),
            Stopped(s) => match s {
                Some(song) => write!(f, "[Stopped] : Last Played - {}", song),
                None => write!(f, "[Stopped]"),
            },
        }
    }
}
// TODO: Implement Back
/// Music Player
#[allow(missing_debug_implementations)]
pub struct MusicPlayer {
    /// Songs in Queue
    playlist: Vec<Song>,
    /// Audio controller
    sink: rodio::Sink,
    /// Current song
    current: Option<Song>,
    /// Previous song
    previous: Option<Song>,
}

impl MusicPlayer {
    /// Constructs a new MusicPlayer
    pub fn new(playlist: Playlist) -> Self {
        // Audio endpoint (EX: Alsa)
        let endpoint =
            rodio::default_output_device().expect("Failed to find default music endpoint");
        MusicPlayer {
            // Remove all unsupported songs
            playlist: playlist.tracks,
            // Create audio controller
            sink: rodio::Sink::new(&endpoint),
            current: None,
            previous: None,
        }
    }

    /// Shuffle the order of the playlist
    pub fn shuffle(&mut self) {
        self.playlist.shuffle(&mut thread_rng());
    }

    /// Plays the first song in the Queue if any
    /// Otherwise throws an error
    pub fn start(&mut self) -> Result<(), MelodyErrors> {
        if self.playlist.is_empty() {
            Err(MelodyErrors::new(
                MelodyErrorsKind::EmptyQueue,
                "Playlist is empty",
                None,
            ))
        } else {
            if self.sink.empty() {
                let mut current = self.playlist.remove(0);

                // TODO: Make this return an error
                let file = File::open(&current)
                    .unwrap_or_else(|_| panic!("Failed to read {:#?}", current.file));
                // TODO: Make this return an error
                let source = rodio::Decoder::new(BufReader::new(file))
                    .unwrap_or_else(|_| panic!("Failed to decode {:#?}", current.file));
                self.sink.append(source);
                current.resume();
                self.current = Some(current);
            };
            Ok(())
        }
    }

    /// Resume's the song
    /// Should only be used of the song was paused
    /// Or it messes with the song's progress counter
    // TODO: Fix error when called when not stopped
    pub fn resume(&mut self) {
        self.sink.play();
        self.current = self.current.take().and_then(|mut s| {
            s.resume();
            Some(s)
        });
    }
    /// Pauses Song
    pub fn pause(&mut self) {
        self.sink.pause();
        // Update Song's playing time
        self.current = self.current.take().and_then(|mut s| {
            s.stop();
            Some(s)
        });
    }

    /// Stop's currently playing song
    // TODO: Fix error if no current song
    pub fn stop(&mut self) {
        self.sink.stop();
        self.previous = self.current.take().and_then(|mut s| {
            s.stop();
            Some(s)
        });
    }
    /// Play next Song in Queue
    /// TODO: Return something if there is nothing else
    pub fn play_next(&mut self) {
        let vol = self.sink.volume();
        self.stop();
        let endpoint =
            rodio::default_output_device().expect("Failed to find default music endpoint");
        self.sink = rodio::Sink::new(&endpoint);
        self.sink.set_volume(vol);
        let _ = self.start().is_ok();
    }
    /// Returns the music players volume
    /// Volume percentage is represented as a decimal
    pub fn volume(&self) -> f32 {
        self.sink.volume()
    }
    /// Set the volume of the music player
    /// volume: Percentage as a decimal
    pub fn set_volume(&mut self, volume: f32) {
        self.sink.set_volume(volume)
    }
    /// Lock current thread until current song ends
    pub fn lock(&self) {
        self.sink.sleep_until_end();
    }
    /// List current songs in queue
    pub fn queue(&self) -> &Vec<Song> {
        &self.playlist
    }
    /// Return the music players status
    pub fn status(&self) -> MusicPlayerStatus {
        if self.sink.empty() {
            MusicPlayerStatus::Stopped(self.previous.clone())
        } else if let Some(song) = self.current.clone() {
            if self.sink.is_paused() {
                MusicPlayerStatus::Paused(song)
            } else {
                MusicPlayerStatus::NowPlaying(song)
            }
        } else {
            MusicPlayerStatus::Stopped(self.previous.clone())
        }
    }
    /// Quit the music player
    pub fn quit(mut self) {
        self.stop();
        self.playlist = vec![];
    }
}

impl fmt::Display for MusicPlayer {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let now_playing = match self.current {
            Some(ref song) => {
                let status: &str = if self.sink.is_paused() {
                    "[paused] "
                } else {
                    ""
                };
                format!("{}{}\n", status, song)
            }
            None => String::new(),
        };
        let mut tw = TabWriter::new(Vec::new());
        let mut lines: Vec<String> = vec![String::from(
            "|\tArtist\t|\tAlbum\t|\tTitle\t|\tDuration\t|",
        )];
        for track in &self.playlist {
            let duration = fmt_duration(&track.duration);
            lines.push(format!(
                "|\t{}\t|\t{}\t|\t{}\t|\t{}\t|",
                track.artist().unwrap_or("Unknown Artist"),
                track.album().unwrap_or("Unknown Album"),
                track.title().unwrap_or("Unknown Title"),
                duration
            ))
        }
        write!(tw, "{}", lines.join("\n")).unwrap();
        tw.flush().unwrap();
        write!(
            f,
            "{}{}",
            now_playing,
            String::from_utf8(tw.into_inner().unwrap()).unwrap()
        )
    }
}

impl Drop for MusicPlayer {
    fn drop(&mut self) {
        self.sink.stop()
    }
}

/// an iterative music player
#[allow(missing_debug_implementations)]
pub struct MinimalMusicPlayer {
    sink: ::rodio::Sink,
    now_playing: Option<Song>,
    prev: Option<Song>,
    songs: Box<dyn Iterator<Item = Song>>,
}

impl Default for MinimalMusicPlayer {
    fn default() -> Self {
        let device = rodio::default_output_device().unwrap();
        let v: Vec<Song> = Vec::with_capacity(0);
        Self {
            sink: ::rodio::Sink::new(&device),
            now_playing: None,
            prev: None,
            songs: Box::new(v.into_iter()),
        }
    }
}

impl MinimalMusicPlayer {
    /// Set volume of music player
    pub fn set_volume(&mut self, volume: f32) {
        self.sink.set_volume(volume)
    }
    /// Sleep until the song is done
    pub fn sleep_until_end(&self) {
        self.sink.sleep_until_end()
    }
    /// Consume an iterator
    pub fn consume<I: 'static + Iterator<Item = Song>>(iter: I) -> Self {
        Self {
            songs: Box::new(iter),
            ..Default::default()
        }
    }
    /// Song is playing
    pub fn is_playing(&self) -> bool {
        !self.sink.empty()
    }
    /// Pause song
    pub fn pause(&mut self) {
        self.sink.pause()
    }
    /// Resume song
    pub fn resume(&mut self) {
        self.sink.play()
    }
    /// Stop song
    pub fn stop(&mut self) {
        self.sink.stop();
    }
    /// Get current volume
    pub fn volume(&self) -> f32 {
        self.sink.volume()
    }
}

impl Iterator for MinimalMusicPlayer {
    type Item = Song;
    fn next(&mut self) -> Option<Song> {
        let vol = self.sink.volume();
        self.sink.stop();
        let device = rodio::default_output_device().unwrap();
        if let Some(song) = self.songs.next() {
            if let Ok(f) = File::open(&song) {
                if let Ok(s) = rodio::Decoder::new(BufReader::new(f)) {
                    self.sink = rodio::Sink::new(&device);
                    self.sink.set_volume(vol);
                    self.prev = self.now_playing.replace(song);
                    self.sink.append(s);
                }
            }
        } else {
            self.now_playing = None;
        }
        self.now_playing.as_ref().cloned()
    }
}

impl ::std::iter::IntoIterator for Playlist {
    type Item = Song;
    type IntoIter = MinimalMusicPlayer;

    fn into_iter(self) -> MinimalMusicPlayer {
        let device = rodio::default_output_device().unwrap();
        MinimalMusicPlayer {
            sink: rodio::Sink::new(&device),
            prev: None,
            now_playing: None,
            songs: Box::new(self.tracks.into_iter()),
        }
    }
}