Skip to content

Instantly share code, notes, and snippets.

@Marco3jp
Last active February 26, 2021 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Marco3jp/61441af8b6f80fc5532095f580c2eda5 to your computer and use it in GitHub Desktop.
Save Marco3jp/61441af8b6f80fc5532095f580c2eda5 to your computer and use it in GitHub Desktop.
notification to /tmp/now_playing.txt, now spotify playing info.
[package]
name = "spotification"
version = "0.3.0"
authors = ["marco <marco3jp+git@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
mpris = "1.1.2"
use mpris::{PlayerFinder, Metadata};
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::env;
use mpris::PlaybackStatus::Playing;
fn main() {
let args: Vec<String> = env::args().collect();
let mut player_name = "spotifyd";
if args.len() > 1 {
player_name = &args[1]
}
let players = PlayerFinder::new()
.expect("Could not connect to D-Bus")
.find_all()
.expect("Could not find any player");
// println!("{:#?}", players);
for player in players {
if player.bus_name().to_string() == String::from("org.mpris.MediaPlayer2.".to_owned() + player_name) {
match player.get_playback_status() {
Ok(result) => if result != Playing {
create_now_playing_file("今は音楽を再生していないみたいです".to_string());
return;
}
Err(msg) => println!("error: {:#?}", msg)
}
let metadata = player.get_metadata().expect("Could not get metadata for player");
let message = get_now_playing_message(metadata);
// println!("{:#?}", message);
create_now_playing_file(message);
}
}
}
fn get_now_playing_message(metadata: Metadata) -> String {
let artists = metadata.artists().unwrap().join(", ");
let song_title = metadata.title().unwrap();
return format!("今は{}の{}を聴いているよ!", artists, song_title);
}
fn create_now_playing_file(message: String) {
let path = Path::new("/tmp/now_playing.txt");
let display = path.display();
let mut file = match File::create(&path) {
Err(why) => panic!("couldn't create {}: {}", display, why),
Ok(file) => file,
};
match file.write_all(message.as_bytes()) {
Err(why) => panic!("couldn't write to {}: {}", display, why),
Ok(_) => println!("successfully wrote to {}", display),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment