Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 19 additions & 10 deletions packages/markitdown/src/markitdown/converters/_rss_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,9 @@ def _parse_atom_type(self, doc: Document) -> DocumentConverterResult:
title = self._get_data_by_tag_name(root, "title")
subtitle = self._get_data_by_tag_name(root, "subtitle")
entries = root.getElementsByTagName("entry")
md_text = f"# {title}\n"
md_text = ""
if title:
md_text += f"# {title}\n"
if subtitle:
md_text += f"{subtitle}\n"
for entry in entries:
Expand Down Expand Up @@ -143,8 +145,11 @@ def _parse_rss_type(self, doc: Document) -> DocumentConverterResult:
channel_title = self._get_data_by_tag_name(channel, "title")
channel_description = self._get_data_by_tag_name(channel, "description")
items = channel.getElementsByTagName("item")
# Initialize before conditionals: feeds may omit <title> entirely
# (would otherwise raise UnboundLocalError on the first +=).
md_text = ""
if channel_title:
md_text = f"# {channel_title}\n"
md_text += f"# {channel_title}\n"
if channel_description:
md_text += f"{channel_description}\n"
for item in items:
Expand Down Expand Up @@ -179,14 +184,18 @@ def _parse_content(self, content: str) -> str:
def _get_data_by_tag_name(
self, element: Element, tag_name: str
) -> Union[str, None]:
"""Get data from first child element with the given tag name.
Returns None when no such element is found.
"""Get data from the first *direct* child element with the given tag name.

``Element.getElementsByTagName`` is recursive, so using it for channel
or feed metadata would incorrectly pick up nested ``<item>`` /
``<entry>`` titles when the parent omits its own ``<title>``.
Returns None when no such direct child is found.
"""
nodes = element.getElementsByTagName(tag_name)
if not nodes:
return None
fc = nodes[0].firstChild
if fc:
if hasattr(fc, "data"):
for node in element.childNodes:
if getattr(node, "tagName", None) != tag_name:
continue
fc = node.firstChild
if fc and hasattr(fc, "data"):
return fc.data
return None
return None
Original file line number Diff line number Diff line change
Expand Up @@ -95,15 +95,21 @@ def convert(

with zipfile.ZipFile(file_stream, "r") as zipObj:
for name in zipObj.namelist():
# Directory entries end with "/" and have no file payload.
if name.endswith("/"):
continue
try:
z_file_stream = io.BytesIO(zipObj.read(name))
z_file_stream_info = StreamInfo(
extension=os.path.splitext(name)[1],
filename=os.path.basename(name),
)
# Forward caller options (e.g. keep_data_uris) into nested
# conversions so ZIP members behave like standalone files.
result = self._markitdown.convert_stream(
stream=z_file_stream,
stream_info=z_file_stream_info,
**kwargs,
)
if result is not None:
md_content += f"## File: {name}\n\n"
Expand Down
96 changes: 96 additions & 0 deletions packages/markitdown/tests/test_rss_zip_fixes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""Regression tests for RSS metadata / crash fixes and ZIP option forwarding."""

import io
import zipfile

from markitdown import MarkItDown, StreamInfo
from markitdown.converters._rss_converter import RssConverter


def test_rss_no_channel_title_does_not_crash_or_leak_item_title():
"""Feeds without a channel <title> must not crash or steal an item title."""
xml = (
b'<?xml version="1.0"?><rss version="2.0"><channel>'
b"<description>Only desc</description>"
b"<item><title>Item One</title><description>body</description></item>"
b"</channel></rss>"
)
result = RssConverter().convert(io.BytesIO(xml), StreamInfo(extension=".rss"))
assert result.title is None
# Channel heading must not be the nested item title
assert not result.markdown.startswith("# Item One")
assert "Only desc" in result.markdown
assert "## Item One" in result.markdown


def test_rss_no_titles_at_all_does_not_raise():
"""Missing channel title + no item titles previously raised UnboundLocalError."""
xml = (
b'<?xml version="1.0"?><rss version="2.0"><channel>'
b"<description>Only desc</description>"
b"<item><description>body</description></item>"
b"</channel></rss>"
)
result = RssConverter().convert(io.BytesIO(xml), StreamInfo(extension=".rss"))
assert "Only desc" in result.markdown
assert result.title is None


def test_rss_channel_title_still_preferred():
xml = (
b'<?xml version="1.0"?><rss version="2.0"><channel>'
b"<title>Feed Title</title><description>Desc</description>"
b"<item><title>Item</title></item>"
b"</channel></rss>"
)
result = RssConverter().convert(io.BytesIO(xml), StreamInfo(extension=".rss"))
assert result.title == "Feed Title"
assert result.markdown.startswith("# Feed Title")
assert "## Item" in result.markdown


def test_atom_missing_feed_title():
xml = (
b'<?xml version="1.0"?><feed xmlns="http://www.w3.org/2005/Atom">'
b"<entry><title>Entry</title></entry>"
b"</feed>"
)
result = RssConverter().convert(io.BytesIO(xml), StreamInfo(extension=".atom"))
assert result.title is None
assert not result.markdown.startswith("# Entry")
assert "## Entry" in result.markdown


def test_zip_propagates_keep_data_uris_and_skips_directories():
html = b'<html><body><img src="data:image/png;base64,aaaa"/></body></html>'
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("folder/", "")
zf.writestr("folder/x.html", html)
buf.seek(0)

kept = MarkItDown().convert_stream(
buf, stream_info=StreamInfo(extension=".zip"), keep_data_uris=True
)
assert "data:image/png;base64,aaaa" in kept.markdown
assert "## File: folder/x.html" in kept.markdown
# Directory-only entries must not get their own section heading.
assert "\n## File: folder/\n" not in ("\n" + kept.markdown + "\n")

buf.seek(0)
truncated = MarkItDown().convert_stream(
buf, stream_info=StreamInfo(extension=".zip"), keep_data_uris=False
)
assert "data:image/png;base64,aaaa" not in truncated.markdown
assert "data:image" in truncated.markdown
assert "aaaa" not in truncated.markdown


if __name__ == "__main__":
test_rss_no_channel_title_does_not_crash_or_leak_item_title()
test_rss_no_titles_at_all_does_not_raise()
test_rss_channel_title_still_preferred()
test_atom_missing_feed_title()
test_zip_propagates_keep_data_uris_and_skips_directories()
print("all passed")