Krolyxon
Tag v0.1.2

rmptuisrcconnection.rs

252 lines · 7.1 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 if 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 }
78
79 Ok(())
80 }
81
82 /// Update status
83 pub fn update_status(&mut self) {
84 let status = self.conn.status().unwrap();
85 let empty_song = self.get_song_with_only_filename("No Song playing or in Queue");
86 let current_song = self
87 .conn
88 .currentsong()
89 .unwrap_or_else(|_| Some(empty_song.clone()))
90 .unwrap_or(empty_song);
91 let stats = self.conn.stats().unwrap_or_default();
92
93 // Playback State
94 match status.state {
95 State::Stop => self.state = "Stopped".to_string(),
96 State::Play => self.state = "Playing".to_string(),
97 State::Pause => self.state = "Paused".to_string(),
98 }
99
100 // Progress
101 let (elapsed, total) = status.time.unwrap_or_default();
102 self.elapsed = elapsed;
103 self.total_duration = total;
104
105 // Volume
106 self.volume = status.volume as u8;
107
108 // Repeat mode
109 self.repeat = status.repeat;
110
111 // Random mode
112 self.random = status.random;
113
114 // Current song
115 self.current_song = current_song;
116
117 // Stats
118 self.stats = stats;
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 None
182 }
183
184 /// Gives title of current playing song
185 pub fn now_playing(&mut self) -> Result<Option<String>> {
186 if let Some(s) = &self.current_song.title {
187 if let Some(a) = &self.current_song.artist {
188 Ok(Some(format!("\"{}\" By {}", s, a)))
189 } else {
190 Ok(Some(s.to_string()))
191 }
192 } else {
193 Ok(Some(self.current_song.file.clone()))
194 }
195 }
196
197 // Playback controls
198 /// Pause playback
199 pub fn pause(&mut self) {
200 self.conn.pause(true).unwrap();
201 }
202
203 /// Toggles playback
204 pub fn toggle_pause(&mut self) {
205 self.conn.toggle_pause().unwrap();
206 }
207
208 /// Toggle Repeat mode
209 pub fn toggle_repeat(&mut self) {
210 if self.conn.status().unwrap().repeat {
211 self.conn.repeat(false).unwrap();
212 } else {
213 self.conn.repeat(true).unwrap();
214 }
215 }
216
217 /// Toggle random mode
218 pub fn toggle_random(&mut self) {
219 if self.conn.status().unwrap().random {
220 self.conn.random(false).unwrap();
221 } else {
222 self.conn.random(true).unwrap();
223 }
224 }
225
226 // Volume controls
227 /// Increase Volume
228 pub fn inc_volume(&mut self, v: i8) {
229 let cur = self.conn.status().unwrap().volume;
230 if cur + v <= 100 {
231 self.conn.volume(cur + v).unwrap();
232 }
233 }
234
235 /// Decrease volume
236 pub fn dec_volume(&mut self, v: i8) {
237 let cur = self.conn.status().unwrap().volume;
238 if cur - v >= 0 {
239 self.conn.volume(cur - v).unwrap();
240 }
241 }
242}
243
244/// Checks if given program is installed in your system
245fn is_installed(ss: &str) -> bool {
246 let output = Command::new("which")
247 .arg(ss)
248 .output()
249 .expect("Failed to execute command");
250
251 output.status.success()
252}