8.9 KiB · text History 0463cca
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use std::path::PathBuf;

use scropple_linux::backend::{Lastfm, ListenBrainz};
use scropple_linux::config::{self, BackendConfig, Config, Kind, project_dirs};
use scropple_linux::mpris::{self, PREFIX, PlayerProxy};
use scropple_linux::{daemon, queue::Queue};

/// Scrobble what Linux media players play (MPRIS) to Scropple servers
/// (final_track, ircd's ScrobbleServ), ListenBrainz and Last.fm.
#[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,
    /// Sign a backend in: Last.fm through the browser; ListenBrainz and
    /// Scropple servers by pasting a token. Saves it to the backend's
    /// token_file.
    Login {
        /// The backend's name in the config
        backend: String,
    },
    /// 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());
            println!("  2. scropple login finaltrack   (and each backend you add)");
            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()?;
                let signed_in = if token.is_empty() {
                    format!("not signed in: scropple login {}", b.name)
                } else {
                    format!("token: {} chars", token.len())
                };
                println!(
                    "backend {:?}: {} at {} ({signed_in})",
                    b.name,
                    b.kind.as_str(),
                    b.endpoint(),
                );
                if b.kind == Kind::Lastfm {
                    b.lastfm_credentials()?;
                    println!("  API key and secret: {}", b.lastfm_credentials_source());
                }
            }
            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,
        Command::Login { backend } => {
            let config = Config::load(&config_path)?;
            let Some(b) = config.backends.iter().find(|b| b.name == backend) else {
                let names: Vec<_> = config.backends.iter().map(|b| b.name.as_str()).collect();
                anyhow::bail!("no backend {backend:?} in the config (there are: {names:?})");
            };
            login(b).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(())
}

async fn login(b: &BackendConfig) -> Result<()> {
    let Some(file) = &b.token_file else {
        anyhow::bail!(
            "backend {:?} has its token inline; set token_file instead to sign in",
            b.name
        );
    };
    let token = match b.kind {
        Kind::Lastfm => {
            let (key, secret) = b.lastfm_credentials()?;
            let lastfm = Lastfm::new(&b.name, b.endpoint(), &key, &secret, "");
            let (request, url) = lastfm.request_token().await?;
            println!("Allow Scropple to scrobble to your Last.fm account:\n\n  {url}\n");
            let _ = std::process::Command::new("xdg-open")
                .arg(&url)
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn();
            prompt("Press Enter once you've allowed it")?;
            let (session, user) = lastfm.session(&request).await.context(
                "Last.fm didn't give a session; was access allowed? (the link lasts an hour)",
            )?;
            println!("signed in to Last.fm as {user}");
            session
        }
        Kind::Listenbrainz => {
            println!("Your user token is on https://listenbrainz.org/settings/");
            let token = prompt("Token")?;
            let user = ListenBrainz::validate(b.endpoint(), &token).await?;
            println!("signed in to ListenBrainz as {user}");
            token
        }
        Kind::Scropple => {
            println!(
                "Make a token on the server's Scrobbling page ({})",
                b.endpoint()
            );
            prompt("Token")?
        }
    };
    if token.is_empty() {
        anyhow::bail!("no token given");
    }
    config::write_private(file, &format!("{token}\n"))?;
    println!("saved to {} (0600)", file.display());
    println!("restart scropple to use it: systemctl --user restart scropple");
    Ok(())
}

fn prompt(label: &str) -> Result<String> {
    use std::io::Write;
    print!("{label}: ");
    std::io::stdout().flush()?;
    let mut line = String::new();
    std::io::stdin().read_line(&mut line)?;
    Ok(line.trim().to_string())
}

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