larablog 0.1.0

Markdown blogs for Laravel Rust in several languages, where every language has its own URL.
Documentation
//! `config/larablog.php`, as a configuration section.
//!
//! The keys and the defaults are the PHP package's, in snake_case. Where PHP takes either a string
//! or an array per language, [`Localized`] takes either. The two settings that read the
//! environment in PHP read it here too: `LARABLOG_SHOW_SCHEDULED`, `LARABLOG_SHOW_DRAFTS`,
//! `LARABLOG_CACHE` and `LARABLOG_CACHE_CHECK_INTERVAL`.

use std::collections::BTreeMap;

use laravel::config::{Env, Section};

/// A value written once for every language, or one per language.
#[derive(Debug, Clone, PartialEq)]
pub enum Localized {
    /// The same text in every language.
    One(String),
    /// A text per language code.
    Per(BTreeMap<String, String>),
}

impl Localized {
    /// The text for a language: its own, else the first one written.
    pub fn for_locale(&self, locale: &str) -> Option<&str> {
        let text = match self {
            Self::One(text) => text.as_str(),
            Self::Per(texts) => texts.get(locale).or_else(|| texts.values().next())?.as_str(),
        };

        (!text.is_empty()).then_some(text)
    }
}

impl From<&str> for Localized {
    fn from(text: &str) -> Self {
        Self::One(text.to_owned())
    }
}

/// The words in category and tag URLs, per language.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Segments {
    /// `category` => the word of each language.
    pub category: BTreeMap<String, String>,
    /// `tag` => the word of each language.
    pub tag: BTreeMap<String, String>,
}

impl Default for Segments {
    fn default() -> Self {
        Self {
            category: pairs([("en", "category"), ("es", "categoria")]),
            tag: pairs([("en", "tag"), ("es", "etiqueta")]),
        }
    }
}

/// The views a collection's pages are drawn with.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Views {
    /// The listing.
    pub index: String,
    /// A post.
    pub show: String,
    /// A category, which is a filtered listing.
    pub category: String,
    /// A tag, which is a filtered listing.
    pub tag: String,
}

impl Default for Views {
    fn default() -> Self {
        Self {
            index: "blog.index".to_owned(),
            show: "blog.show".to_owned(),
            category: "blog.index".to_owned(),
            tag: "blog.index".to_owned(),
        }
    }
}

/// Social cards drawn with Laracards, one per post and language.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CardSettings {
    /// Draw them at all.
    pub enabled: bool,
    /// A template configured in `LaracardsConfig`.
    pub template: String,
    /// Where they are written, under `public/`.
    pub path: String,
    /// The brand line on the card. The host of `APP_URL` when `None`.
    pub brand: Option<String>,
}

impl Default for CardSettings {
    fn default() -> Self {
        Self {
            enabled: true,
            template: "post".to_owned(),
            path: "img/blog".to_owned(),
            brand: None,
        }
    }
}

/// The RSS feed of each language, at `/{path}/feed`.
#[derive(Debug, Clone, PartialEq)]
pub struct FeedSettings {
    /// Serve it.
    pub enabled: bool,
    /// The channel title. The application name when `None`.
    pub title: Option<Localized>,
    /// The channel description. The title when `None`.
    pub description: Option<Localized>,
    /// How many posts it carries.
    pub limit: usize,
}

impl Default for FeedSettings {
    fn default() -> Self {
        Self {
            enabled: true,
            title: None,
            description: None,
            limit: 20,
        }
    }
}

/// One blog, or one set of guides, case studies or whitepapers.
#[derive(Debug, Clone, PartialEq)]
pub struct CollectionConfig {
    /// The folder with `_authors.yml`, `_categories.yml` and one folder per post. Relative paths
    /// start at the application's base path.
    pub path: String,
    /// The languages it is written in, the default first. `None` means the `supported` locales of
    /// `laralocale`, else its `locale`.
    pub locales: Option<Vec<String>>,
    /// The first segment of its URLs, per language. Empty puts it at the root.
    pub paths: BTreeMap<String, String>,
    /// The words in category and tag URLs, per language.
    pub segments: Segments,
    /// The views of its pages.
    pub views: Views,
    /// Posts per page of a listing.
    pub per_page: usize,
    /// Social cards.
    pub cards: CardSettings,
    /// The feed.
    pub feed: FeedSettings,
}

impl Default for CollectionConfig {
    fn default() -> Self {
        Self {
            path: "content/blog".to_owned(),
            locales: None,
            paths: pairs([("en", "blog"), ("es", "blog")]),
            segments: Segments::default(),
            views: Views::default(),
            per_page: 12,
            cards: CardSettings::default(),
            feed: FeedSettings::default(),
        }
    }
}

/// The index of every collection is cached and rebuilt when any of its files changes.
///
/// The cache lives in the memory of the process, which in Laravel Rust outlives the request, so
/// PHP's `store` key has nothing to point at and is not here.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CacheSettings {
    /// Cache the index and the rendered bodies. Off reads the files on every use.
    pub enabled: bool,
    /// Seconds between filesystem checks. `None` uses 60 in production and 0 elsewhere.
    pub check_interval: Option<u64>,
}

impl Default for CacheSettings {
    fn default() -> Self {
        Self {
            enabled: true,
            check_interval: None,
        }
    }
}

/// What the CommonMark converter does with HTML written in the Markdown.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HtmlInput {
    /// Keep it. The content is written by the site's owner.
    #[default]
    Allow,
    /// Drop it.
    Strip,
    /// Show it as text.
    Escape,
}

/// CommonMark.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MarkdownSettings {
    /// `Allow` unless anybody else writes posts.
    pub html_input: HtmlInput,
    /// Let `javascript:` and similar links through.
    pub allow_unsafe_links: bool,
    /// Links to other hosts open with `rel="noopener noreferrer"` and `target="_blank"`.
    pub external_links: bool,
}

impl Default for MarkdownSettings {
    fn default() -> Self {
        Self {
            html_input: HtmlInput::Allow,
            allow_unsafe_links: false,
            external_links: true,
        }
    }
}

fn pairs<const N: usize>(pairs: [(&str, &str); N]) -> BTreeMap<String, String> {
    pairs
        .into_iter()
        .map(|(key, value)| (key.to_owned(), value.to_owned()))
        .collect()
}

fn default_collections() -> BTreeMap<String, CollectionConfig> {
    BTreeMap::from([("blog".to_owned(), CollectionConfig::default())])
}

fn cache_from_env(env: &Env) -> Option<CacheSettings> {
    Some(CacheSettings {
        enabled: env.get("LARABLOG_CACHE").unwrap_or(true),
        check_interval: env.get("LARABLOG_CACHE_CHECK_INTERVAL"),
    })
}

/// The package's configuration, the equivalent of `config/larablog.php`.
#[derive(Debug, Clone, Section)]
pub struct LarablogConfig {
    /// The collections, by name. Several of them (a blog, guides, case studies) each get their own
    /// entry and their own call to [`LarablogServiceProvider::routes`](crate::LarablogServiceProvider::routes).
    #[section(default = default_collections())]
    pub collections: BTreeMap<String, CollectionConfig>,

    /// Posts dated in the future stay off every list, feed and sitemap and answer 404. Turn it on
    /// locally to preview them.
    #[env("LARABLOG_SHOW_SCHEDULED", default = false)]
    pub show_scheduled: bool,

    /// Drafts stay off every list, feed and sitemap and answer 404. Turn it on locally to preview
    /// them.
    #[env("LARABLOG_SHOW_DRAFTS", default = false)]
    pub show_drafts: bool,

    /// Words a minute, for the reading time when a post does not say it.
    #[section(default = 220)]
    pub words_per_minute: u32,

    /// The index cache.
    #[env(with = cache_from_env)]
    pub cache: CacheSettings,

    /// CommonMark.
    pub markdown: MarkdownSettings,
}