use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, LazyLock, Mutex, PoisonError};
use laravel::time::Timestamp;
use regex::{Captures, Regex};
use serde::Serialize;
use serde_json::Value;
use crate::conditionals;
use crate::config::{CollectionConfig, LarablogConfig};
use crate::index::{IndexData, IndexError, Source};
use crate::markdown::{Markdown, Rendered};
use crate::routes::{self, Kind};
use crate::{Author, Category, Error, Post, support};
static POST_LINK: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"(?s)<a\b([^>]*?)\shref="post:([A-Za-z0-9_.-]+)([#?][^"]*)?"([^>]*)>(.*?)</a>"#)
.expect("a valid pattern")
});
static LINKED: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"\]\(post:([A-Za-z0-9_.-]+)|href="post:([A-Za-z0-9_.-]+)"#).expect("a valid pattern")
});
pub(crate) struct Shared {
pub(crate) markdown: Markdown,
indexes: Mutex<HashMap<String, Entry>>,
}
struct Entry {
signature: String,
checked_at: i64,
index: Arc<IndexData>,
}
impl Shared {
pub(crate) fn new() -> Self {
Self {
markdown: Markdown::new(),
indexes: Mutex::new(HashMap::new()),
}
}
}
tokio::task_local! {
static SCOPE: Scope;
}
#[derive(Default)]
struct Scope {
indexes: Mutex<HashMap<String, Arc<IndexData>>>,
url: Option<String>,
}
pub async fn scoped<F: std::future::Future>(url: Option<String>, future: F) -> F::Output {
SCOPE
.scope(
Scope {
indexes: Mutex::new(HashMap::new()),
url,
},
future,
)
.await
}
pub fn flush() {
let _ = SCOPE.try_with(|scope| scope.indexes.lock().unwrap_or_else(PoisonError::into_inner).clear());
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Tag {
pub slug: String,
pub name: String,
pub count: usize,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Pagination<T> {
pub items: Vec<T>,
pub current_page: usize,
pub last_page: usize,
pub per_page: usize,
pub total: usize,
pub prev_page_url: Option<String>,
pub next_page_url: Option<String>,
}
impl<T> Pagination<T> {
pub fn has_pages(&self) -> bool {
self.last_page > 1
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SitemapEntry {
pub loc: String,
pub lastmod: Option<String>,
pub alternates: Vec<(String, String)>,
}
#[derive(Clone)]
pub struct Blog {
name: String,
shared: Arc<Shared>,
}
impl std::fmt::Debug for Blog {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_struct("Blog").field("name", &self.name).finish()
}
}
impl Blog {
pub(crate) fn new(name: &str, shared: Arc<Shared>) -> Self {
Self {
name: name.to_owned(),
shared,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn settings(&self) -> CollectionConfig {
laravel::config()
.section::<LarablogConfig>()
.collections
.get(&self.name)
.cloned()
.unwrap_or_default()
}
pub fn locales(&self) -> Vec<String> {
let supported = laravel::config()
.get::<laralocale::LocaleConfig>()
.map(|config| config.supported.clone())
.unwrap_or_default();
support::resolve_locales(self.settings().locales.as_deref(), &supported, &app_locale())
}
pub fn posts(&self, locale: Option<&str>) -> Vec<Post> {
let locale = locale_or_current(locale);
self.index()
.posts
.iter()
.filter(|post| post.locale == locale && post.is_published())
.cloned()
.collect()
}
pub fn all(&self) -> Vec<Post> {
self.index().posts.clone()
}
pub fn find(&self, slug: &str, locale: Option<&str>) -> Option<Post> {
let locale = locale_or_current(locale);
let index = self.index();
let position = index.lookup.get(&locale)?.get(slug)?;
Self::published_at(&index, *position)
}
pub fn find_in_any_locale(&self, slug: &str) -> Option<Post> {
let index = self.index();
let mut positions: Vec<usize> = index
.lookup
.values()
.filter_map(|slugs| slugs.get(slug).copied())
.collect();
positions.sort_unstable();
positions
.into_iter()
.find_map(|position| Self::published_at(&index, position))
}
pub fn translations_of(&self, post: &Post, include_self: bool) -> Vec<(String, Post)> {
let index = self.index();
let mut found: Vec<(String, Post)> = Vec::new();
for locale in self.locales() {
if !include_self && locale == post.locale {
continue;
}
for candidate in &index.posts {
if candidate.id == post.id && candidate.locale == locale && candidate.is_published() {
found.retain(|(existing, _)| *existing != locale);
found.push((locale.clone(), candidate.clone()));
}
}
}
found
}
pub fn link_to(&self, id: &str, locale: &str) -> Option<String> {
let index = self.index();
let positions = index.positions.get(id)?;
std::iter::once(locale.to_owned())
.chain(self.locales())
.find_map(|wanted| {
positions
.get(&wanted)
.and_then(|position| Self::published_at(&index, *position))
})
.map(|post| post.url())
}
pub fn resolve_links(&self, html: &str, locale: &str) -> String {
let html = conditionals::resolve(html, |id| self.link_to(id, locale).is_some());
if !html.contains("href=\"post:") {
return html;
}
POST_LINK
.replace_all(&html, |found: &Captures<'_>| {
let attributes = &found[1];
let id = &found[2];
let rest = found.get(3).map_or("", |m| m.as_str());
let after = &found[4];
let text = &found[5];
if let Some(url) = self.link_to(id, locale) {
return format!("<a{attributes} href=\"{}{rest}\"{after}>{text}</a>", escape(&url));
}
if self.exists(id) {
text.to_owned()
} else {
format!("<a{attributes} href=\"#\"{after}>{text}</a>")
}
})
.into_owned()
}
pub fn broken_links(&self, post: &Post) -> Vec<String> {
self.linked_ids(post)
.into_iter()
.filter(|id| self.link_to(id, &post.locale).is_none() && !self.exists(id))
.collect()
}
pub fn pending_links(&self, post: &Post) -> Vec<(String, Option<Timestamp>)> {
let index = self.index();
let mut pending = Vec::new();
for id in self.linked_ids(post) {
if self.link_to(&id, &post.locale).is_some() || !self.exists(&id) {
continue;
}
let date = index
.posts
.iter()
.filter(|candidate| candidate.id == id && !candidate.draft)
.map(|candidate| candidate.date)
.min();
pending.push((id, date));
}
pending
}
fn exists(&self, id: &str) -> bool {
self.index().positions.contains_key(id)
}
fn linked_ids(&self, post: &Post) -> Vec<String> {
let content = std::fs::read_to_string(&post.file).unwrap_or_default();
let mut ids: Vec<String> = Vec::new();
for found in LINKED.captures_iter(&content) {
if let Some(id) = found.get(1).or_else(|| found.get(2)) {
ids.push(id.as_str().to_owned());
}
}
ids.extend(post.conditions().into_iter().map(|condition| condition.post));
let mut unique: Vec<String> = Vec::new();
for id in ids {
if !id.is_empty() && !unique.contains(&id) {
unique.push(id);
}
}
unique
}
pub fn category(&self, key: &str, locale: Option<&str>) -> Option<Category> {
let locale = locale_or_current(locale);
let fallback = fallback_locale();
let index = self.index();
let definition = index.category(key)?;
let name = match definition {
Value::Object(map) => support::localized(Some(map.get("name").unwrap_or(definition)), &locale, &fallback)
.unwrap_or_else(|| support::headline(key)),
other => support::scalar_text(other).unwrap_or_default(),
};
let explicit_slug = match definition {
Value::Object(map) => map
.get("slug")
.map(|slug| support::localized(Some(slug), &locale, &fallback).unwrap_or_default()),
_ => None,
};
let slug = explicit_slug.unwrap_or_else(|| support::slug(&name));
let slug = if slug.is_empty() { support::slug(key) } else { slug };
let (description, color, meta) = match definition {
Value::Object(map) => (
support::localized(map.get("description"), &locale, &fallback),
map.get("color").and_then(support::scalar_text),
map.iter()
.filter(|(field, _)| !["name", "slug", "description", "color"].contains(&field.as_str()))
.map(|(field, value)| (field.clone(), value.clone()))
.collect(),
),
_ => (None, None, serde_json::Map::new()),
};
Some(Category {
collection: self.name.clone(),
key: key.to_owned(),
locale,
name,
slug,
description,
color,
meta,
})
}
pub fn categories(&self, locale: Option<&str>) -> Vec<Category> {
let locale = locale_or_current(locale);
let used: Vec<String> = self
.posts(Some(&locale))
.into_iter()
.filter_map(|post| post.category)
.collect();
self.index()
.categories
.iter()
.filter(|(key, _)| used.contains(key))
.filter_map(|(key, _)| self.category(key, Some(&locale)))
.collect()
}
pub fn category_by_slug(&self, slug: &str, locale: Option<&str>) -> Option<Category> {
let locale = locale_or_current(locale);
self.index()
.categories
.iter()
.filter_map(|(key, _)| self.category(key, Some(&locale)))
.find(|category| category.slug == slug)
}
pub fn in_category(&self, category: &Category) -> Vec<Post> {
self.posts(Some(&category.locale))
.into_iter()
.filter(|post| post.category.as_deref() == Some(category.key.as_str()))
.collect()
}
pub fn tags(&self, locale: Option<&str>) -> Vec<Tag> {
let mut tags: Vec<Tag> = Vec::new();
for post in self.posts(locale) {
for tag in &post.tags {
let slug = support::slug(tag);
match tags.iter_mut().find(|existing| existing.slug == slug) {
Some(existing) => existing.count += 1,
None => tags.push(Tag {
slug,
name: tag.clone(),
count: 1,
}),
}
}
}
tags.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.name.cmp(&b.name)));
tags
}
pub fn with_tag(&self, slug: &str, locale: Option<&str>) -> Vec<Post> {
self.posts(locale)
.into_iter()
.filter(|post| post.tags.iter().any(|tag| support::slug(tag) == slug))
.collect()
}
pub fn author(&self, key: &str, locale: Option<&str>) -> Author {
let locale = locale_or_current(locale);
let fallback = fallback_locale();
let index = self.index();
match index.author(key) {
None => Author::named(key, key),
Some(Value::Object(map)) => Author {
key: key.to_owned(),
name: map
.get("name")
.and_then(support::scalar_text)
.unwrap_or_else(|| key.to_owned()),
role: support::localized(map.get("role"), &locale, &fallback),
bio: support::localized(map.get("bio"), &locale, &fallback),
avatar: map.get("avatar").and_then(support::scalar_text),
links: match map.get("links") {
Some(Value::Object(links)) => links
.iter()
.filter_map(|(name, url)| Some((name.clone(), support::scalar_text(url)?)))
.collect::<BTreeMap<_, _>>(),
_ => BTreeMap::new(),
},
},
Some(other) => Author::named(key, support::scalar_text(other).unwrap_or_default()),
}
}
pub fn related(&self, post: &Post, limit: usize) -> Vec<Post> {
let mut scored: Vec<(usize, Post)> = Vec::new();
for candidate in self.posts(Some(&post.locale)) {
if candidate.id == post.id {
continue;
}
let score = if post.category.is_some() && candidate.category == post.category {
3
} else {
0
} + post.tags.iter().filter(|tag| candidate.tags.contains(tag)).count();
if score > 0 {
scored.push((score, candidate));
}
}
scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| b.1.date.cmp(&a.1.date)));
scored.into_iter().map(|(_, post)| post).take(limit).collect()
}
pub fn paginate(&self, posts: Vec<Post>, page: Option<usize>) -> Pagination<Post> {
let per_page = self.settings().per_page.max(1);
let page = page
.unwrap_or_else(|| usize::try_from(laravel::pagination::current_page()).unwrap_or(1))
.max(1);
let total = posts.len();
let last_page = total.div_ceil(per_page).max(1);
let base = current_url();
let link = |page: usize| format!("{base}?page={page}");
Pagination {
items: posts.into_iter().skip((page - 1) * per_page).take(per_page).collect(),
current_page: page,
last_page,
per_page,
total,
prev_page_url: (page > 1).then(|| link(page - 1)),
next_page_url: (page < last_page).then(|| link(page + 1)),
}
}
pub fn url(&self, kind: &str, locale: Option<&str>, parameters: &[(&str, &str)], absolute: bool) -> String {
let Some(kind) = Kind::parse(kind) else {
return "#".to_owned();
};
let locale = locale_or_current(locale);
let uri = routes::uri(
&self.name,
kind,
&locale,
&self.settings(),
&self.locales(),
&app_locale(),
);
let path = routes::fill(&uri, parameters);
if !absolute {
return path;
}
let base = laravel::url::to("/");
format!("{}{}", base.trim_end_matches('/'), if path == "/" { "" } else { &path })
}
pub fn index_alternates(&self) -> Vec<(String, String)> {
self.locales()
.into_iter()
.map(|locale| {
let url = self.url("index", Some(&locale), &[], true);
(locale, url)
})
.collect()
}
pub fn category_alternates(&self, category: &Category) -> Vec<(String, String)> {
self.locales()
.into_iter()
.filter_map(|locale| {
let translated = self.category(&category.key, Some(&locale))?;
(!self.in_category(&translated).is_empty()).then(|| (locale, translated.url()))
})
.collect()
}
pub fn sitemap(&self) -> Vec<SitemapEntry> {
let index = self.index_alternates();
let mut entries: Vec<SitemapEntry> = index
.iter()
.map(|(_, url)| SitemapEntry {
loc: url.clone(),
lastmod: None,
alternates: index.clone(),
})
.collect();
for locale in self.locales() {
for post in self.posts(Some(&locale)) {
entries.push(SitemapEntry {
loc: post.url(),
lastmod: Some(support::atom(post.updated.unwrap_or(post.date))),
alternates: post.alternates(),
});
}
}
entries
}
pub fn errors(&self) -> Vec<IndexError> {
self.index().errors.clone()
}
pub fn rebuild_index(&self) -> Result<usize, Error> {
let index = self.load(true);
Ok(index.posts.len())
}
pub fn route_name(collection: &str, kind: &str, locale: &str) -> String {
routes::route_name(collection, kind, locale)
}
pub(crate) fn rendered(&self, post: &Post) -> Arc<Rendered> {
let caching = laravel::config().section::<LarablogConfig>().cache.enabled;
self.shared
.markdown
.render(&post.file, caching)
.unwrap_or_else(|error| {
tracing::warn!(file = %post.file.display(), %error, "A post could not be rendered");
Arc::new(Rendered {
html: String::new(),
headings: Vec::new(),
})
})
}
fn published_at(index: &IndexData, position: usize) -> Option<Post> {
let post = index.posts.get(position)?;
(post.is_published() && post.file.is_file()).then(|| post.clone())
}
fn source(&self) -> Source {
let settings = laravel::config();
let app = &settings.app;
let path = std::path::Path::new(
settings
.section::<LarablogConfig>()
.collections
.get(&self.name)
.map_or("", |c| c.path.as_str()),
);
let path = if path.is_absolute() {
path.to_path_buf()
} else {
app.base_path.join(path)
};
Source {
name: self.name.clone(),
path,
locales: self.locales(),
words_per_minute: settings.section::<LarablogConfig>().words_per_minute,
}
}
fn index(&self) -> Arc<IndexData> {
let source = self.source();
let key = source.key();
if let Ok(Some(index)) = SCOPE.try_with(|scope| {
scope
.indexes
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(&key)
.cloned()
}) {
return index;
}
let index = self.load_from(&source, false);
remember(&key, &index);
index
}
fn load(&self, force: bool) -> Arc<IndexData> {
let source = self.source();
let index = self.load_from(&source, force);
remember(&source.key(), &index);
index
}
fn load_from(&self, source: &Source, force: bool) -> Arc<IndexData> {
let config = laravel::config();
let settings = config.section::<LarablogConfig>();
if !settings.cache.enabled {
return Arc::new(source.build());
}
let interval = settings
.cache
.check_interval
.unwrap_or(if config.app.env.is_production() { 60 } else { 0 });
let now = laravel::now().timestamp().as_second();
let key = source.key();
let mut indexes = self.shared.indexes.lock().unwrap_or_else(PoisonError::into_inner);
let entry = indexes.get(&key);
if !force
&& let Some(entry) = entry
&& u64::try_from(now - entry.checked_at).is_ok_and(|elapsed| elapsed < interval)
{
return Arc::clone(&entry.index);
}
let signature = source.signature();
let index = match entry {
Some(entry) if !force && entry.signature == signature => Arc::clone(&entry.index),
_ => Arc::new(source.build()),
};
indexes.insert(
key,
Entry {
signature,
checked_at: now,
index: Arc::clone(&index),
},
);
index
}
}
fn escape(text: &str) -> String {
text.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
fn app_locale() -> String {
laravel::config()
.get::<laralocale::LocaleConfig>()
.map_or_else(|| "en".to_owned(), |config| config.locale.clone())
}
fn fallback_locale() -> String {
laralocale::fallback_locale()
}
fn locale_or_current(locale: Option<&str>) -> String {
locale.map_or_else(laralocale::locale, str::to_owned)
}
fn current_url() -> String {
SCOPE
.try_with(|scope| scope.url.clone())
.ok()
.flatten()
.unwrap_or_else(|| laravel::url::to("/").trim_end_matches('/').to_owned())
}
fn remember(key: &str, index: &Arc<IndexData>) {
let _ = SCOPE.try_with(|scope| {
scope
.indexes
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(key.to_owned(), Arc::clone(index));
});
}