Krolyxon
Commit a816152

rmptuisrcconnection.rs

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