diff --git a/Cargo.toml b/Cargo.toml index 3ae8c68..b48cf9a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,8 @@ chrono = { version = "0.4", features = ["serde"] } comrak = { version = "0.27", features = ["syntect"] } minijinja = { version = "2.1", features = ["loader"] } password-auth = "1.0.0" +rand = "0.8" +regex = "1.10" serde = { version = "1.0", features = ["derive"] } sqlx = { version = "0.8", features = [ "runtime-tokio", diff --git a/src/handlers.rs b/src/handlers.rs index 1cdb7dc..33323e1 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -10,6 +10,8 @@ use axum::{ use axum_login::AuthSession; use chrono::Datelike; use minijinja::context; +use rand::{thread_rng, Rng}; +use regex::Regex; use serde::Deserialize; use tracing::error; @@ -71,6 +73,19 @@ pub async fn handler_article( .split(',') .map(|s| s.trim().to_string()) .collect::>(), + image => { + // find all image URLs in the article markdown content and choose one randomly. + let re = Regex::new(r"\!\[.*?\]\((.*?)\)").unwrap(); + let mut image_urls: Vec = vec![]; + for (_, [image_url]) in re.captures_iter(&article.content).map(|c| c.extract()) { + image_urls.push(image_url.to_string()); + } + if image_urls.is_empty() { + None + } else { + Some(image_urls[thread_rng().gen_range(0..image_urls.len())].clone()) + } + }, logged_in => auth_session.user.is_some(), }, ) diff --git a/src/models/articles.rs b/src/models/articles.rs index a6a90bb..6523d7a 100644 --- a/src/models/articles.rs +++ b/src/models/articles.rs @@ -7,7 +7,7 @@ use tracing::info; pub struct Article { pub id: i32, title: String, - content: String, + pub content: String, pub tags: String, pub created_at: NaiveDateTime, updated_at: NaiveDateTime, diff --git a/templates/article.html b/templates/article.html index 9d42961..0f4f0ba 100755 --- a/templates/article.html +++ b/templates/article.html @@ -4,12 +4,15 @@ {% block head %} + + {% if config.twitter_card.enabled %} + {% endif %} {% endblock %}