| 1 | use mpd::song::Song; |
| 2 | use mpd::{Client, State}; |
| 3 | use simple_dmenu::dmenu; |
| 4 | use std::process::Command; |
| 5 | use std::time::Duration; |
| 6 | |
| 7 | pub type Result<T> = core::result::Result<T, Error>; |
| 8 | pub type Error = Box<dyn std::error::Error>; |
| 9 | |
| 10 | #[derive(Debug)] |
| 11 | /// struct storing the mpd Client related stuff |
| 12 | pub struct Connection { |
| 13 | pub conn: Client, |
| 14 | pub songs_filenames: Vec<String>, |
| 15 | pub state: String, |
| 16 | pub elapsed: Duration, |
| 17 | pub total_duration: Duration, |
| 18 | pub volume: u8, |
| 19 | pub repeat: bool, |
| 20 | pub random: bool, |
| 21 | pub current_song: Song, |
| 22 | pub stats: mpd::Stats, |
| 23 | } |
| 24 | |
| 25 | impl Connection { |
| 26 | /// Create a new connection |
| 27 | pub fn new(addrs: &str) -> Result<Self> { |
| 28 | let mut conn = Client::connect(addrs).unwrap(); |
| 29 | |
| 30 | let empty_song = Song { |
| 31 | file: "No Song playing or in Queue".to_string(), |
| 32 | ..Default::default() |
| 33 | }; |
| 34 | |
| 35 | let songs_filenames: Vec<String> = conn |
| 36 | .listall() |
| 37 | .unwrap() |
| 38 | .into_iter() |
| 39 | .map(|x| x.file) |
| 40 | .collect(); |
| 41 | |
| 42 | let status = conn.status().unwrap(); |
| 43 | let (elapsed, total) = status.time.unwrap_or_default(); |
| 44 | let volume: u8 = status.volume as u8; |
| 45 | let repeat = status.repeat; |
| 46 | let random = status.random; |
| 47 | let stats = conn.stats().unwrap_or_default(); |
| 48 | |
| 49 | let current_song = conn |
| 50 | .currentsong() |
| 51 | .unwrap_or_else(|_| Some(empty_song.clone())) |
| 52 | .unwrap_or(empty_song); |
| 53 | Ok(Self { |
| 54 | conn, |
| 55 | songs_filenames, |
| 56 | state: "Stopped".to_string(), |
| 57 | elapsed, |
| 58 | total_duration: total, |
| 59 | volume, |
| 60 | repeat, |
| 61 | random, |
| 62 | current_song, |
| 63 | stats, |
| 64 | }) |
| 65 | } |
| 66 | |
| 67 | /// Dmenu prompt for selecting songs |
| 68 | pub fn play_dmenu(&mut self) -> Result<()> { |
| 69 | is_installed("dmenu")?; |
| 70 | let ss: Vec<&str> = self.songs_filenames.iter().map(|x| x.as_str()).collect(); |
| 71 | let op = dmenu!(iter &ss; args "-p", "Choose a song: ", "-l", "30"); |
| 72 | let index = get_choice_index(&self.songs_filenames, &op); |
| 73 | let song = self.get_song_with_only_filename(ss.get(index).unwrap()); |
| 74 | self.push(&song)?; |
| 75 | Ok(()) |
| 76 | } |
| 77 | |
| 78 | /// Update status |
| 79 | pub fn update_status(&mut self) { |
| 80 | let status = self.conn.status().unwrap(); |
| 81 | let empty_song = self.get_song_with_only_filename("No Song playing or in Queue"); |
| 82 | let current_song = self |
| 83 | .conn |
| 84 | .currentsong() |
| 85 | .unwrap_or_else(|_| Some(empty_song.clone())) |
| 86 | .unwrap_or(empty_song); |
| 87 | let stats = self.conn.stats().unwrap_or_default(); |
| 88 | |
| 89 | // Playback State |
| 90 | match status.state { |
| 91 | State::Stop => self.state = "Stopped".to_string(), |
| 92 | State::Play => self.state = "Playing".to_string(), |
| 93 | State::Pause => self.state = "Paused".to_string(), |
| 94 | } |
| 95 | |
| 96 | // Progress |
| 97 | let (elapsed, total) = status.time.unwrap_or_default(); |
| 98 | self.elapsed = elapsed; |
| 99 | self.total_duration = total; |
| 100 | |
| 101 | // Volume |
| 102 | self.volume = status.volume as u8; |
| 103 | |
| 104 | // Repeat mode |
| 105 | self.repeat = status.repeat; |
| 106 | |
| 107 | // Random mode |
| 108 | self.random = status.random; |
| 109 | |
| 110 | // Current song |
| 111 | self.current_song = current_song; |
| 112 | |
| 113 | // |
| 114 | |
| 115 | self.stats = stats; |
| 116 | } |
| 117 | |
| 118 | /// Get progress ratio of current playing song |
| 119 | pub fn get_progress_ratio(&self) -> f64 { |
| 120 | let total = self.total_duration.as_secs_f64(); |
| 121 | if total == 0.0 { |
| 122 | 0.0 |
| 123 | } else { |
| 124 | let ratio = self.elapsed.as_secs_f64() / self.total_duration.as_secs_f64(); |
| 125 | if ratio > 1.0 || ratio == 0.0 { |
| 126 | 0.0 |
| 127 | } else { |
| 128 | ratio |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | /// push the given song to queue |
| 134 | pub fn push(&mut self, song: &Song) -> Result<()> { |
| 135 | if self.conn.queue().unwrap().is_empty() { |
| 136 | self.conn.push(song).unwrap(); |
| 137 | self.conn.play().unwrap(); |
| 138 | } else { |
| 139 | self.conn.push(song)?; |
| 140 | let len: u32 = (self.conn.queue().unwrap().len() - 1).try_into().unwrap(); |
| 141 | self.conn.switch(len)?; |
| 142 | if self.conn.status()?.state == State::Stop { |
| 143 | self.conn.play()?; |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | Ok(()) |
| 148 | } |
| 149 | |
| 150 | /// Push all songs of a playlist into queue |
| 151 | pub fn load_playlist(&mut self, playlist: &str) -> Result<()> { |
| 152 | self.conn.load(playlist, ..)?; |
| 153 | self.conn.play()?; |
| 154 | Ok(()) |
| 155 | } |
| 156 | |
| 157 | /// Add given song to playlist |
| 158 | pub fn add_to_playlist(&mut self, playlist: &str, song: &Song) -> Result<()> { |
| 159 | self.conn.pl_push(playlist, song)?; |
| 160 | Ok(()) |
| 161 | } |
| 162 | |
| 163 | /// Given a filename, get instance of Song with only filename |
| 164 | pub fn get_song_with_only_filename(&self, filename: &str) -> Song { |
| 165 | Song { |
| 166 | file: filename.to_string(), |
| 167 | ..Default::default() |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | /// Given a song name from a directory, it returns the full path of the song in the database |
| 172 | pub fn get_full_path(&self, short_path: &str) -> Option<String> { |
| 173 | for (i, f) in self.songs_filenames.iter().enumerate() { |
| 174 | if f.contains(short_path) { |
| 175 | return Some(self.songs_filenames.get(i).unwrap().to_string()); |
| 176 | } |
| 177 | } |
| 178 | None |
| 179 | } |
| 180 | |
| 181 | /// Gives title of current playing song |
| 182 | pub fn now_playing(&mut self) -> Result<Option<String>> { |
| 183 | if let Some(s) = &self.current_song.title { |
| 184 | if let Some(a) = &self.current_song.artist { |
| 185 | Ok(Some(format!("\"{}\" By {}", s, a))) |
| 186 | } else { |
| 187 | Ok(Some(s.to_string())) |
| 188 | } |
| 189 | } else { |
| 190 | Ok(Some(self.current_song.file.clone())) |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | // Playback controls |
| 195 | /// Pause playback |
| 196 | pub fn pause(&mut self) { |
| 197 | self.conn.pause(true).unwrap(); |
| 198 | } |
| 199 | |
| 200 | /// Toggles playback |
| 201 | pub fn toggle_pause(&mut self) { |
| 202 | self.conn.toggle_pause().unwrap(); |
| 203 | } |
| 204 | |
| 205 | /// Toggle Repeat mode |
| 206 | pub fn toggle_repeat(&mut self) { |
| 207 | if self.conn.status().unwrap().repeat { |
| 208 | self.conn.repeat(false).unwrap(); |
| 209 | } else { |
| 210 | self.conn.repeat(true).unwrap(); |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | /// Toggle random mode |
| 215 | pub fn toggle_random(&mut self) { |
| 216 | if self.conn.status().unwrap().random { |
| 217 | self.conn.random(false).unwrap(); |
| 218 | } else { |
| 219 | self.conn.random(true).unwrap(); |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | // Volume controls |
| 224 | /// Increase Volume |
| 225 | pub fn inc_volume(&mut self, v: i8) { |
| 226 | let cur = self.conn.status().unwrap().volume; |
| 227 | if cur + v <= 100 { |
| 228 | self.conn.volume(cur + v).unwrap(); |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | /// Decrease volume |
| 233 | pub fn dec_volume(&mut self, v: i8) { |
| 234 | let cur = self.conn.status().unwrap().volume; |
| 235 | if cur - v >= 0 { |
| 236 | self.conn.volume(cur - v).unwrap(); |
| 237 | } |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | /// Gets the index of the string from the Vector |
| 242 | fn get_choice_index(ss: &[String], selection: &str) -> usize { |
| 243 | let mut choice: usize = 0; |
| 244 | if let Some(index) = ss.iter().position(|s| s == selection) { |
| 245 | choice = index; |
| 246 | } |
| 247 | |
| 248 | choice |
| 249 | } |
| 250 | |
| 251 | /// Checks if given program is installed in your system |
| 252 | fn is_installed(ss: &str) -> Result<()> { |
| 253 | let output = Command::new("which") |
| 254 | .arg(ss) |
| 255 | .output() |
| 256 | .expect("Failed to execute command"); |
| 257 | if output.status.success() { |
| 258 | Ok(()) |
| 259 | } else { |
| 260 | let err = format!("{} not installed", ss); |
| 261 | Err(err.into()) |
| 262 | } |
| 263 | } |