Krolyxon
Commit 38ebdf9

rmptuisrcconnection.rs

285 lines · 8.3 KB · Rust

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