Krolyxon
Commit 59eed99

rmptuisrcconnection.rs

284 lines · 8.2 KB · Rust

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