use std::{
borrow::Cow,
collections::HashMap,
fs,
path::Path,
sync::{Arc, Mutex, PoisonError},
};
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
use comrak::nodes::{Node, NodeCode, NodeValue};
use yaml_rust2::YamlLoader;
use crate::{ConvertOptions, HighlightLanguages, resources::HIGHLIGHT_LANGUAGES};
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct UsedAssets {
pub(crate) highlight: bool,
pub(crate) math: bool,
pub(crate) mermaid: bool,
}
pub(crate) fn build_comrak_options(options: &ConvertOptions) -> comrak::Options<'static> {
let mut comrak_options = comrak::Options::default();
comrak_options.render.r#unsafe = options.allow_unsafe;
comrak_options.render.hardbreaks = options.hardbreaks;
comrak_options.render.gfm_quirks = true;
comrak_options.render.tasklist_classes = true;
comrak_options.extension.alerts = true;
comrak_options.extension.autolink = true;
comrak_options.extension.cjk_friendly_emphasis = true;
comrak_options.extension.description_lists = true;
comrak_options.extension.footnotes = true;
comrak_options.extension.front_matter_delimiter = Some(String::from("---"));
comrak_options.extension.header_id_prefix = Some(String::new());
comrak_options.extension.multiline_block_quotes = true;
comrak_options.extension.strikethrough = true;
comrak_options.extension.subscript = true;
comrak_options.extension.superscript = true;
comrak_options.extension.table = true;
comrak_options.extension.tagfilter = true;
comrak_options.extension.tasklist = true;
comrak_options.parse.relaxed_tasklist_matching = true;
if options.math.is_some() {
comrak_options.extension.math_code = true;
comrak_options.extension.math_dollars = true;
comrak_options.extension.math_latex = true;
}
if options.embed_images {
let base_path = match options.base_path {
Some(path) if !path.as_os_str().is_empty() => path,
_ => Path::new("."),
};
let real_base_path = fs::canonicalize(base_path).ok();
let base_path = base_path.to_path_buf();
let embedded: Mutex<HashMap<String, String>> = Mutex::new(HashMap::new());
comrak_options.extension.image_url_rewriter = Some(Arc::new(move |url: &str| {
let mut embedded = embedded.lock().unwrap_or_else(PoisonError::into_inner);
embedded
.entry(url.to_string())
.or_insert_with(|| {
real_base_path
.as_deref()
.and_then(|real_base_path| {
embed_image(base_path.as_path(), real_base_path, url)
})
.unwrap_or_else(|| url.to_string())
})
.clone()
}));
}
comrak_options
}
pub(crate) fn document_title(root: Node) -> Option<String> {
for node in root.children() {
match node.data.borrow().value {
NodeValue::FrontMatter(ref front_matter) => {
if let Some(title) = front_matter_title(front_matter) {
return Some(title);
}
},
NodeValue::Heading(heading) if heading.level == 1 => {
let title = node_text(node);
if !title.is_empty() {
return Some(title);
}
},
_ => (),
}
}
None
}
pub(crate) fn used_assets(root: Node, options: &ConvertOptions) -> UsedAssets {
let wants_mermaid = options.mermaid.is_some();
let mut used_assets = UsedAssets::default();
for node in root.descendants() {
match node.data.borrow().value {
NodeValue::CodeBlock(ref code_block) => {
let lang = code_block.info.split_whitespace().next().unwrap_or("");
if lang == "math" {
used_assets.math = true;
} else if wants_mermaid && lang == "mermaid" {
used_assets.mermaid = true;
} else if is_highlighted(options.highlight_languages, lang) {
used_assets.highlight = true;
}
},
NodeValue::Math(..) => used_assets.math = true,
_ => (),
}
if used_assets.highlight && used_assets.math && (used_assets.mermaid || !wants_mermaid) {
break;
}
}
used_assets
}
fn is_highlighted(languages: HighlightLanguages, lang: &str) -> bool {
if lang.is_empty() {
return false;
}
match languages {
HighlightLanguages::BuiltIn => HIGHLIGHT_LANGUAGES
.lines()
.filter(|line| !line.starts_with('#'))
.any(|name| name.eq_ignore_ascii_case(lang)),
HighlightLanguages::Any => true,
HighlightLanguages::Only(languages) => {
languages.iter().any(|name| name.eq_ignore_ascii_case(lang))
},
}
}
fn front_matter_title(front_matter: &str) -> Option<String> {
let documents = YamlLoader::load_from_str(front_matter).ok()?;
let title = documents.first()?["title"].as_str()?.trim();
(!title.is_empty()).then(|| title.to_string())
}
fn node_text(node: Node) -> String {
let mut text = String::new();
for descendant in node.descendants() {
match descendant.data.borrow().value {
NodeValue::Text(ref literal) => text.push_str(literal),
NodeValue::Code(NodeCode {
ref literal, ..
}) => text.push_str(literal),
NodeValue::LineBreak | NodeValue::SoftBreak => text.push(' '),
_ => (),
}
}
text.trim().to_string()
}
fn embed_image(base_path: &Path, real_base_path: &Path, url: &str) -> Option<String> {
if url.is_empty() || url.starts_with(['#', '/', '\\']) || has_scheme(url) {
return None;
}
let (path_url, fragment) =
url.split_once('#').map_or((url, None), |(path, fragment)| (path, Some(fragment)));
let path_url = path_url.split_once('?').map_or(path_url, |(path, _)| path);
let relative_path = percent_decode(path_url);
let relative_path = Path::new(relative_path.as_ref());
if relative_path.is_absolute() {
return None;
}
let mime = image_mime(relative_path.extension()?.to_str()?)?;
let path = fs::canonicalize(base_path.join(relative_path)).ok()?;
if !path.starts_with(real_base_path) {
return None;
}
let image = fs::read(path).ok()?;
let mut data_url = String::with_capacity(
mime.len()
+ 13
+ image.len().div_ceil(3) * 4
+ fragment.map_or(0, |fragment| fragment.len() + 1),
);
data_url.push_str("data:");
data_url.push_str(mime);
data_url.push_str(";base64,");
BASE64.encode_string(image, &mut data_url);
if let Some(fragment) = fragment {
data_url.push('#');
data_url.push_str(fragment);
}
Some(data_url)
}
fn has_scheme(url: &str) -> bool {
match url.find(':') {
Some(index) => {
let scheme = &url[..index];
scheme.len() > 1
&& scheme.starts_with(|c: char| c.is_ascii_alphabetic())
&& scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
},
None => false,
}
}
fn percent_decode(url: &str) -> Cow<'_, str> {
let bytes = url.as_bytes();
let Some(start) = url.find('%') else {
return Cow::Borrowed(url);
};
let mut decoded = Vec::with_capacity(bytes.len());
let mut index = start;
decoded.extend_from_slice(&bytes[..start]);
while index < bytes.len() {
match bytes[index] {
b'%' if index + 2 < bytes.len() => {
match hex_octet(bytes[index + 1], bytes[index + 2]) {
Some(byte) => {
decoded.push(byte);
index += 3;
},
None => {
decoded.push(b'%');
index += 1;
},
}
},
byte => {
decoded.push(byte);
index += 1;
},
}
}
match String::from_utf8(decoded) {
Ok(decoded) => Cow::Owned(decoded),
Err(_) => Cow::Borrowed(url),
}
}
fn hex_octet(high: u8, low: u8) -> Option<u8> {
Some((hex_digit(high)? << 4) | hex_digit(low)?)
}
fn hex_digit(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
fn image_mime(extension: &str) -> Option<&'static str> {
const MIMES: [(&str, &str); 12] = [
("png", "image/png"),
("apng", "image/apng"),
("jpg", "image/jpeg"),
("jpeg", "image/jpeg"),
("gif", "image/gif"),
("svg", "image/svg+xml"),
("webp", "image/webp"),
("avif", "image/avif"),
("bmp", "image/bmp"),
("ico", "image/x-icon"),
("tif", "image/tiff"),
("tiff", "image/tiff"),
];
MIMES.into_iter().find(|(name, _)| extension.eq_ignore_ascii_case(name)).map(|(_, mime)| mime)
}
#[cfg(test)]
mod tests {
use std::env;
use super::*;
#[test]
fn a_url_without_percent_encoding_is_borrowed() {
assert_eq!("images/pic.png", percent_decode("images/pic.png"));
assert!(matches!(percent_decode("images/pic.png"), Cow::Borrowed(_)));
}
#[test]
fn percent_encoded_octets_are_decoded() {
assert_eq!("a b.png", percent_decode("a%20b.png"));
assert_eq!("a/b.png", percent_decode("a%2Fb.png"));
assert_eq!("圖.png", percent_decode("%E5%9C%96.png"));
}
#[test]
fn a_percent_which_is_not_an_escape_is_kept() {
assert_eq!("%圖.png", percent_decode("%圖.png"));
assert_eq!("%zz.png", percent_decode("%zz.png"));
assert_eq!("%+A.png", percent_decode("%+A.png"));
assert_eq!("100%", percent_decode("100%"));
assert_eq!("100%2", percent_decode("100%2"));
}
#[test]
fn only_real_schemes_are_detected() {
assert!(has_scheme("https://magiclen.org/pic.png"));
assert!(has_scheme("data:image/png;base64,AAAA"));
assert!(has_scheme("mailto:len@magiclen.org"));
assert!(!has_scheme("images/pic.png"));
assert!(!has_scheme("C:/images/pic.png"));
}
#[test]
fn only_relative_images_are_embedded() {
let dir = env::temp_dir().join("markdown2html-converter-unit-embed-image");
let sub_dir = dir.join("sub");
let path = dir.join("pic.png");
fs::create_dir_all(sub_dir.as_path()).unwrap();
fs::write(path.as_path(), b"an image").unwrap();
let real_dir = fs::canonicalize(dir.as_path()).unwrap();
let real_sub_dir = fs::canonicalize(sub_dir.as_path()).unwrap();
let from_dir = |url: &str| embed_image(dir.as_path(), real_dir.as_path(), url);
let from_sub_dir = |url: &str| embed_image(sub_dir.as_path(), real_sub_dir.as_path(), url);
let data_url = Some(String::from("data:image/png;base64,YW4gaW1hZ2U="));
assert_eq!(data_url, from_dir("pic.png"));
assert_eq!(data_url, from_dir("sub/../pic.png"));
assert_eq!(None, from_sub_dir("../pic.png"));
assert_eq!(None, from_dir(path.to_str().unwrap()));
assert_eq!(None, from_dir("https://magiclen.org/pic.png"));
assert_eq!(None, from_dir("//magiclen.org/pic.png"));
assert_eq!(None, from_dir("#anchor"));
}
}