rsblocks now support spotify using dbus

This commit is contained in:
mustafa salih 2021-01-13 01:44:02 +03:00
parent e2ada32383
commit 2c18c32e5f
5 changed files with 227 additions and 98 deletions

22
Cargo.lock generated
View File

@ -194,6 +194,16 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7313c0d620d0cb4dbd9d019e461a4beb501071ff46ec0ab933efb4daa76d73e3" checksum = "7313c0d620d0cb4dbd9d019e461a4beb501071ff46ec0ab933efb4daa76d73e3"
[[package]]
name = "dbus"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b1334c0161ddfccd239ac81b188d62015b049c986c5cd0b7f9447cf2c54f4a3"
dependencies = [
"libc",
"libdbus-sys",
]
[[package]] [[package]]
name = "event-listener" name = "event-listener"
version = "2.5.1" version = "2.5.1"
@ -260,6 +270,15 @@ version = "0.2.81"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1482821306169ec4d07f6aca392a4681f66c75c9918aa49641a2595db64053cb" checksum = "1482821306169ec4d07f6aca392a4681f66c75c9918aa49641a2595db64053cb"
[[package]]
name = "libdbus-sys"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc12a3bc971424edbbf7edaf6e5740483444db63aa8e23d3751ff12a30f306f0"
dependencies = [
"pkg-config",
]
[[package]] [[package]]
name = "linked-hash-map" name = "linked-hash-map"
version = "0.5.3" version = "0.5.3"
@ -397,11 +416,12 @@ checksum = "4e1b7878800220a76a08f32c057829511440f65528b63b940f2f2bc145d7ac68"
[[package]] [[package]]
name = "rsblocks" name = "rsblocks"
version = "0.1.8" version = "0.1.9"
dependencies = [ dependencies = [
"alsa", "alsa",
"breadx", "breadx",
"chrono", "chrono",
"dbus",
"minreq", "minreq",
"mpd", "mpd",
"nix 0.19.1", "nix 0.19.1",

View File

@ -1,6 +1,6 @@
[package] [package]
name = "rsblocks" name = "rsblocks"
version = "0.1.8" version = "0.1.9"
authors = ["mustafa salih <mustafasalih1991@gmail.com>"] authors = ["mustafa salih <mustafasalih1991@gmail.com>"]
edition = "2018" edition = "2018"
readme = "README.md" readme = "README.md"
@ -17,6 +17,7 @@ minreq = "2.2.1"
alsa = "0.4.3" alsa = "0.4.3"
nix = "0.19.1" nix = "0.19.1"
mpd = "0.0.12" mpd = "0.0.12"
dbus = "0.9.1"
[dependencies.breadx] [dependencies.breadx]
version = "0.1.11" version = "0.1.11"

View File

@ -19,7 +19,6 @@ A multi threaded fast status bar for dwm window manager written in **Rust** 🦀
* Cpu Temperature * Cpu Temperature
* Uptime * Uptime
* Mpd Current Song File * Mpd Current Song File
* Spotify Current Song
* Easy to configure with `rsblocks.yml` file * Easy to configure with `rsblocks.yml` file
@ -27,16 +26,6 @@ A multi threaded fast status bar for dwm window manager written in **Rust** 🦀
* This tool is still in development stage. * This tool is still in development stage.
* currently supports only linux. * currently supports only linux.
## Build Requirements
* [Libdbus](https://dbus.freedesktop.org/releases/dbus/) 1.6 or higher as a spotify requirement
On Ubuntu, you can do :
```sh
sudo apt install libdbus-1-dev pkg-config
```
## Cargo Installation ## Cargo Installation
You can install the binary crate directly You can install the binary crate directly
```sh ```sh

View File

@ -6,6 +6,7 @@ general:
seperator: '┃' seperator: '┃'
# Time always running, no enable option for this
time: time:
icon: '' icon: ''
format: '%d %b, %I:%M:%S %p' format: '%d %b, %I:%M:%S %p'
@ -13,21 +14,21 @@ time:
memory: memory:
enable: true
icon: '▦' icon: '▦'
enable: true
delay: 2.0 delay: 2.0
disk: disk:
enable: true
icon: '' icon: ''
enable: true
delay: 120.0 delay: 120.0
battery: battery:
source: 'BAT0'
icon: '' icon: ''
enable: false enable: false
source: 'BAT0'
delay: 120.0 delay: 120.0
@ -45,15 +46,19 @@ mpd:
delay: 5.0 delay: 5.0
# reads from alsa, alsa-utils package should
# be installed on the system to make it work.
volume: volume:
enable: true
icon: '' icon: ''
enable: true
delay: 0.18 delay: 0.18
card: 'PULSE' card: 'PULSE'
spotify:
icon: ''
enable: false
delay: 0.5
# weather format options is available on # weather format options is available on
# https://github.com/chubin/wttr.in # https://github.com/chubin/wttr.in
# NOTES: # NOTES:

View File

@ -1,6 +1,32 @@
//! `rsblocks` A multi threaded status bar for dwm window manager.
/*
Licence: MIT
Author: Mustafa Salih
[MustafaSalih](https://github.com/MustafaSalih1993)
Contributers:
- AdaShoelace - for her/his contributions.
[AdaShoelace](https://github.com/AdaShoelace)
Thanks to:
- wttr.in - for using their weather API.
[wttr.in](https://github.com/chubin/wttr.in)
*/
use alsa::mixer::{Mixer, SelemChannelId, SelemId}; use alsa::mixer::{Mixer, SelemChannelId, SelemId};
use breadx::{display::*, window::Window}; use breadx::{display::*, window::Window};
use chrono::prelude::*; use chrono::prelude::*;
use dbus::blocking::stdintf::org_freedesktop_dbus::Properties;
use dbus::{arg, blocking::Connection};
use mpd::{Client, Song}; use mpd::{Client, Song};
use std::fs::File; use std::fs::File;
use std::io::Error; use std::io::Error;
@ -21,6 +47,7 @@ pub enum ThreadsData {
Battery(String), Battery(String),
CpuTemp(String), CpuTemp(String),
Uptime(String), Uptime(String),
Spotify(String),
} }
#[derive(Clone)] #[derive(Clone)]
@ -35,6 +62,7 @@ pub struct Config {
pub cpu_temperature: CpuTemp, pub cpu_temperature: CpuTemp,
pub uptime: Uptime, pub uptime: Uptime,
pub mpd: Mpd, pub mpd: Mpd,
pub spotify: Spotify,
} }
#[derive(Clone)] #[derive(Clone)]
@ -104,6 +132,33 @@ pub struct Mpd {
pub enabled: bool, pub enabled: bool,
pub delay: f64, pub delay: f64,
} }
#[derive(Clone)]
pub struct Spotify {
pub icon: String,
pub enabled: bool,
pub delay: f64,
}
pub struct Blocks {
disp: Display<name::NameConnection>,
root: Window,
}
impl Blocks {
pub fn new() -> Self {
let disp = Display::create(None, None).expect("Failed to create x11 connection");
let root = disp.default_screen().root;
Self { disp, root }
}
}
impl Default for Blocks {
fn default() -> Self {
Self::new()
}
}
/* TODOS /* TODOS
TODO 1: Error handling required if rsblocks.yml file is empty. TODO 1: Error handling required if rsblocks.yml file is empty.
@ -117,11 +172,12 @@ pub struct Mpd {
TODO 5: Fix repeated code for threads in `run` function. TODO 5: Fix repeated code for threads in `run` function.
TODO 6: Getting song metadata from mpd by a format provided by the user. TODO 6: Getting song metadata by a format provided by the user.
*/ */
/*this function is responsible to check if the rsblocks.yml file /*
this function is responsible to check if the rsblocks.yml file
exists to call parse_config to read it OTHERWISE exists to call parse_config to read it OTHERWISE
it will call load_defaults to load a hardcoded default configuration it will call load_defaults to load a hardcoded default configuration
@ -200,62 +256,80 @@ fn load_defaults() -> Config {
enabled: false, enabled: false,
delay: 15.0, delay: 15.0,
}, },
spotify: Spotify {
icon: String::from(""),
enabled: false,
delay: 15.0,
},
} }
} }
/* /*
it will read and parse the rsblocks.yml file content and return a valid configuration it will read and parse the rsblocks.yml file content and return a valid configuration
IF some content is missing in the rsblocks.yml file, it will set IF some content is missing in the rsblocks.yml file, it will set
a default values to that a default values to that.
NOTE: (get_or_set) functions job below getting the values from the configuration doc IF
a value is not exist in the config it will SET a value givin in the last argument.
*/ */
fn parse_config(doc: &yaml::Yaml) -> Config { fn parse_config(doc: &yaml::Yaml) -> Config {
// parsing icons and set default if not exist in the config file
let seperator = get_or_set_string(doc, "general", "seperator", "|"); let seperator = get_or_set_string(doc, "general", "seperator", "|");
// time values
let time_icon = get_or_set_string(doc, "time", "icon", ""); let time_icon = get_or_set_string(doc, "time", "icon", "");
let mem_icon = get_or_set_string(doc, "memory", "icon", "");
let disk_icon = get_or_set_string(doc, "disk", "icon", "");
let volume_icon = get_or_set_string(doc, "volume", "icon", "");
let weather_icon = get_or_set_string(doc, "weather", "icon", "");
let battery_icon = get_or_set_string(doc, "battery", "icon", "");
let cpu_temperature_icon = get_or_set_string(doc, "cpu_temperature", "icon", "");
let uptime_icon = get_or_set_string(doc, "uptime", "icon", "");
let mpd_icon = get_or_set_string(doc, "mpd", "icon", "");
//parsing formats and city weather
let time_format = get_or_set_string(doc, "time", "format", "%T"); let time_format = get_or_set_string(doc, "time", "format", "%T");
let weather_format = get_or_set_string(doc, "weather", "format", "%l:+%t");
let weather_city = get_or_set_string(doc, "weather", "city", "");
// parsing enabled state (everything false by default)
let disk_enabled = get_or_set_bool(doc, "disk", "enable");
let memory_enabled = get_or_set_bool(doc, "memory", "enable");
let volume_enabled = get_or_set_bool(doc, "volume", "enable");
let weather_enabled = get_or_set_bool(doc, "weather", "enable");
let battery_enabled = get_or_set_bool(doc, "battery", "enable");
let cpu_temperature_enabled = get_or_set_bool(doc, "cpu_temperature", "enable");
let uptime_enabled = get_or_set_bool(doc, "uptime", "enable");
let mpd_enabled = get_or_set_bool(doc, "mpd", "enable");
// parsing update_delay state (should be all seconds in f64 type)
let time_delay = get_or_set_f64(doc, "time", "delay", 1.0); let time_delay = get_or_set_f64(doc, "time", "delay", 1.0);
let disk_delay = get_or_set_f64(doc, "disk", "delay", 120.0);
let memory_delay = get_or_set_f64(doc, "memory", "delay", 2.0);
let volume_delay = get_or_set_f64(doc, "volume", "delay", 0.17);
let weather_delay = get_or_set_f64(doc, "weather", "delay", 7200.0);
let battery_delay = get_or_set_f64(doc, "battery", "delay", 120.0);
let cpu_temperature_delay = get_or_set_f64(doc, "cpu_temperature", "delay", 120.0);
let uptime_delay = get_or_set_f64(doc, "uptime", "delay", 60.0);
let mpd_delay = get_or_set_f64(doc, "mpd", "delay", 15.0);
// parsing card for volume, ALSA or PULSE // memory values
let mem_icon = get_or_set_string(doc, "memory", "icon", "");
let memory_enabled = get_or_set_bool(doc, "memory", "enable");
let memory_delay = get_or_set_f64(doc, "memory", "delay", 2.0);
//disk values
let disk_icon = get_or_set_string(doc, "disk", "icon", "");
let disk_enabled = get_or_set_bool(doc, "disk", "enable");
let disk_delay = get_or_set_f64(doc, "disk", "delay", 120.0);
// volume values
let volume_icon = get_or_set_string(doc, "volume", "icon", "");
let volume_enabled = get_or_set_bool(doc, "volume", "enable");
let volume_delay = get_or_set_f64(doc, "volume", "delay", 0.17);
let volume_card = get_or_set_string(doc, "volume", "card", "ALSA"); let volume_card = get_or_set_string(doc, "volume", "card", "ALSA");
// parsing battery source name // weather values
let battery_source = get_or_set_string(doc, "battery", "source", "BAT0"); let weather_icon = get_or_set_string(doc, "weather", "icon", "");
let weather_format = get_or_set_string(doc, "weather", "format", "%l:+%t");
let weather_city = get_or_set_string(doc, "weather", "city", "");
let weather_enabled = get_or_set_bool(doc, "weather", "enable");
let weather_delay = get_or_set_f64(doc, "weather", "delay", 7200.0);
//parsing mpd host and port // battery values
let battery_icon = get_or_set_string(doc, "battery", "icon", "");
let battery_enabled = get_or_set_bool(doc, "battery", "enable");
let battery_source = get_or_set_string(doc, "battery", "source", "BAT0");
let battery_delay = get_or_set_f64(doc, "battery", "delay", 120.0);
// cpu values
let cpu_temperature_icon = get_or_set_string(doc, "cpu_temperature", "icon", "");
let cpu_temperature_enabled = get_or_set_bool(doc, "cpu_temperature", "enable");
let cpu_temperature_delay = get_or_set_f64(doc, "cpu_temperature", "delay", 120.0);
// uptime values
let uptime_icon = get_or_set_string(doc, "uptime", "icon", "");
let uptime_enabled = get_or_set_bool(doc, "uptime", "enable");
let uptime_delay = get_or_set_f64(doc, "uptime", "delay", 60.0);
// mpd values
let mpd_icon = get_or_set_string(doc, "mpd", "icon", "");
let mpd_host = get_or_set_string(doc, "mpd", "host", "127.0.0.1"); let mpd_host = get_or_set_string(doc, "mpd", "host", "127.0.0.1");
let mpd_port = get_or_set_string(doc, "mpd", "port", "6600"); let mpd_port = get_or_set_string(doc, "mpd", "port", "6600");
let mpd_enabled = get_or_set_bool(doc, "mpd", "enable");
let mpd_delay = get_or_set_f64(doc, "mpd", "delay", 15.0);
//spotify values
let spotify_icon = get_or_set_string(doc, "spotify", "icon", "");
let spotify_enabled = get_or_set_bool(doc, "spotify", "enable");
let spotify_delay = get_or_set_f64(doc, "spotify", "delay", 10.0);
Config { Config {
seperator, seperator,
@ -310,10 +384,15 @@ fn parse_config(doc: &yaml::Yaml) -> Config {
enabled: mpd_enabled, enabled: mpd_enabled,
delay: mpd_delay, delay: mpd_delay,
}, },
spotify: Spotify {
icon: spotify_icon,
enabled: spotify_enabled,
delay: spotify_delay,
},
} }
} }
// getting a f32 value from rsblocks.yml file or set default (last argument) // getting a f64 value from rsblocks.yml file or set default (last argument)
fn get_or_set_f64(doc: &yaml::Yaml, parent: &str, child: &str, default: f64) -> f64 { fn get_or_set_f64(doc: &yaml::Yaml, parent: &str, child: &str, default: f64) -> f64 {
let val: f64 = if doc[parent][child].is_badvalue() { let val: f64 = if doc[parent][child].is_badvalue() {
default default
@ -352,28 +431,21 @@ fn get_or_set_string(doc: &yaml::Yaml, parent: &str, child: &str, default_val: &
// Running the program: // Running the program:
pub struct Blocks {
disp: Display<name::NameConnection>,
root: Window,
}
impl Blocks {
pub fn new() -> Self {
let disp = Display::create(None, None).expect("Failed to create x11 connection");
let root = disp.default_screen().root;
Self { disp, root }
}
}
impl Default for Blocks {
fn default() -> Self {
Self::new()
}
}
pub fn run(config: Config, mut blocks: Blocks) { pub fn run(config: Config, mut blocks: Blocks) {
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
// spotify thread
if config.spotify.enabled {
let spotify_tx = tx.clone();
let configcp = config.clone();
let mut spotify_data = ThreadsData::Spotify(get_spotify(&configcp));
thread::spawn(move || loop {
spotify_tx.send(spotify_data).unwrap();
spotify_data = ThreadsData::Spotify(get_spotify(&configcp));
thread::sleep(Duration::from_secs_f64(configcp.spotify.delay))
});
}
// mpd thread // mpd thread
if config.mpd.enabled { if config.mpd.enabled {
let mpd_tx = tx.clone(); let mpd_tx = tx.clone();
@ -474,6 +546,7 @@ pub fn run(config: Config, mut blocks: Blocks) {
thread::sleep(Duration::from_secs_f64(configcp.uptime.delay)) thread::sleep(Duration::from_secs_f64(configcp.uptime.delay))
}); });
} }
// Time thread // Time thread
{ {
let time_tx = tx; let time_tx = tx;
@ -489,19 +562,20 @@ pub fn run(config: Config, mut blocks: Blocks) {
//Main //Main
{ {
// NOTE: order matters to the final format // NOTE: order matters to the final format
let mut bar: Vec<String> = vec!["".to_string(); 9]; let mut bar: Vec<String> = vec!["".to_string(); 10];
//iterating the values recieved from the threads //iterating the values recieved from the threads
for data in rx { for data in rx {
match data { match data {
ThreadsData::Mpd(x) => bar[0] = x, ThreadsData::Spotify(x) => bar[0] = x,
ThreadsData::Sound(x) => bar[1] = x, ThreadsData::Mpd(x) => bar[1] = x,
ThreadsData::Weather(x) => bar[2] = x, ThreadsData::Sound(x) => bar[2] = x,
ThreadsData::Disk(x) => bar[3] = x, ThreadsData::Weather(x) => bar[3] = x,
ThreadsData::Memory(x) => bar[4] = x, ThreadsData::Disk(x) => bar[4] = x,
ThreadsData::CpuTemp(x) => bar[5] = x, ThreadsData::Memory(x) => bar[5] = x,
ThreadsData::Battery(x) => bar[6] = x, ThreadsData::CpuTemp(x) => bar[6] = x,
ThreadsData::Uptime(x) => bar[7] = x, ThreadsData::Battery(x) => bar[7] = x,
ThreadsData::Time(x) => bar[8] = x, ThreadsData::Uptime(x) => bar[8] = x,
ThreadsData::Time(x) => bar[9] = x,
} }
// match ends here // match ends here
@ -511,7 +585,6 @@ pub fn run(config: Config, mut blocks: Blocks) {
} }
pub fn update(bar: &[String], blocks: &mut Blocks) { pub fn update(bar: &[String], blocks: &mut Blocks) {
// TODO: FIX ME, this solution sucks
let mut x = String::new(); let mut x = String::new();
for i in bar.iter() { for i in bar.iter() {
x.push_str(i.as_str()); x.push_str(i.as_str());
@ -544,10 +617,7 @@ pub fn get_time(config: &Config) -> String {
) )
} }
/* // will make a GET request from wttr.in
CREDIT: thanks for wttr.in to use their API
will make a GET request from wttr.in
*/
fn get_weather(config: &Config) -> String { fn get_weather(config: &Config) -> String {
let format = if config.weather.format.is_empty() { let format = if config.weather.format.is_empty() {
String::from("%l:+%t") String::from("%l:+%t")
@ -585,6 +655,7 @@ pub fn get_disk(config: &Config) -> String {
) )
} }
// getting volume percentage
pub fn get_volume(config: &Config) -> String { pub fn get_volume(config: &Config) -> String {
let card = if config.volume.card == "PULSE" { let card = if config.volume.card == "PULSE" {
"pulse" "pulse"
@ -763,19 +834,21 @@ pub fn get_uptime(config: &Config) -> Result<String, std::io::Error> {
Ok(result) Ok(result)
} }
// yes, error handling looks fucking sucks!
// getting mpd song file // getting mpd song file
pub fn get_mpd_current(config: &Config) -> String { pub fn get_mpd_current(config: &Config) -> String {
let stream_path = format!("{}:{}", config.mpd.host, config.mpd.port); let stream_path = format!("{}:{}", config.mpd.host, config.mpd.port);
let empty_string = String::from("");
let mut conn = match Client::connect(&stream_path) { let mut conn = match Client::connect(&stream_path) {
Ok(connection) => connection, Ok(connection) => connection,
_ => return String::from(""), _ => return empty_string,
}; };
let current: Song = match conn.currentsong() { let current: Song = match conn.currentsong() {
Ok(opt) => match opt { Ok(opt) => match opt {
Some(song) => song, Some(song) => song,
_ => return String::from(""), _ => return empty_string,
}, },
_ => return String::from(""), _ => return empty_string,
}; };
let result = format!( let result = format!(
@ -785,3 +858,44 @@ pub fn get_mpd_current(config: &Config) -> String {
result result
} }
// getting spotify current artist and title.
// FIXME: I know im lazy asshole, this error handling looks ugly, i dont like it too, need to fix soon.
fn get_spotify(config: &Config) -> String {
let conn = match Connection::new_session() {
Ok(conn) => conn,
_ => return String::from(""),
};
let p = conn.with_proxy(
"org.mpris.MediaPlayer2.spotify",
"/org/mpris/MediaPlayer2",
Duration::from_millis(5000),
);
let metadata: arg::PropMap = match p.get("org.mpris.MediaPlayer2.Player", "Metadata") {
Ok(data) => data,
_ => return String::from(""),
};
let title: Option<&String> = arg::prop_cast(&metadata, "xesam:title");
let artist: Option<&Vec<String>> = arg::prop_cast(&metadata, "xesam:artist");
let title = match title {
Some(title) => title,
_ => "",
};
let artist = match artist {
Some(artist_vec) => match artist_vec.first() {
Some(name) => name,
_ => "",
},
None => "",
};
format!(
" {} {} - {} {}",
config.spotify.icon, artist, title, config.seperator
)
}