Krolyxon
Commit d0b76c3

rmptuisrcconnection.rs

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