Krolyxon
Commit 83c86d3

rmptuisrcconnection.rs

254 lines · 7.2 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(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 /// Dmenu prompt for selecting songs
65 pub fn play_dmenu(&mut self) -> Result<()> {
66 is_installed("dmenu")?;
67 let ss: Vec<&str> = self.songs_filenames.iter().map(|x| x.as_str()).collect();
68 let op = dmenu!(iter &ss; args "-p", "Choose a song: ", "-l", "30");
69 let index = get_choice_index(&self.songs_filenames, &op);
70 let song = self.get_song_with_only_filename(ss.get(index).unwrap());
71 self.push(&song)?;
72 Ok(())
73 }
74
75 /// Update status
76 pub fn update_status(&mut self) {
77 let status = self.conn.status().unwrap();
78 let empty_song = self.get_song_with_only_filename("No Song playing or in Queue");
79 let current_song = self
80 .conn
81 .currentsong()
82 .unwrap_or_else(|_| Some(empty_song.clone()))
83 .unwrap_or(empty_song);
84
85 // Playback State
86 match status.state {
87 State::Stop => self.state = "Stopped".to_string(),
88 State::Play => self.state = "Playing".to_string(),
89 State::Pause => self.state = "Paused".to_string(),
90 }
91
92 // Progress
93 let (elapsed, total) = status.time.unwrap_or_default();
94 self.elapsed = elapsed;
95 self.total_duration = total;
96
97 // Volume
98 self.volume = status.volume as u8;
99
100 // Repeat mode
101 self.repeat = status.repeat;
102
103 // Random mode
104 self.random = status.random;
105
106 self.current_song = current_song;
107 }
108
109 /// Get progress ratio of current playing song
110 pub fn get_progress_ratio(&self) -> f64 {
111 let total = self.total_duration.as_secs_f64();
112 if total == 0.0 {
113 0.0
114 } else {
115 let ratio = self.elapsed.as_secs_f64() / self.total_duration.as_secs_f64();
116 if ratio > 1.0 || ratio == 0.0 {
117 0.0
118 } else {
119 ratio
120 }
121 }
122 }
123
124 /// push the given song to queue
125 pub fn push(&mut self, song: &Song) -> Result<()> {
126 if self.conn.queue().unwrap().is_empty() {
127 self.conn.push(song).unwrap();
128 self.conn.play().unwrap();
129 } else {
130 self.conn.push(song)?;
131 let len: u32 = (self.conn.queue().unwrap().len() - 1).try_into().unwrap();
132 self.conn.switch(len)?;
133 if self.conn.status()?.state == State::Stop {
134 self.conn.play()?;
135 }
136 }
137
138 Ok(())
139 }
140
141 /// Push all songs of a playlist into queue
142 pub fn load_playlist(&mut self, playlist: &str) -> Result<()> {
143 self.conn.load(playlist, ..)?;
144 self.conn.play()?;
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 ..Default::default()
159 }
160 }
161
162 /// Given a song name from a directory, it returns the full path of the song in the database
163 pub fn get_full_path(&self, short_path: &str) -> Option<String> {
164 for (i, f) in self.songs_filenames.iter().enumerate() {
165 if f.contains(short_path) {
166 return Some(self.songs_filenames.get(i).unwrap().to_string());
167 }
168 }
169 None
170 }
171
172 /// Gives title of current playing song
173 pub fn now_playing(&mut self) -> Result<Option<String>> {
174 if let Some(s) = &self.current_song.title {
175 if let Some(a) = &self.current_song.artist {
176 Ok(Some(format!("\"{}\" By {}", s, a)))
177 } else {
178 Ok(Some(s.to_string()))
179 }
180 } else {
181 Ok(Some(self.current_song.file.clone()))
182 }
183 }
184
185 // Playback controls
186 /// Pause playback
187 pub fn pause(&mut self) {
188 self.conn.pause(true).unwrap();
189 }
190
191 /// Toggles playback
192 pub fn toggle_pause(&mut self) {
193 self.conn.toggle_pause().unwrap();
194 }
195
196 /// Toggle Repeat mode
197 pub fn toggle_repeat(&mut self) {
198 if self.conn.status().unwrap().repeat {
199 self.conn.repeat(false).unwrap();
200 } else {
201 self.conn.repeat(true).unwrap();
202 }
203 }
204
205 /// Toggle random mode
206 pub fn toggle_random(&mut self) {
207 if self.conn.status().unwrap().random {
208 self.conn.random(false).unwrap();
209 } else {
210 self.conn.random(true).unwrap();
211 }
212 }
213
214 // Volume controls
215 /// Increase Volume
216 pub fn inc_volume(&mut self, v: i8) {
217 let cur = self.conn.status().unwrap().volume;
218 if cur + v <= 100 {
219 self.conn.volume(cur + v).unwrap();
220 }
221 }
222
223 /// Decrease volume
224 pub fn dec_volume(&mut self, v: i8) {
225 let cur = self.conn.status().unwrap().volume;
226 if cur - v >= 0 {
227 self.conn.volume(cur - v).unwrap();
228 }
229 }
230}
231
232/// Gets the index of the string from the Vector
233fn get_choice_index(ss: &[String], selection: &str) -> usize {
234 let mut choice: usize = 0;
235 if let Some(index) = ss.iter().position(|s| s == selection) {
236 choice = index;
237 }
238
239 choice
240}
241
242/// Checks if given program is installed in your system
243fn is_installed(ss: &str) -> Result<()> {
244 let output = Command::new("which")
245 .arg(ss)
246 .output()
247 .expect("Failed to execute command");
248 if output.status.success() {
249 Ok(())
250 } else {
251 let err = format!("{} not installed", ss);
252 Err(err.into())
253 }
254}