Krolyxon
Commit 971b336

rmptuisrcconnection.rs

251 lines · 7.1 KB · Rust

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