Krolyxon
Commit 520dad7

rmptuisrcconnection.rs

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