Krolyxon
Commit 3578eae

rmptuisrcconnection.rs

113 lines · 3.2 KB · Rust

1use mpd::song::Song;
2use mpd::{Client, State};
3use simple_dmenu::dmenu;
4
5pub struct Connection {
6 pub conn: Client,
7 pub songs_filenames: Vec<String>,
8}
9
10impl Connection {
11 pub fn new(addrs: &str) -> Result<Self, mpd::error::Error> {
12 let mut conn = Client::connect(addrs)?;
13 let songs_filenames: Vec<String> = conn
14 .listall()
15 .unwrap()
16 .iter()
17 .map(|x| x.clone().file)
18 .collect();
19
20 Ok(Self {
21 conn,
22 songs_filenames,
23 })
24 }
25
26 pub fn play_fzf(&mut self) {
27 let ss = &self.songs_filenames;
28 let fzf_choice = rust_fzf::select(ss.clone(), Vec::new()).unwrap();
29 let index = get_choice_index(&self.songs_filenames, fzf_choice.get(0).unwrap());
30 let song = self.get_song_with_only_filename(ss.get(index).unwrap());
31 self.push(&song);
32 }
33
34 pub fn play_dmenu(&mut self) {
35 let ss: Vec<&str> = self.songs_filenames.iter().map(|x| x.as_str()).collect();
36 let op = dmenu!(iter &ss; args "-l", "30");
37 let index = get_choice_index(&self.songs_filenames, &op);
38 let song = self.get_song_with_only_filename(ss.get(index).unwrap());
39 self.push(&song);
40 }
41
42 fn push(&mut self, song: &Song) {
43 if self.conn.queue().unwrap().is_empty() {
44 self.conn.push(song).unwrap();
45 self.conn.play().unwrap();
46 } else {
47 self.conn.push(song).unwrap();
48 if self.conn.status().unwrap().state == State::Stop {
49 self.conn.play().unwrap();
50 }
51 self.conn.next().unwrap();
52 }
53 }
54
55 fn get_song_with_only_filename(&self, filename: &str) -> Song {
56 Song {
57 file: filename.to_string(),
58 artist: None,
59 title: None,
60 duration: None,
61 last_mod: None,
62 name: None,
63 place: None,
64 range: None,
65 tags: vec![("".to_string(), "".to_string())],
66 }
67 }
68
69 pub fn status(&mut self) {
70 let current_song = self.conn.currentsong();
71 let status = self.conn.status().unwrap();
72
73 if current_song.is_ok() {
74 let song = current_song.unwrap();
75 if let Some(s) = song {
76 println!("{} - {}", s.artist.unwrap(), s.title.unwrap());
77 }
78 }
79 println!(
80 "volume: {}\trepeat: {}\trandom: {}\tsingle: {}\tconsume: {}",
81 status.volume, status.repeat, status.random, status.single, status.consume
82 );
83 }
84
85 // Play controls
86 pub fn pause(&mut self) {
87 self.conn.pause(true).unwrap();
88 }
89
90 pub fn toggle_pause(&mut self) {
91 self.conn.toggle_pause().unwrap();
92 }
93
94 // Volume controls
95 pub fn inc_volume(&mut self, inc: i8) {
96 let cur = self.conn.status().unwrap().volume;
97 self.conn.volume(cur + inc).unwrap();
98 }
99
100 pub fn dec_volume(&mut self, dec: i8) {
101 let cur = self.conn.status().unwrap().volume;
102 self.conn.volume(cur - dec).unwrap();
103 }
104}
105
106fn get_choice_index(ss: &Vec<String>, selection: &str) -> usize {
107 let mut choice: usize = 0;
108 if let Some(index) = ss.iter().position(|s| s == selection) {
109 choice = index;
110 }
111
112 choice
113}