feed_generator/__init__.py

49 lines
1.5 KiB
Python
Raw Normal View History

2023-08-03 22:15:46 +02:00
import markdown
import pathlib
import os
current_dir = pathlib.Path(__file__).parent
2023-09-05 15:12:31 +02:00
extensions = ['meta', 'nl2br']
2023-08-03 22:15:46 +02:00
with (current_dir / "base_feed.xml").open("r") as f:
base_feed = f.read()
with (current_dir / "base_item.xml").open("r") as f:
base_item = f.read()
def convert_case(string: str):
while string.find("_") != -1:
string = string.replace("_" + string[string.index("_") + 1], string[string.index("_") +1].upper())
return string
2023-09-05 15:12:31 +02:00
def convert_markdown_to_html(article_path: pathlib.Path):
with (article_path / "article.md").open("r") as f:
markdown_data = f.read()
markdown_instance = markdown.Markdown(extensions=extensions)
html = markdown_instance.convert(markdown_data)
metadata = markdown_instance.Meta
return html, metadata
2023-08-03 22:15:46 +02:00
def article_to_xml(article_path: pathlib.Path):
2023-08-05 10:38:54 +02:00
try:
2023-09-05 15:12:31 +02:00
html, metadata = convert_markdown_to_html(article_path)
2023-08-05 10:38:54 +02:00
except Exception as e:
print(e)
2023-08-05 10:39:34 +02:00
return ""
2023-08-03 22:15:46 +02:00
tags = [f"<{convert_case(key)}>{metadata[key][0]}</{convert_case(key)}>" for key in metadata.keys()]
tags.append(f"<description>\n{html}\n</description>")
return base_item.format(tags="\n".join(tags))
def make_rss_feed(path, channel_name, channel_link, description):
articles = "".join([article_to_xml(path) for path in (pathlib.Path.cwd() / path).glob("*")])
return base_feed \
.replace("{title}", channel_name) \
.replace("{link}", channel_link) \
.replace("{description}", description) \
.replace("{items}", articles)