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