9.5 KiB · text History 6c56e6c
//! `~/.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 = "..."
//! ```

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>>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BackendConfig {
    pub name: String,
    /// The server's base URL: `/api/v1/scrobble` and `/api/v1/now-playing`
    /// are under it.
    pub url: String,
    pub token: Option<String>,
    pub token_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));
            }
        }
        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
                );
            }
        }
        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 bearer token: inline, or the trimmed contents of `token_file`
    /// (`~` expanded).
    pub fn token(&self) -> Result<String> {
        match (&self.token, &self.token_file) {
            (Some(t), _) => Ok(t.trim().to_string()),
            (None, Some(path)) => {
                let t = std::fs::read_to_string(path).with_context(|| {
                    format!("backend {:?}: reading {}", self.name, path.display())
                })?;
                Ok(t.trim().to_string())
            }
            (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,
    })
}

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 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 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());
    }
}