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
//! # Music Lounge player client library
//!
//! Client library to allow interaction with Music Lounge processes
use std::env;
use lazy_static::lazy_static;
use rust_utils::logging::Log;
use mlounge_core::{
    library::{Playlist, Song, Library, PlaylistStore},
    player::{PlayerResult, audio_cmd}
};

pub use mlounge_core::player::{PlayerCommand, PlayerState, PlayerStatus, RepeatMode};

lazy_static! {
    static ref TMP_DIR: String = format!("/tmp/mlounge-{}/", env::var("USER").expect("What is your name again?"));
    static ref LOG: Log = Log::new("mlounge", "music-lounge");
}

/// Client object for the user interface, used to control the background process
pub struct MLoungeClient {
    /// The play queue (can be a playlist)
    pub queue: Playlist,

    /// The currently playing song
    pub song: Song,

    /// The state of the player
    pub state: PlayerState,

    /// Should one song, all songs, or no songs be repeated?
    pub repeat: RepeatMode,

    // the song the player is at in the playlist
    position: usize,

    // the id of that song
    id: u64
}

impl MLoungeClient {
    /// Create a new `MLoungeClient`
    pub fn new() -> MLoungeClient {
        let list: Playlist = audio_cmd(Some(&LOG), PlayerCommand::GetQueue).unwrap_or_else(|_| Playlist::new("_"));

        // the first song that will be played
        let first_song = if !list.songs.is_empty() {
            list.songs[0].clone()
        }
        else {
            Song::empty()
        };

        let mut player = MLoungeClient {
            song: first_song,
            queue: list,
            position: usize::MAX,
            state: PlayerState::Stopped,
            repeat: RepeatMode::Once,
            id: 0
        };

        player.quick_sync();
        player
    }

    /// Load a playlist into the player and start playing it
    pub fn load_list(&mut self, list: &Playlist, first_song: &Song) -> PlayerResult<()> {
        self.queue = list.clone();
        audio_cmd::<()>(None, PlayerCommand::Load(list.clone()))?;
        self.set_pos(first_song)
    }

    /// Is the player empty?
    pub fn is_empty(&self) -> bool { self.song.duration == 0 }

    /// Set the repeat mode
    pub fn cycle_repeat(&mut self) -> PlayerResult<()> {
        audio_cmd(None, PlayerCommand::CycleRepeat)?;
        self.quick_sync();
        Ok(())
    }

    /// Restart the current song
    pub fn restart(&mut self) -> PlayerResult<()> {
        if self.state != PlayerState::Stopped {
            audio_cmd(None, PlayerCommand::Restart)?;
            self.quick_sync();
        }
        Ok(())
    }

    /// Skip to the mext song
    pub fn next_song(&mut self) -> PlayerResult<()> {
        audio_cmd(None, PlayerCommand::Next)?;
        self.quick_sync();
        Ok(())
    }

    /// Skip to the previous song
    pub fn prev_song(&mut self) -> PlayerResult<()> {
        audio_cmd(None, PlayerCommand::Prev)?;
        self.quick_sync();
        Ok(())
    }

    /// Toggle song playback
    pub fn play_pause(&mut self) -> PlayerResult<()> {
        if self.state == PlayerState::Playing {
            audio_cmd(None, PlayerCommand::Pause)?;
        }
        else if let PlayerState::Paused(_) = self.state {
            audio_cmd(None, PlayerCommand::Resume)?;
        }
        self.quick_sync();
        Ok(())
    }

    /// Stop the player and clear the play queue
    pub fn stop(&mut self) -> PlayerResult<()> {
        self.queue.songs.clear();
        audio_cmd(None, PlayerCommand::Stop)?;
        self.position = usize::MAX;
        self.sync(true)
    }

    /// Shuffle the play queue
    pub fn shuffle_queue(&mut self) -> PlayerResult<()> {
        audio_cmd(None, PlayerCommand::Shuffle)?;
        self.sync(true)
    }

    /// Get the current time of the song
    pub fn cur_time(&self) -> String {
        let seconds = self.cur_time_secs();
        let sec_rem = seconds % 60;
        let minutes = (seconds - (seconds % 60)) / 60;
        format!("{minutes}:{sec_rem:02}")
    }

    /// Get the current time of the song in seconds
    pub fn cur_time_secs(&self) -> u64 { audio_cmd(None, PlayerCommand::CurrentTime).unwrap_or(0) }

    /// Skip to another song in the play queue
    pub fn set_pos(&mut self, song: &Song) -> PlayerResult<()> {
        audio_cmd(None, PlayerCommand::SetPos(song.clone()))?;
        self.quick_sync();
        Ok(())
    }

    /// Check if the player is still playing a song or if it has been changed
    pub fn song_changed(&mut self) -> bool {
        if let Ok(status) = audio_cmd::<PlayerStatus>(None, PlayerCommand::Status) {
            return status.song_id != self.id;
        }

        false
    }

    /// Sync player status and play queue
    pub fn sync(&mut self, reverse: bool) -> PlayerResult<()> {
        if reverse {
            let queue: Playlist = audio_cmd(None, PlayerCommand::GetQueue)?;
            self.queue = queue;
        }
        else {
            audio_cmd(None, PlayerCommand::SetQueue(self.queue.clone()))?
        }

        self.quick_sync();
        Ok(())
    }

    /// Sync just the player status
    pub fn quick_sync(&mut self) {
        if let Ok(status) = audio_cmd::<PlayerStatus>(Some(&LOG), PlayerCommand::Status) {
            self.position = status.position;
            self.repeat = status.repeat_mode;
            self.state = status.state;
            if !self.queue.songs.is_empty() {
                self.song =
                    if self.position == usize::MAX {
                        self.position = 0;
                        self.queue.songs[0].clone()
                    }
                    else { self.queue.songs[self.position].clone() };
            }
            else {
                self.song = Song::empty();
            }
            self.id = self.song.song_id();
        }
    }

    /// Seek to a specific time in the current song
    pub fn seek(&self, time: u64) { audio_cmd(None, PlayerCommand::Seek(time)).expect("What went wrong?!") }

    /// Set the current song to play
    pub fn set_song(&mut self, song: &Song) {
        self.song = song.clone();
        self.set_pos(song).unwrap();
    }
}

impl Default for MLoungeClient {
    fn default() -> Self {
        Self::new()
    }
}

/// Get the music library
pub fn get_library() -> PlayerResult<Option<Library>> {
    audio_cmd(Some(&LOG), PlayerCommand::GetLibrary)
}

/// Rescan the music library
pub fn rescan_library() -> PlayerResult<()> {
    audio_cmd(Some(&LOG), PlayerCommand::RescanLibrary)
}

/// Get the playlists from the background process
pub fn get_playlists() -> PlayerResult<PlaylistStore> {
    audio_cmd(Some(&LOG), PlayerCommand::GetPlaylists)
}