playdoobs 0.1.0

Service and matching CLI application for controlling the currently active MPRIS2 player
Documentation
use clap::{Parser, Subcommand};
use color_eyre::eyre::Context;
use jiff::SignedDuration;
use playdoobs::types::{Metadata, TrackId};
use playdoobs::{PLAYER_DBUS_NAME_METADATA_KEY, PlaydoobsdBlocking, VERSION, parse_player_name};
use zbus::zvariant::{OwnedValue, Value};

#[derive(Parser)]
#[command(version = VERSION, about)]
#[command(propagate_version = true)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

// IMPORTANT: firefox acts really weird in regards to getting the position and seeking
// seeking always seems to be in 5s increments
// the position keeps increasing on every call even if the video is stopped
// the behavior is the same when using `busctl`
// so we better use mpv for testing to not be confused by whatever firefox does

#[derive(Subcommand)]
enum Commands {
    /// Toggle play/pause.
    PlayPause,
    /// Start or resume playback.
    Play,
    /// Pause playback.
    Pause,
    /// Stop playback.
    Stop,
    /// Skip to the next track.
    Next,
    /// Skip to the previous track.
    Previous,
    /// Returns or sets the current track position in seconds.
    Position { position: Option<SignedDuration> },
    /// Seeks forward/back in the current track by the specified number of seconds.
    Seek { offset: SignedDuration },
    /// Show the metadata for the current track.
    Metadata,
}

fn main() -> color_eyre::Result<()> {
    let cli = Cli::parse();
    color_eyre::install()?;

    let player = PlaydoobsdBlocking::connect().wrap_err("Failed to connect to playdoobsd")?;

    match cli.command {
        Commands::PlayPause => player
            .play_pause()
            .wrap_err("Failed to toggle play/pause")?,
        Commands::Play => player.play().wrap_err("Failed to start playback")?,
        Commands::Pause => player.pause().wrap_err("Failed to pause playback")?,
        Commands::Stop => player.stop().wrap_err("Failed to stop playback")?,
        Commands::Next => player.next().wrap_err("Failed to switch to next track")?,
        Commands::Previous => player
            .previous()
            .wrap_err("Failed to switch to previous track")?,
        Commands::Position { position } => match position {
            Some(position) => {
                let metadata = player.metadata().wrap_err("Failed to read metadata")?;

                if let Some(track_id) = metadata.track_id() {
                    let track_id = TrackId::try_from(Value::from(track_id))
                        .wrap_err("Failed to parse track ID from metadata")?;
                    player
                        .set_position(track_id, position.into())
                        .wrap_err_with(|| format!("Failed to set position to: {position}"))?;
                } else {
                    eprintln!("No track ID for current track");
                }
            }
            None => {
                let position = player
                    .position()
                    .wrap_err("Failed to get playback position")?;
                // debug repr for SignedDuration is human readable
                println!("Playback position: {position:?}");
            }
        },
        Commands::Seek { offset } => player
            .seek(offset.into())
            .wrap_err_with(|| format!("Failed to seek with offset: {offset}"))?,
        Commands::Metadata => pretty_print_metadata(
            player
                .metadata()
                .wrap_err("Failed to get metadata for current track")?,
        ),
    }

    Ok(())
}

fn pretty_print_metadata(m: Metadata) {
    // TODO check for /NoTrack or something
    // iter over the keys so we can print all entries
    for (k, v) in m.iter() {
        let (field_name, field_value) = match k.as_str() {
            "xesam:title" => ("Title", m.title()),
            "xesam:url" => ("URL", m.url()),
            "xesam:album" => ("Album", m.album()),
            PLAYER_DBUS_NAME_METADATA_KEY => ("Player", player_name(v)),
            "mpris:trackid" => ("Track ID", m.track_id().map(|t| t.to_string())),
            // debug repr for SignedDuration is human readable
            "mpris:length" => ("Length", m.length().map(|l| format!("{l:?}"))),
            "mpris:artUrl" => ("Art URL", m.art_url()),
            "xesam:artist" => ("Artist", m.artists().map(|a| a.join(", "))),
            k => (k, Some(v.to_string())),
        };
        println!(
            "{field_name:<8} - {field_value}",
            field_value = field_value.unwrap_or_default()
        );
    }
}

fn player_name(value: &OwnedValue) -> Option<String> {
    let value: String = value.clone().try_into().unwrap_or_default();
    parse_player_name(&value).ok()
}