use crate::dom::{HTMLTag, NodeHandle, Parser};
use std::borrow::Cow;
use crate::converter::Context;
use crate::converter::inline::link::{MarkdownLink, append_markdown_link};
use crate::converter::main_helpers::tag_name_eq;
use crate::converter::media::MediaContext;
use crate::converter::media::first_address;
use crate::converter::utility::content::normalized_tag_name;
use crate::converter::utility::escaping::escape_link_label;
use crate::converter::utility::preprocessing::sanitize_markdown_url;
use crate::converter::walk::{CaptureEnd, Close, Open};
use crate::options::{ConversionOptions, InlineDataMedia};
fn append_media_src_link(output: &mut String, src: &str, tag: &HTMLTag, options: &ConversionOptions, ctx: &Context) {
let title = crate::converter::utility::attributes::decoded_attribute(tag, "title");
let name = normalized_tag_name(tag.name().as_utf8_str());
let label = title
.as_deref()
.filter(|label| !label.trim().is_empty())
.unwrap_or(&name);
if ctx.in_link && matches!(name.as_ref(), "audio" | "video") {
output.push_str(label);
if let Some(boundary) = ctx.media_boundary.as_ref() {
let mut state = boundary.get();
if state.first_edge.is_none() {
state.first_edge = label.chars().next();
state.first_is_media = true;
}
state.last_edge = label.chars().next_back();
boundary.set(state);
}
return;
}
let escaped_label = escape_link_label(label);
append_markdown_link(
output,
&MarkdownLink {
label: &escaped_label,
href: src,
title: None,
raw_text: "",
},
options,
ctx.reference_collector.as_ref(),
);
}
pub fn extract_media_src<'a>(tag: &'a HTMLTag<'a>) -> Cow<'a, str> {
crate::converter::utility::attributes::decoded_attribute(tag, "src").unwrap_or(Cow::Borrowed(""))
}
pub(in crate::converter) fn media_element_src<'a>(
tag: &'a HTMLTag<'a>,
parser: &'a Parser,
choice: InlineDataMedia,
) -> Cow<'a, str> {
let own = extract_media_src(tag);
let children = tag.children();
let mut sources = children
.top()
.iter()
.filter_map(|child_handle| match child_handle.get(parser) {
Some(crate::dom::Node::Tag(child_tag)) if is_source_element(child_tag) => Some(child_tag),
_ => None,
})
.map(|source| crate::converter::utility::attributes::decoded_attribute(source, "src"));
if choice == InlineDataMedia::Keep {
return if own.is_empty() {
sources.next().flatten().unwrap_or(Cow::Borrowed(""))
} else {
own
};
}
let addresses = std::iter::once(own)
.chain(sources.flatten())
.filter(|address| !address.is_empty());
first_address(choice, addresses).unwrap_or(Cow::Borrowed(""))
}
pub fn is_source_element(tag: &HTMLTag) -> bool {
tag_name_eq(tag.name().as_utf8_str(), "source")
}
pub const fn should_output_media_link(src: &str) -> bool {
!src.is_empty()
}
pub fn open_media(
tag_name: &str,
node_handle: &NodeHandle,
parser: &Parser,
output: &mut String,
context: MediaContext<'_>,
children: &mut Vec<NodeHandle>,
) -> Option<Open> {
let Some(crate::dom::Node::Tag(tag)) = node_handle.get(parser) else {
return None;
};
if tag_name == "audio" {
handle_audio(node_handle, tag, parser, output, context, children);
} else {
handle_video(node_handle, tag, parser, output, context, children);
}
(!children.is_empty()).then_some(Open {
scope: None,
close: Close::Capture(CaptureEnd::MediaFallback),
})
}
fn list_media_fallback(tag: &HTMLTag, parser: &Parser, children: &mut Vec<NodeHandle>) {
children.extend(tag.children().top().iter().copied().filter(|child_handle| {
!matches!(child_handle.get(parser), Some(crate::dom::Node::Tag(child_tag)) if is_source_element(child_tag))
}));
}
pub fn close_media_fallback(fallback: &str, output: &mut String, ctx: &Context) {
if !fallback.is_empty() {
let fallback = fallback.trim();
if ctx.in_link
&& !fallback.is_empty()
&& output.ends_with(|character: char| !character.is_whitespace())
&& !output.ends_with(['(', '[', '{'])
&& !fallback.starts_with(['.', ',', ';', ':', '!', '?', ')', ']', '}'])
{
output.push(' ');
}
output.push_str(fallback);
if ctx.in_link && !fallback.is_empty() {
mark_media_tail(ctx);
}
if !ctx.in_paragraph && !ctx.convert_as_inline && !ctx.in_link {
output.push_str("\n\n");
}
}
}
fn mark_media_tail(ctx: &Context) {
if let Some(boundary) = ctx.media_boundary.as_ref() {
let mut state = boundary.get();
state.pending = true;
boundary.set(state);
}
}
#[cfg(feature = "visitor")]
fn apply_media_visit_result(
visit_result: crate::visitor::VisitResult,
node_handle: &NodeHandle,
parser: &Parser,
output: &mut String,
ctx: &Context,
) -> bool {
use crate::visitor::VisitResult;
match visit_result {
VisitResult::Continue => false,
VisitResult::Skip => true,
VisitResult::Custom(custom) => {
output.push_str(&custom);
if !ctx.in_paragraph && !ctx.convert_as_inline && !custom.ends_with('\n') {
output.push('\n');
}
true
}
VisitResult::PreserveHtml => {
use crate::converter::utility::serialization::serialize_node;
output.push_str(&serialize_node(node_handle, parser));
true
}
VisitResult::Error(err) => {
if ctx.visitor_error.borrow().is_none() {
*ctx.visitor_error.borrow_mut() = Some(err);
}
true
}
}
}
#[cfg_attr(not(feature = "visitor"), allow(unused_variables))]
fn handle_audio(
node_handle: &NodeHandle,
tag: &HTMLTag,
parser: &Parser,
output: &mut String,
context: MediaContext<'_>,
children: &mut Vec<NodeHandle>,
) {
let MediaContext {
options,
ctx,
depth,
dom_ctx,
} = context;
let raw_src = media_element_src(tag, parser, options.inline_data_media);
let base_resolved_src = ctx.resolve_url(&raw_src, node_handle, parser, dom_ctx);
let src = sanitize_markdown_url(base_resolved_src.as_deref().unwrap_or(&raw_src)).into_owned();
let src_opt: Option<&str> = if src.is_empty() { None } else { Some(src.as_str()) };
#[cfg(feature = "visitor")]
if let Some(ref visitor_handle) = ctx.visitor {
use crate::visitor::{NodeContext, NodeType};
let node_id = node_handle.get_inner();
let parent_tag = dom_ctx.parent_tag_name(node_id, parser);
let index_in_parent = dom_ctx.get_sibling_index(node_id).unwrap_or(0);
let node_ctx = NodeContext::with_lazy_attributes(
NodeType::Element,
Cow::Borrowed("audio"),
tag,
depth,
index_in_parent,
parent_tag.map(Cow::Borrowed),
false,
);
let visit_result = {
let mut visitor = visitor_handle.lock().expect("visitor mutex poisoned");
visitor.visit_audio(&node_ctx, src_opt)
};
if apply_media_visit_result(visit_result, node_handle, parser, output, ctx) {
return;
}
}
if ctx.in_code_block {
return;
}
let inline_data = ctx.inline_data_treatment(options.inline_data_media, &src);
if inline_data == InlineDataMedia::DropElement {
return;
}
if inline_data == InlineDataMedia::Keep && should_output_media_link(&src) {
append_media_src_link(output, &src, tag, options, ctx);
if !ctx.in_paragraph && !ctx.convert_as_inline && !ctx.in_link {
output.push_str("\n\n");
}
}
list_media_fallback(tag, parser, children);
if ctx.in_link && inline_data == InlineDataMedia::Keep && !src.is_empty() {
mark_media_tail(ctx);
}
}
#[cfg_attr(not(feature = "visitor"), allow(unused_variables))]
fn handle_video(
node_handle: &NodeHandle,
tag: &HTMLTag,
parser: &Parser,
output: &mut String,
context: MediaContext<'_>,
children: &mut Vec<NodeHandle>,
) {
let MediaContext {
options,
ctx,
depth,
dom_ctx,
} = context;
let raw_src = media_element_src(tag, parser, options.inline_data_media);
let base_resolved_src = ctx.resolve_url(&raw_src, node_handle, parser, dom_ctx);
let src = sanitize_markdown_url(base_resolved_src.as_deref().unwrap_or(&raw_src)).into_owned();
let src_opt: Option<&str> = if src.is_empty() { None } else { Some(src.as_str()) };
#[cfg(feature = "visitor")]
if let Some(ref visitor_handle) = ctx.visitor {
use crate::visitor::{NodeContext, NodeType};
let node_id = node_handle.get_inner();
let parent_tag = dom_ctx.parent_tag_name(node_id, parser);
let index_in_parent = dom_ctx.get_sibling_index(node_id).unwrap_or(0);
let node_ctx = NodeContext::with_lazy_attributes(
NodeType::Element,
Cow::Borrowed("video"),
tag,
depth,
index_in_parent,
parent_tag.map(Cow::Borrowed),
false,
);
let visit_result = {
let mut visitor = visitor_handle.lock().expect("visitor mutex poisoned");
visitor.visit_video(&node_ctx, src_opt)
};
if apply_media_visit_result(visit_result, node_handle, parser, output, ctx) {
return;
}
}
if ctx.in_code_block {
return;
}
let inline_data = ctx.inline_data_treatment(options.inline_data_media, &src);
if inline_data == InlineDataMedia::DropElement {
return;
}
if inline_data == InlineDataMedia::Keep && should_output_media_link(&src) {
append_media_src_link(output, &src, tag, options, ctx);
if !ctx.in_paragraph && !ctx.convert_as_inline && !ctx.in_link {
output.push_str("\n\n");
}
}
list_media_fallback(tag, parser, children);
if ctx.in_link && inline_data == InlineDataMedia::Keep && !src.is_empty() {
mark_media_tail(ctx);
}
}
pub fn open_picture(tag: &HTMLTag, parser: &Parser, children: &mut Vec<NodeHandle>) -> crate::converter::walk::Open {
list_media_fallback(tag, parser, children);
crate::converter::walk::Open::children_only()
}
#[cfg_attr(not(feature = "visitor"), allow(unused_variables))]
pub fn handle_iframe(
node_handle: &NodeHandle,
tag: &HTMLTag,
parser: &Parser,
output: &mut String,
context: MediaContext<'_>,
) {
let MediaContext {
options,
ctx,
depth,
dom_ctx,
} = context;
let raw_src = crate::converter::utility::attributes::decoded_attribute(tag, "src").unwrap_or(Cow::Borrowed(""));
let base_resolved_src = ctx.resolve_url(&raw_src, node_handle, parser, dom_ctx);
let src = sanitize_markdown_url(base_resolved_src.as_deref().unwrap_or(&raw_src)).into_owned();
let src_opt: Option<&str> = if src.is_empty() { None } else { Some(src.as_str()) };
#[cfg(feature = "visitor")]
if let Some(ref visitor_handle) = ctx.visitor {
use crate::visitor::{NodeContext, NodeType};
let node_id = node_handle.get_inner();
let parent_tag = dom_ctx.parent_tag_name(node_id, parser);
let index_in_parent = dom_ctx.get_sibling_index(node_id).unwrap_or(0);
let node_ctx = NodeContext::with_lazy_attributes(
NodeType::Element,
Cow::Borrowed("iframe"),
tag,
depth,
index_in_parent,
parent_tag.map(Cow::Borrowed),
false,
);
let visit_result = {
let mut visitor = visitor_handle.lock().expect("visitor mutex poisoned");
visitor.visit_iframe(&node_ctx, src_opt)
};
if apply_media_visit_result(visit_result, node_handle, parser, output, ctx) {
return;
}
}
if ctx.inline_data_treatment(options.inline_data_media, &src) == InlineDataMedia::Keep && !src.is_empty() {
append_media_src_link(output, &src, tag, options, ctx);
if !ctx.in_paragraph && !ctx.convert_as_inline {
output.push_str("\n\n");
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn should_escape_a_src_that_would_close_the_iframe_link_and_open_a_new_one() {
let html = "<iframe src='a](https://evil.example/payload)b'></iframe>";
let result = crate::convert(html, None).unwrap();
let content = result.content.unwrap_or_default();
assert_eq!(content, "[iframe](a](https://evil.example/payload)b)\n");
}
#[test]
fn should_escape_a_src_that_would_close_the_audio_link_and_open_a_new_one() {
let html = "<audio src='a](https://evil.example/payload)b'></audio>";
let result = crate::convert(html, None).unwrap();
let content = result.content.unwrap_or_default();
assert_eq!(content, "[audio](a](https://evil.example/payload)b)\n");
}
#[test]
fn should_escape_a_src_that_would_close_the_video_link_and_open_a_new_one() {
let html = "<video src='a](https://evil.example/payload)b'></video>";
let result = crate::convert(html, None).unwrap();
let content = result.content.unwrap_or_default();
assert_eq!(content, "[video](a](https://evil.example/payload)b)\n");
}
}