5.8 KiB · text History 6c56e6c
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use std::path::PathBuf;

use scropple_linux::config::{self, Config, project_dirs};
use scropple_linux::mpris::{self, PREFIX, PlayerProxy};
use scropple_linux::{daemon, queue::Queue};

/// Scrobble what Linux media players play (MPRIS) to Scropple-compatible
/// backends: final_track, ircd's ScrobbleServ, anything speaking the
/// Scropple HTTP backend's JSON.
#[derive(Parser)]
#[command(version)]
struct Cli {
    /// Config file [default: ~/.config/scropple/config.toml]
    #[arg(long, global = true)]
    config: Option<PathBuf>,

    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand)]
enum Command {
    /// Run the daemon (the default)
    Run,
    /// Write the example config to the config path, and an empty token file
    Init {
        /// Replace an existing config
        #[arg(long)]
        force: bool,
    },
    /// Show the players on the bus, what they're playing, and whether it would scrobble
    Players,
    /// Check the config: backends, tokens, filter
    Check,
    /// How many scrobbles wait, per backend
    Queue,
}

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "scropple=info,scropple_linux=info".into()),
        )
        .with_target(false)
        // stderr: where journald picks it up under systemd, and out of the
        // way of `players`/`queue` output.
        .with_writer(std::io::stderr)
        // Colours only on a terminal: under systemd they'd be escape codes
        // in the journal.
        .with_ansi(std::io::IsTerminal::is_terminal(&std::io::stderr()))
        .init();

    let cli = Cli::parse();
    let config_path = match cli.config {
        Some(p) => p,
        None => Config::default_path()?,
    };
    let queue_path = state_dir()?.join("queue.sqlite");

    match cli.command.unwrap_or(Command::Run) {
        Command::Run => {
            let config = Config::load(&config_path)?;
            daemon::run(config, &queue_path).await
        }
        Command::Init { force } => {
            let done = config::init(&config_path, force)?;
            println!("wrote {}", done.config.display());
            for token in &done.created_tokens {
                println!("created {} (empty, 0600)", token.display());
            }
            println!("\nnext:");
            println!("  1. set your backend's url in {}", done.config.display());
            for token in &done.created_tokens {
                println!(
                    "  2. paste a token from its Scrobbling page into {}",
                    token.display()
                );
            }
            println!("  3. scropple check");
            println!("  4. systemctl --user enable --now scropple   (contrib/scropple.service)");
            Ok(())
        }
        Command::Check => {
            let config = Config::load(&config_path)?;
            println!("config: {}", config_path.display());
            println!("tick: every {}s", config.tick_seconds);
            for b in &config.backends {
                let token = b.token()?;
                println!(
                    "backend {:?}: {} (token: {} chars)",
                    b.name,
                    b.url,
                    token.len()
                );
            }
            if config.backends.is_empty() {
                println!("no backends: plays would only be logged");
            }
            Ok(())
        }
        Command::Queue => {
            let q = Queue::open(&queue_path)?;
            let counts = q.counts()?;
            if counts.is_empty() {
                println!("nothing waiting");
            }
            for (backend, n) in counts {
                println!("{backend}: {n} waiting");
            }
            Ok(())
        }
        Command::Players => players(&config_path).await,
    }
}

async fn players(config_path: &std::path::Path) -> Result<()> {
    let filter = if config_path.exists() {
        Config::load(config_path)?.filter()
    } else {
        Default::default()
    };
    let conn = zbus::Connection::session()
        .await
        .context("connecting to the session bus")?;
    let dbus = zbus::fdo::DBusProxy::new(&conn).await?;
    let mut found = false;
    for name in dbus.list_names().await? {
        let name = name.to_string();
        if !name.starts_with(PREFIX) {
            continue;
        }
        found = true;
        let player = mpris::player_name(&name).unwrap_or("?");
        let proxy = PlayerProxy::builder(&conn)
            .destination(name.clone())?
            .build()
            .await?;
        let status = proxy.playback_status().await.unwrap_or_else(|_| "?".into());
        let allowed = if filter.allows(player) {
            "scrobbled"
        } else {
            "filtered out"
        };
        println!("{name}\n  player: {player} ({allowed}), {status}");
        match proxy
            .metadata()
            .await
            .ok()
            .and_then(|m| mpris::parse_metadata(player, &m))
        {
            Some(t) => println!(
                "  {} — {}{}{}",
                t.artist,
                t.title,
                t.album.map(|a| format!(" ({a})")).unwrap_or_default(),
                if t.duration_ms > 0 {
                    format!(", {}s", t.duration_ms / 1000)
                } else {
                    ", length unknown".into()
                }
            ),
            None => println!("  nothing scrobbleable (no artist and title)"),
        }
    }
    if !found {
        println!("no MPRIS players on the session bus");
    }
    Ok(())
}

fn state_dir() -> Result<PathBuf> {
    let dirs = project_dirs()?;
    Ok(dirs
        .state_dir()
        .unwrap_or_else(|| dirs.data_local_dir())
        .to_path_buf())
}