engawa-chat 0.4.0

A peer-to-peer chat lobby for editors and browsers
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, ensure};
use serde::{Deserialize, Deserializer, Serialize};
use teravars::{Engine, discover_config_files, load_merged, system_context};

use crate::protocol::Room;
use crate::scope::Scope;

#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Veranda {
    name: String,
    key: String,
}

impl Veranda {
    fn validate_name(name: &str) -> Result<()> {
        ensure!(
            crate::scope::valid_veranda_name(name),
            "veranda name must be 1–96 UTF-8 bytes without control characters, template tags or surrounding whitespace"
        );
        Ok(())
    }

    pub(crate) fn into_scope(self) -> Result<(Scope, String)> {
        Self::validate_name(&self.name)?;
        Ok((Scope::from_key_hex(&self.key)?, self.name))
    }

    pub(crate) fn generate(name: String) -> Result<String> {
        Self::validate_name(&name)?;
        let mut key = [0u8; 32];
        getrandom::fill(&mut key)?;
        #[derive(Serialize)]
        struct Snippet {
            veranda: Veranda,
        }
        Ok(toml::to_string(&Snippet {
            veranda: Veranda {
                name,
                key: hex::encode(key),
            },
        })?)
    }
}

#[derive(Deserialize)]
#[serde(default, deny_unknown_fields)]
pub(crate) struct Config {
    pub auto_update: bool,
    pub data_dir: Option<PathBuf>,
    pub invite_base: String,
    pub veranda: Option<Veranda>,
    #[serde(deserialize_with = "favorites")]
    pub favorites: Vec<Room>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            auto_update: true,
            data_dir: None,
            invite_base: "https://yukimemi.github.io/engawa/".into(),
            veranda: None,
            favorites: Vec::new(),
        }
    }
}

fn favorites<'de, D: Deserializer<'de>>(input: D) -> Result<Vec<Room>, D::Error> {
    #[derive(Deserialize)]
    #[serde(deny_unknown_fields)]
    struct Favorite {
        name: String,
        history: bool,
    }

    Vec::<Favorite>::deserialize(input)?
        .into_iter()
        .map(|f| Room::new(&f.name, f.history).map_err(serde::de::Error::custom))
        .collect()
}

impl Config {
    pub(crate) fn load(explicit: Option<&Path>) -> Result<Self> {
        if let Some(path) = explicit {
            let path = std::path::absolute(path)?;
            if path.is_dir() {
                return Self::directory(&path);
            }
            return Self::read(
                path.parent().context("invalid config path")?,
                std::slice::from_ref(&path),
            );
        }
        let root = std::env::var_os("XDG_CONFIG_HOME")
            .map(PathBuf::from)
            .filter(|dir| dir.is_absolute())
            .or_else(dirs::config_dir);
        if let Some(dir) = root.map(|dir| dir.join("engawa"))
            && dir
                .try_exists()
                .with_context(|| format!("checking {}", dir.display()))?
        {
            return Self::directory(&dir);
        }
        Ok(Self::default())
    }

    fn directory(dir: &Path) -> Result<Self> {
        Self::read(dir, &discover_config_files(dir)?)
    }

    fn read(base: &Path, files: &[PathBuf]) -> Result<Self> {
        if files.is_empty() {
            return Ok(Self::default());
        }
        // Parser and template diagnostics can quote the line containing a bearer key.
        let mut table = load_merged(files, &mut Engine::default(), &system_context())
            .map_err(|_| {
                anyhow::anyhow!(
                    "could not load Engawa config in {} (check TOML, includes and templates)",
                    base.display()
                )
            })?
            .config;
        table.remove("vars");
        let mut cfg: Self = toml::Value::Table(table).try_into().map_err(|_| {
            anyhow::anyhow!(
                "invalid Engawa configuration fields or values in {}",
                base.display()
            )
        })?;
        if let Some(dir) = &mut cfg.data_dir {
            ensure!(
                !dir.as_os_str().is_empty(),
                "configured data_dir cannot be empty"
            );
            if dir.is_relative() {
                *dir = base.join(&*dir);
            }
        }
        Ok(cfg)
    }
}

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

    #[test]
    fn includes_templates_and_overlays_use_consistent_room_identity() -> Result<()> {
        let tmp = tempfile::tempdir()?;
        let dir = tmp.path();
        std::fs::write(dir.join("common.toml"), "[vars]\nroom = '縁側'\n")?;
        std::fs::write(
            dir.join("config.toml"),
            "include = ['common.toml']\ndata_dir = 'old'\n[[favorites]]\nname = '{{ vars.room }}'\nhistory = true\n",
        )?;
        std::fs::write(
            dir.join("config.local.toml"),
            "data_dir = 'local'\nauto_update = false\n",
        )?;
        let cfg = Config::load(Some(dir))?;
        assert_eq!(cfg.data_dir.unwrap(), dir.join("local"));
        assert!(!cfg.auto_update);
        assert_eq!(cfg.favorites[0].id, Room::new("縁側", true)?.id);
        let base = Config::load(Some(&dir.join("config.toml")))?;
        assert_eq!(base.data_dir.unwrap(), dir.join("old"));
        assert!(base.auto_update);
        Ok(())
    }
}