lastfmpris/src/player.rs
2024-09-11 17:31:19 -07:00

51 lines
No EOL
1.4 KiB
Rust

use crate::config::Config;
use anyhow::{anyhow, Result, Context};
use mpris::{Player, PlayerFinder, PlaybackStatus};
use std::thread;
use std::time::Duration;
const INTERVAL: Duration = Duration::from_millis(1000);
const MPRIS_BUS_PREFIX: &str = "org.mpris.MediaPlayer2.";
pub fn is_active(player: &Player) -> bool {
if !player.is_running() { return false; }
matches!(player.get_playback_status(), Ok(PlaybackStatus::Playing))
}
pub fn is_whitelisted(config: &Config, player: &Player) -> bool {
if Some(player.bus_name()) == config.global.player_bus.as_deref() {
return true
} else if config.global.player_bus.is_none() {
return player.bus_name().starts_with(MPRIS_BUS_PREFIX)
} else {
return false
}
}
pub fn wait_for_player(config: &Config) -> Result<Player> {
let finder = PlayerFinder::new()
.map_err(|err| anyhow!("{}", err))
.context("failed to connect to d-bus")?;
loop {
let players = match finder.iter_players() {
Ok(players) => players,
_ => {
thread::sleep(INTERVAL);
continue;
}
};
for player in players {
if let Ok(player) = player {
if is_active(&player) && is_whitelisted(config, &player) {
return Ok(player);
}
}
}
thread::sleep(INTERVAL);
}
}