| 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 | pub struct Connection { |
| 12 | pub conn: Client, |
| 13 | pub songs_filenames: Vec<String>, |
| 14 | pub state: String, |
| 15 | pub elapsed: Duration, |
| 16 | pub total_duration: Duration, |
| 17 | } |
| 18 | |
| 19 | impl Connection { |
| 20 | /// Create a new connection |
| 21 | pub fn new(addrs: &str) -> Result<Self> { |
| 22 | let mut conn = Client::connect(addrs).unwrap(); |
| 23 | let songs_filenames: Vec<String> = conn |
| 24 | .listall() |
| 25 | .unwrap() |
| 26 | .into_iter() |
| 27 | .map(|x| x.file) |
| 28 | .collect(); |
| 29 | |
| 30 | let (elapsed, total) = conn.status().unwrap().time.unwrap_or_default(); |
| 31 | |
| 32 | Ok(Self { |
| 33 | conn, |
| 34 | songs_filenames, |
| 35 | state: "Stopped".to_string(), |
| 36 | elapsed, |
| 37 | total_duration: total, |
| 38 | }) |
| 39 | } |
| 40 | |
| 41 | /// Fzf prompt for selecting song |
| 42 | pub fn play_fzf(&mut self) -> Result<()> { |
| 43 | is_installed("fzf").map_err(|ex| ex)?; |
| 44 | |
| 45 | let ss = &self.songs_filenames; |
| 46 | let fzf_choice = rust_fzf::select(ss.clone(), Vec::new()).unwrap(); |
| 47 | let index = get_choice_index(&self.songs_filenames, fzf_choice.get(0).unwrap()); |
| 48 | let song = self.get_song_with_only_filename(ss.get(index).unwrap()); |
| 49 | self.push(&song)?; |
| 50 | |
| 51 | Ok(()) |
| 52 | } |
| 53 | |
| 54 | /// Dmenu prompt for selecting songs |
| 55 | pub fn play_dmenu(&mut self) -> Result<()> { |
| 56 | is_installed("dmenu").map_err(|ex| ex)?; |
| 57 | let ss: Vec<&str> = self.songs_filenames.iter().map(|x| x.as_str()).collect(); |
| 58 | let op = dmenu!(iter &ss; args "-p", "Choose a song: ", "-l", "30"); |
| 59 | let index = get_choice_index(&self.songs_filenames, &op); |
| 60 | let song = self.get_song_with_only_filename(ss.get(index).unwrap()); |
| 61 | self.push(&song)?; |
| 62 | Ok(()) |
| 63 | } |
| 64 | |
| 65 | pub fn update_state(&mut self) -> String { |
| 66 | match self.conn.status().unwrap().state { |
| 67 | State::Stop => self.state = "Stopped".to_string(), |
| 68 | State::Play => self.state = "Playing".to_string(), |
| 69 | State::Pause => self.state = "Paused".to_string(), |
| 70 | } |
| 71 | self.state.clone() |
| 72 | } |
| 73 | |
| 74 | pub fn update_progress(&mut self) { |
| 75 | let (elapsed, total) = self.conn.status().unwrap().time.unwrap_or_default(); |
| 76 | self.elapsed = elapsed; |
| 77 | self.total_duration = total; |
| 78 | } |
| 79 | |
| 80 | pub fn get_progress_ratio(&self) -> f64 { |
| 81 | let total = self.total_duration.as_secs_f64(); |
| 82 | if total == 0.0 { |
| 83 | 0.0 |
| 84 | } else { |
| 85 | let ratio = self.elapsed.as_secs_f64() / self.total_duration.as_secs_f64(); |
| 86 | if ratio > 1.0 || ratio == 0.0 { |
| 87 | 1.0 |
| 88 | } else { |
| 89 | ratio |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// push the given song to queue |
| 95 | pub fn push(&mut self, song: &Song) -> Result<()> { |
| 96 | if self.conn.queue().unwrap().is_empty() { |
| 97 | self.conn.push(song).unwrap(); |
| 98 | self.conn.play().unwrap(); |
| 99 | } else { |
| 100 | self.conn.push(song)?; |
| 101 | let len: u32 = (self.conn.queue().unwrap().len() - 1).try_into().unwrap(); |
| 102 | self.conn.switch(len)?; |
| 103 | if self.conn.status()?.state == State::Stop { |
| 104 | self.conn.play()?; |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | Ok(()) |
| 109 | } |
| 110 | |
| 111 | /// Push all songs of a playlist into queue |
| 112 | pub fn push_playlist(&mut self, playlist: &str) -> Result<()> { |
| 113 | let songs: Vec<Song> = self.conn.playlist(playlist)?; |
| 114 | |
| 115 | for song in songs { |
| 116 | if self.songs_filenames.contains(&song.file) { |
| 117 | let song = self.get_song_with_only_filename(&song.file); |
| 118 | self.conn.push(&song)?; |
| 119 | self.conn.play()?; |
| 120 | } |
| 121 | } |
| 122 | Ok(()) |
| 123 | } |
| 124 | |
| 125 | /// Given a filename, get instance of Song with only filename |
| 126 | pub fn get_song_with_only_filename(&self, filename: &str) -> Song { |
| 127 | Song { |
| 128 | file: filename.to_string(), |
| 129 | artist: None, |
| 130 | title: None, |
| 131 | duration: None, |
| 132 | last_mod: None, |
| 133 | name: None, |
| 134 | place: None, |
| 135 | range: None, |
| 136 | tags: vec![("".to_string(), "".to_string())], |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | /// get current playing song |
| 141 | pub fn get_current_song(&mut self) -> Option<String> { |
| 142 | self.conn.currentsong().unwrap().unwrap_or_default().title |
| 143 | } |
| 144 | |
| 145 | /// Print status to stdout |
| 146 | pub fn status(&mut self) { |
| 147 | let current_song = self.conn.currentsong(); |
| 148 | let status = self.conn.status().unwrap(); |
| 149 | |
| 150 | if current_song.is_ok() && status.state != State::Stop { |
| 151 | let song = current_song.unwrap(); |
| 152 | if let Some(s) = song { |
| 153 | println!("{} - {}", s.artist.unwrap(), s.title.unwrap()); |
| 154 | } |
| 155 | } |
| 156 | println!( |
| 157 | "volume: {}\trepeat: {}\trandom: {}\tsingle: {}\tconsume: {}", |
| 158 | status.volume, status.repeat, status.random, status.single, status.consume |
| 159 | ); |
| 160 | } |
| 161 | |
| 162 | /// Gives title of current playing song |
| 163 | pub fn now_playing(&mut self) -> Result<Option<String>> { |
| 164 | let song = self.conn.currentsong()?.unwrap_or_default(); |
| 165 | if let Some(s) = song.title { |
| 166 | if let Some(a) = song.artist { |
| 167 | return Ok(Some(format!("\"{}\" By {}", a, s))); |
| 168 | } else { |
| 169 | return Ok(Some(s)); |
| 170 | } |
| 171 | } else { |
| 172 | return Ok(Some(song.file)); |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | // Playback controls |
| 177 | /// Pause playback |
| 178 | pub fn pause(&mut self) { |
| 179 | self.conn.pause(true).unwrap(); |
| 180 | } |
| 181 | |
| 182 | /// Toggles playback |
| 183 | pub fn toggle_pause(&mut self) { |
| 184 | self.conn.toggle_pause().unwrap(); |
| 185 | } |
| 186 | |
| 187 | // Volume controls |
| 188 | pub fn inc_volume(&mut self, v: i8) { |
| 189 | let cur = self.conn.status().unwrap().volume; |
| 190 | if cur + v <= 100 { |
| 191 | self.conn.volume(cur + v).unwrap(); |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | pub fn dec_volume(&mut self, v: i8) { |
| 196 | let cur = self.conn.status().unwrap().volume; |
| 197 | if cur - v >= 0 { |
| 198 | self.conn.volume(cur - v).unwrap(); |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | /// Gets the index of the string from the Vector |
| 204 | fn get_choice_index(ss: &Vec<String>, selection: &str) -> usize { |
| 205 | let mut choice: usize = 0; |
| 206 | if let Some(index) = ss.iter().position(|s| s == selection) { |
| 207 | choice = index; |
| 208 | } |
| 209 | |
| 210 | choice |
| 211 | } |
| 212 | |
| 213 | /// Checks if given program is installed in your system |
| 214 | fn is_installed(ss: &str) -> Result<()> { |
| 215 | let output = Command::new("which") |
| 216 | .arg(ss) |
| 217 | .output() |
| 218 | .expect("Failed to execute command"); |
| 219 | if output.status.success() { |
| 220 | Ok(()) |
| 221 | } else { |
| 222 | let err = format!("{} not installed", ss); |
| 223 | Err(err.into()) |
| 224 | } |
| 225 | } |