Krolyxon
Commit b93eae4

rmptuisrcconnection.rs

194 lines · 5.7 KB · Rust

1use mpd::song::Song;
2use mpd::{Client, State};
3use simple_dmenu::dmenu;
4use std::process::Command;
5
6pub type Result<T> = core::result::Result<T, Error>;
7pub type Error = Box<dyn std::error::Error>;
8
9#[derive(Debug)]
10pub struct Connection {
11 pub conn: Client,
12 pub songs_filenames: Vec<String>,
13 // pub state: String,
14}
15
16impl Connection {
17 /// Create a new connection
18 pub fn new(addrs: &str) -> Result<Self> {
19 let mut conn = Client::connect(addrs).unwrap();
20 let songs_filenames: Vec<String> = conn
21 .listall()
22 .unwrap()
23 .into_iter()
24 .map(|x| x.file)
25 .collect();
26
27 Ok(Self {
28 conn,
29 songs_filenames,
30 // state: "Stopped".to_string(),
31 })
32 }
33
34 /// Fzf prompt for selecting song
35 pub fn play_fzf(&mut self) -> Result<()> {
36 is_installed("fzf").map_err(|ex| ex)?;
37
38 let ss = &self.songs_filenames;
39 let fzf_choice = rust_fzf::select(ss.clone(), Vec::new()).unwrap();
40 let index = get_choice_index(&self.songs_filenames, fzf_choice.get(0).unwrap());
41 let song = self.get_song_with_only_filename(ss.get(index).unwrap());
42 self.push(&song)?;
43
44 Ok(())
45 }
46
47 /// Dmenu prompt for selecting songs
48 pub fn play_dmenu(&mut self) -> Result<()> {
49 is_installed("dmenu").map_err(|ex| ex)?;
50 let ss: Vec<&str> = self.songs_filenames.iter().map(|x| x.as_str()).collect();
51 let op = dmenu!(iter &ss; args "-l", "30");
52 let index = get_choice_index(&self.songs_filenames, &op);
53 let song = self.get_song_with_only_filename(ss.get(index).unwrap());
54 self.push(&song)?;
55 Ok(())
56 }
57
58 // pub fn update_state(&mut self) {
59 // match self.conn.status().unwrap().state {
60 // State::Stop => self.state = "Stopped".to_string(),
61 // State::Play => self.state = "Playing".to_string(),
62 // State::Pause => self.state = "Paused".to_string(),
63 // }
64 // }
65
66 /// push the given song to queue
67 pub fn push(&mut self, song: &Song) -> Result<()> {
68 if self.conn.queue().unwrap().is_empty() {
69 self.conn.push(song).unwrap();
70 self.conn.play().unwrap();
71 } else {
72 self.conn.push(song)?;
73 if self.conn.status()?.state == State::Stop {
74 self.conn.play()?;
75 }
76 self.conn.next().unwrap();
77 }
78
79 Ok(())
80 }
81
82 /// Push all songs of a playlist into queue
83 pub fn push_playlist(&mut self, playlist: &str) -> Result<()> {
84 let songs: Vec<Song> = self.conn.playlist(playlist)?;
85
86 for song in songs {
87 if self.songs_filenames.contains(&song.file) {
88 let song = self.get_song_with_only_filename(&song.file);
89 self.conn.push(&song)?;
90 self.conn.play()?;
91 }
92 }
93 Ok(())
94 }
95
96 /// Given a filename, get instance of Song with only filename
97 pub fn get_song_with_only_filename(&self, filename: &str) -> Song {
98 Song {
99 file: filename.to_string(),
100 artist: None,
101 title: None,
102 duration: None,
103 last_mod: None,
104 name: None,
105 place: None,
106 range: None,
107 tags: vec![("".to_string(), "".to_string())],
108 }
109 }
110
111 /// get current playing song
112 pub fn get_current_song(&mut self) -> Option<String> {
113 self.conn.currentsong().unwrap().unwrap_or_default().title
114 }
115
116 /// Print status to stdout
117 pub fn status(&mut self) {
118 let current_song = self.conn.currentsong();
119 let status = self.conn.status().unwrap();
120
121 if current_song.is_ok() && status.state != State::Stop {
122 let song = current_song.unwrap();
123 if let Some(s) = song {
124 println!("{} - {}", s.artist.unwrap(), s.title.unwrap());
125 }
126 }
127 println!(
128 "volume: {}\trepeat: {}\trandom: {}\tsingle: {}\tconsume: {}",
129 status.volume, status.repeat, status.random, status.single, status.consume
130 );
131 }
132
133 /// Gives title of current playing song
134 pub fn now_playing(&mut self) -> Result<Option<String>> {
135 let song = self.conn.currentsong()?.unwrap();
136 if let Some(s) = song.title {
137 if let Some(a) = song.artist {
138 return Ok(Some(format!("{} - {}", s, a)));
139 } else {
140 return Ok(Some(s));
141 }
142 } else {
143 return Ok(Some(song.file));
144 }
145 }
146
147 // Playback controls
148 /// Pause playback
149 pub fn pause(&mut self) {
150 self.conn.pause(true).unwrap();
151 }
152
153 /// Toggles playback
154 pub fn toggle_pause(&mut self) {
155 self.conn.toggle_pause().unwrap();
156 }
157
158 // Volume controls
159 /// Sets the volume
160 pub fn set_volume(&mut self, u: String) {
161 let cur = self.conn.status().unwrap().volume;
162 let sym = u.get(0..1).unwrap();
163 let u: i8 = u.parse::<i8>().unwrap();
164 if sym == "+" || sym == "-" {
165 self.conn.volume(cur + u).unwrap();
166 } else {
167 self.conn.volume(u).unwrap();
168 }
169 }
170}
171
172/// Gets the index of the string from the Vector
173fn get_choice_index(ss: &Vec<String>, selection: &str) -> usize {
174 let mut choice: usize = 0;
175 if let Some(index) = ss.iter().position(|s| s == selection) {
176 choice = index;
177 }
178
179 choice
180}
181
182/// Checks if given program is installed in your system
183fn is_installed(ss: &str) -> Result<()> {
184 let output = Command::new("which")
185 .arg(ss)
186 .output()
187 .expect("Failed to execute command");
188 if output.status.success() {
189 Ok(())
190 } else {
191 let err = format!("{} not installed", ss);
192 Err(err.into())
193 }
194}