Krolyxon
Commit 3d569cb

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