17.0 KiB · text History 0463cca
//! `~/.config/scropple/config.toml`:
//!
//! ```toml
//! # How often playback time is checked against the scrobble threshold.
//! tick_seconds = 5
//!
//! [filter]
//! # Players never scrobbled (replaces the default list: browsers, KDE
//! # Connect, GSConnect, playerctld).
//! # deny = ["firefox", "chromium"]
//! # Only these, if set.
//! # allow = ["spotify", "strawberry"]
//!
//! [[backend]]
//! name = "finaltrack"
//! url = "https://finaltrack.neiam.org"
//! token_file = "finaltrack.token"   # next to this file; or: token = "..."
//!
//! [[backend]]
//! name = "listenbrainz"
//! type = "listenbrainz"              # url defaults to api.listenbrainz.org
//! token_file = "listenbrainz.token"
//!
//! [[backend]]
//! name = "lastfm"
//! type = "lastfm"
//! token_file = "lastfm.session"      # written by `scropple login lastfm`
//! # api_key = "..."; api_secret_file = "lastfm.secret"  (unless built in)
//! ```

use anyhow::{Context, Result, bail};
use serde::Deserialize;
use std::path::{Path, PathBuf};

use crate::engine::{DEFAULT_DENY, Filter};

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    #[serde(default = "default_tick")]
    pub tick_seconds: u64,
    #[serde(default)]
    pub filter: FilterConfig,
    #[serde(default, rename = "backend")]
    pub backends: Vec<BackendConfig>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FilterConfig {
    pub deny: Option<Vec<String>>,
    pub allow: Option<Vec<String>>,
}

/// What a backend speaks.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
    /// The Scropple HTTP contract: final_track, ircd's ScrobbleServ.
    #[default]
    Scropple,
    Listenbrainz,
    Lastfm,
}

impl Kind {
    pub fn as_str(self) -> &'static str {
        match self {
            Kind::Scropple => "scropple",
            Kind::Listenbrainz => "listenbrainz",
            Kind::Lastfm => "lastfm",
        }
    }
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BackendConfig {
    pub name: String,
    #[serde(default, rename = "type")]
    pub kind: Kind,
    /// The server's base URL. Required for scropple (`/api/v1/scrobble` and
    /// `/api/v1/now-playing` are under it); ListenBrainz and Last.fm default
    /// to their own.
    pub url: Option<String>,
    /// The bearer token (scropple), user token (ListenBrainz) or session key
    /// (Last.fm, from `scropple login`).
    pub token: Option<String>,
    pub token_file: Option<PathBuf>,
    /// Last.fm only: the application's key and secret, when this build
    /// doesn't have them built in.
    pub api_key: Option<String>,
    pub api_secret: Option<String>,
    pub api_secret_file: Option<PathBuf>,
}

fn default_tick() -> u64 {
    5
}

impl Config {
    pub fn default_path() -> Result<PathBuf> {
        Ok(project_dirs()?.config_dir().join("config.toml"))
    }

    /// Reads and checks a config file. A relative `token_file` is resolved
    /// against the file's own directory, so a token sits next to its config
    /// whatever XDG_CONFIG_HOME, `--config` or HOME say.
    pub fn load(path: &Path) -> Result<Self> {
        let text =
            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
        let mut config = Self::parse(&text).with_context(|| format!("in {}", path.display()))?;
        let dir = path.parent().unwrap_or(Path::new("."));
        for b in &mut config.backends {
            if let Some(file) = &b.token_file {
                b.token_file = Some(resolve(dir, file));
            }
            if let Some(file) = &b.api_secret_file {
                b.api_secret_file = Some(resolve(dir, file));
            }
        }
        Ok(config)
    }

    pub fn parse(text: &str) -> Result<Self> {
        let config: Config = toml::from_str(text)?;
        if config.tick_seconds == 0 {
            bail!("tick_seconds must be at least 1");
        }
        let mut names = std::collections::HashSet::new();
        for b in &config.backends {
            if !names.insert(&b.name) {
                bail!("two backends are named {:?}", b.name);
            }
            if b.token.is_some() == b.token_file.is_some() {
                bail!(
                    "backend {:?}: give exactly one of token, token_file",
                    b.name
                );
            }
            match b.kind {
                Kind::Scropple if b.url.is_none() => {
                    bail!("backend {:?}: a scropple backend needs a url", b.name)
                }
                Kind::Lastfm => {
                    if b.api_secret.is_some() && b.api_secret_file.is_some() {
                        bail!(
                            "backend {:?}: give at most one of api_secret, api_secret_file",
                            b.name
                        );
                    }
                    let key =
                        b.api_key.is_some() || crate::backend::lastfm::BUILTIN_API_KEY.is_some();
                    let secret = b.api_secret.is_some()
                        || b.api_secret_file.is_some()
                        || crate::backend::lastfm::BUILTIN_API_SECRET.is_some();
                    if !(key && secret) {
                        bail!(
                            "backend {:?}: this build has no Last.fm API key built in; set api_key and api_secret (or api_secret_file) from https://www.last.fm/api/account/create",
                            b.name
                        );
                    }
                }
                _ if b.api_key.is_some()
                    || b.api_secret.is_some()
                    || b.api_secret_file.is_some() =>
                {
                    bail!(
                        "backend {:?}: api_key and api_secret are for Last.fm",
                        b.name
                    )
                }
                _ => {}
            }
        }
        Ok(config)
    }

    pub fn filter(&self) -> Filter {
        let deny = self
            .filter
            .deny
            .clone()
            .unwrap_or_else(|| DEFAULT_DENY.iter().map(|s| s.to_string()).collect());
        Filter::new(deny, self.filter.allow.clone())
    }
}

impl BackendConfig {
    /// The base URL, the backend's default when unset.
    pub fn endpoint(&self) -> &str {
        match (&self.url, self.kind) {
            (Some(url), _) => url,
            (None, Kind::Listenbrainz) => crate::backend::listenbrainz::ROOT,
            (None, Kind::Lastfm) => crate::backend::lastfm::ROOT,
            (None, Kind::Scropple) => "",
        }
    }

    /// Last.fm's API key and secret: from the config, else built in.
    pub fn lastfm_credentials(&self) -> Result<(String, String)> {
        use crate::backend::lastfm::{BUILTIN_API_KEY, BUILTIN_API_SECRET};
        let key = match (&self.api_key, BUILTIN_API_KEY) {
            (Some(k), _) => k.trim().to_string(),
            (None, Some(k)) => k.to_string(),
            (None, None) => bail!("backend {:?}: no Last.fm api_key", self.name),
        };
        let secret = match (&self.api_secret, &self.api_secret_file, BUILTIN_API_SECRET) {
            (Some(s), _, _) => s.trim().to_string(),
            (None, Some(path), _) => std::fs::read_to_string(path)
                .with_context(|| format!("backend {:?}: reading {}", self.name, path.display()))?
                .trim()
                .to_string(),
            (None, None, Some(s)) => s.to_string(),
            (None, None, None) => bail!("backend {:?}: no Last.fm api_secret", self.name),
        };
        Ok((key, secret))
    }

    /// Where the API key and secret come from, for `check`.
    pub fn lastfm_credentials_source(&self) -> &'static str {
        if self.api_key.is_some() {
            "from the config"
        } else {
            "built in"
        }
    }

    /// The token: inline, or the trimmed contents of `token_file` (`~`
    /// expanded). Empty means not signed in yet.
    pub fn token(&self) -> Result<String> {
        match (&self.token, &self.token_file) {
            (Some(t), _) => Ok(t.trim().to_string()),
            (None, Some(path)) => match std::fs::read_to_string(path) {
                Ok(t) => Ok(t.trim().to_string()),
                // Not written yet: not signed in.
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
                Err(e) => Err(e).with_context(|| {
                    format!("backend {:?}: reading {}", self.name, path.display())
                }),
            },
            (None, None) => bail!("backend {:?} has no token", self.name),
        }
    }
}

/// The annotated example config, as `scropple init` writes it.
pub const EXAMPLE: &str = include_str!("../contrib/config.example.toml");

/// What `init` did.
#[derive(Debug, PartialEq, Eq)]
pub struct Init {
    pub config: PathBuf,
    /// Token files created empty (0600), waiting for a token.
    pub created_tokens: Vec<PathBuf>,
}

/// Writes [`EXAMPLE`] to `path` (creating its directory), and creates each
/// token file it names that doesn't exist yet: empty, mode 0600. An
/// existing config is only replaced with `force`; an existing token file is
/// never touched.
pub fn init(path: &Path, force: bool) -> Result<Init> {
    if path.exists() && !force {
        bail!("{} already exists (--force to replace it)", path.display());
    }
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
    }
    std::fs::write(path, EXAMPLE).with_context(|| format!("writing {}", path.display()))?;

    let mut created_tokens = vec![];
    let dir = path.parent().unwrap_or(Path::new("."));
    for backend in Config::parse(EXAMPLE)?.backends {
        if let Some(file) = &backend.token_file {
            let token = resolve(dir, file);
            if !token.exists() {
                create_private(&token)?;
                created_tokens.push(token);
            }
        }
    }
    Ok(Init {
        config: path.to_path_buf(),
        created_tokens,
    })
}

/// Writes `contents` to `path`, readable only by its owner (0600), whether
/// or not it existed.
pub fn write_private(path: &Path, contents: &str) -> Result<()> {
    use std::io::Write;
    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    let mut f = std::fs::OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .mode(0o600)
        .open(path)
        .with_context(|| format!("writing {}", path.display()))?;
    f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
    f.write_all(contents.as_bytes())?;
    Ok(())
}

fn create_private(path: &Path) -> Result<()> {
    use std::os::unix::fs::OpenOptionsExt;
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(path)
        .with_context(|| format!("creating {}", path.display()))?;
    Ok(())
}

pub fn project_dirs() -> Result<directories::ProjectDirs> {
    directories::ProjectDirs::from("org", "neiam", "scropple").context("no home directory")
}

/// A path from the config: `~/…` is under the home directory, a relative
/// path is under `dir` (the config file's), an absolute one is itself.
pub fn resolve(dir: &Path, path: &Path) -> PathBuf {
    if path.starts_with("~") {
        expand_home(path)
    } else if path.is_relative() {
        dir.join(path)
    } else {
        path.to_path_buf()
    }
}

fn expand_home(path: &Path) -> PathBuf {
    match (path.strip_prefix("~"), directories::BaseDirs::new()) {
        (Ok(rest), Some(dirs)) => dirs.home_dir().join(rest),
        _ => path.to_path_buf(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_a_full_config() {
        let c = Config::parse(
            r#"
            tick_seconds = 3
            [filter]
            allow = ["spotify"]
            [[backend]]
            name = "finaltrack"
            url = "https://finaltrack.neiam.org"
            token = " abc \n"
            "#,
        )
        .unwrap();
        assert_eq!(c.tick_seconds, 3);
        assert_eq!(c.backends[0].token().unwrap(), "abc");
        assert!(c.filter().allows("spotify"));
        assert!(!c.filter().allows("strawberry"));
    }

    #[test]
    fn the_example_config_is_valid() {
        let c = Config::parse(EXAMPLE).unwrap();
        assert_eq!(c.backends[0].name, "finaltrack");
        assert!(!c.filter().allows("firefox"));
    }

    #[test]
    fn init_writes_once_and_puts_a_private_token_file_beside_it() {
        use std::os::unix::fs::PermissionsExt;

        let dir = std::env::temp_dir().join(format!("scropple-init-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let path = dir.join("cfg/config.toml");

        let done = init(&path, false).unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), EXAMPLE);
        let token = dir.join("cfg/finaltrack.token");
        assert_eq!(done.created_tokens, std::slice::from_ref(&token));
        assert_eq!(
            std::fs::metadata(&token).unwrap().permissions().mode() & 0o777,
            0o600
        );

        // Not twice, unless forced; a token written meanwhile survives, and
        // loading the config finds it.
        assert!(init(&path, false).is_err());
        std::fs::write(&token, "secret\n").unwrap();
        assert!(init(&path, true).unwrap().created_tokens.is_empty());
        assert_eq!(
            Config::load(&path).unwrap().backends[0].token().unwrap(),
            "secret"
        );

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn listenbrainz_and_lastfm() {
        let c = Config::parse(
            r#"
            [[backend]]
            name = "lb"
            type = "listenbrainz"
            token = "t"
            [[backend]]
            name = "fm"
            type = "lastfm"
            token = ""
            api_key = "k"
            api_secret = "s"
            "#,
        )
        .unwrap();
        assert_eq!(c.backends[0].kind, Kind::Listenbrainz);
        assert_eq!(c.backends[0].endpoint(), "https://api.listenbrainz.org");
        assert_eq!(c.backends[1].kind, Kind::Lastfm);
        assert_eq!(
            c.backends[1].lastfm_credentials().unwrap(),
            ("k".to_string(), "s".to_string())
        );
        // A scropple backend is the default type.
        let c = Config::parse("[[backend]]\nname='a'\nurl='u'\ntoken='t'").unwrap();
        assert_eq!(c.backends[0].kind, Kind::Scropple);

        // Without credentials built in, Last.fm needs them in the config.
        if crate::backend::lastfm::BUILTIN_API_KEY.is_none() {
            assert!(Config::parse("[[backend]]\nname='fm'\ntype='lastfm'\ntoken=''").is_err());
        }
    }

    #[test]
    fn private_files_are_0600_even_when_they_existed() {
        use std::os::unix::fs::PermissionsExt;
        let path = std::env::temp_dir().join(format!("scropple-private-{}", std::process::id()));
        std::fs::write(&path, "old").unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
        write_private(&path, "new").unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "new");
        assert_eq!(
            std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o600
        );
        std::fs::remove_file(&path).unwrap();
    }

    #[test]
    fn token_paths_resolve_against_the_config() {
        let dir = Path::new("/etc/scropple");
        assert_eq!(
            resolve(dir, Path::new("t.token")),
            Path::new("/etc/scropple/t.token")
        );
        assert_eq!(
            resolve(dir, Path::new("sub/t.token")),
            Path::new("/etc/scropple/sub/t.token")
        );
        assert_eq!(
            resolve(dir, Path::new("/abs/t.token")),
            Path::new("/abs/t.token")
        );
        assert!(!resolve(dir, Path::new("~/t.token")).starts_with("~"));
        assert!(resolve(dir, Path::new("~/t.token")).ends_with("t.token"));
    }

    #[test]
    fn defaults_and_mistakes() {
        let c = Config::parse("").unwrap();
        assert_eq!(c.tick_seconds, 5);
        assert!(c.backends.is_empty());
        assert!(!c.filter().allows("firefox"));

        let two_tokens = "[[backend]]\nname='a'\nurl='u'\ntoken='t'\ntoken_file='f'";
        assert!(Config::parse(two_tokens).is_err());
        let none = "[[backend]]\nname='a'\nurl='u'";
        assert!(Config::parse(none).is_err());
        let no_url = "[[backend]]\nname='a'\ntoken='t'";
        assert!(Config::parse(no_url).is_err());
        let key_elsewhere = "[[backend]]\nname='a'\ntype='listenbrainz'\ntoken='t'\napi_key='k'";
        assert!(Config::parse(key_elsewhere).is_err());
        assert!(Config::parse("[[backend]]\nname='a'\ntype='libre'\ntoken='t'").is_err());
        let dup =
            "[[backend]]\nname='a'\nurl='u'\ntoken='t'\n[[backend]]\nname='a'\nurl='v'\ntoken='t'";
        assert!(Config::parse(dup).is_err());
        assert!(Config::parse("typo = 1").is_err());
    }
}