Krolyxon
Commit 3f6b2bf

rmptuisrcconnection.rs

195 lines · 5.8 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 let len: u32 = (self.conn.queue().unwrap().len() - 1).try_into().unwrap();
74 self.conn.switch(len)?;
75 if self.conn.status()?.state == State::Stop {
76 self.conn.play()?;
77 }
78 }
79
80 Ok(())
81 }
82
83 /// Push all songs of a playlist into queue
84 pub fn push_playlist(&mut self, playlist: &str) -> Result<()> {
85 let songs: Vec<Song> = self.conn.playlist(playlist)?;
86
87 for song in songs {
88 if self.songs_filenames.contains(&song.file) {
89 let song = self.get_song_with_only_filename(&song.file);
90 self.conn.push(&song)?;
91 self.conn.play()?;
92 }
93 }
94 Ok(())
95 }
96
97 /// Given a filename, get instance of Song with only filename
98 pub fn get_song_with_only_filename(&self, filename: &str) -> Song {
99 Song {
100 file: filename.to_string(),
101 artist: None,
102 title: None,
103 duration: None,
104 last_mod: None,
105 name: None,
106 place: None,
107 range: None,
108 tags: vec![("".to_string(), "".to_string())],
109 }
110 }
111
112 /// get current playing song
113 pub fn get_current_song(&mut self) -> Option<String> {
114 self.conn.currentsong().unwrap().unwrap_or_default().title
115 }
116
117 /// Print status to stdout
118 pub fn status(&mut self) {
119 let current_song = self.conn.currentsong();
120 let status = self.conn.status().unwrap();
121
122 if current_song.is_ok() && status.state != State::Stop {
123 let song = current_song.unwrap();
124 if let Some(s) = song {
125 println!("{} - {}", s.artist.unwrap(), s.title.unwrap());
126 }
127 }
128 println!(
129 "volume: {}\trepeat: {}\trandom: {}\tsingle: {}\tconsume: {}",
130 status.volume, status.repeat, status.random, status.single, status.consume
131 );
132 }
133
134 /// Gives title of current playing song
135 pub fn now_playing(&mut self) -> Result<Option<String>> {
136 let song = self.conn.currentsong()?.unwrap_or_default();
137 if let Some(s) = song.title {
138 if let Some(a) = song.artist {
139 return Ok(Some(format!("{} - {}", s, a)));
140 } else {
141 return Ok(Some(s));
142 }
143 } else {
144 return Ok(Some(song.file));
145 }
146 }
147
148 // Playback controls
149 /// Pause playback
150 pub fn pause(&mut self) {
151 self.conn.pause(true).unwrap();
152 }
153
154 /// Toggles playback
155 pub fn toggle_pause(&mut self) {
156 self.conn.toggle_pause().unwrap();
157 }
158
159 // Volume controls
160 /// Sets the volume
161 pub fn set_volume(&mut self, u: String) {
162 let cur = self.conn.status().unwrap().volume;
163 let sym = u.get(0..1).unwrap();
164 let u: i8 = u.parse::<i8>().unwrap();
165 if sym == "+" || sym == "-" {
166 self.conn.volume(cur + u).unwrap();
167 } else {
168 self.conn.volume(u).unwrap();
169 }
170 }
171}
172
173/// Gets the index of the string from the Vector
174fn get_choice_index(ss: &Vec<String>, selection: &str) -> usize {
175 let mut choice: usize = 0;
176 if let Some(index) = ss.iter().position(|s| s == selection) {
177 choice = index;
178 }
179
180 choice
181}
182
183/// Checks if given program is installed in your system
184fn is_installed(ss: &str) -> Result<()> {
185 let output = Command::new("which")
186 .arg(ss)
187 .output()
188 .expect("Failed to execute command");
189 if output.status.success() {
190 Ok(())
191 } else {
192 let err = format!("{} not installed", ss);
193 Err(err.into())
194 }
195}