Rivista/rivista/gmi/post.py

80 lines
3.7 KiB
Python
Raw Normal View History

#!/usr/bin/python
# -*- coding: utf-8 -*-
#from markdown_text_clean import clean_text
#from md2gemini import md2gemini
#from rivista.gmi.markdown import GmiMarkdown
from rivista.html.gmi import HtmlGmi
from rivista.markdown.html import MarkdownHtml
class GmiPost:
def generate_gmi(atom: dict):
"""Generate an Gemini document."""
atom_title = atom['title']
atom_subtitle = atom['subtitle']
atom_header = f'# {atom_title}\n### {atom_subtitle}\n\n'
atom_items = []
for item in atom['items']:
item_title = item['title']
item_published = item['published']
item_updated = item['updated']
item_contents = ''
for content in item['contents']:
match content['type']:
case 'text':
content_html = MarkdownHtml.convert_to_html(content['text'])
content_text = HtmlGmi.convert_to_gmi(content_html)
#content_text = GmiMarkdown.convert_to_gmi(content['text'])
#content_text = md2gemini(content['text'], links="at-end")
#content_text = clean_text(content['text'])
item_contents += f'\n{content_text}\n'
case _ if content['type'] in ('html', 'xhtml'):
content_text = HtmlGmi.convert_to_gmi(content['text'])
item_contents += f'\n{content_text}\n'
case _:
content_text = content['text']
item_contents += f'\n```\n{content_text}\n```\n'
links = item['links'] if 'links' in item else None
item_links = ''
if links:
item_links = '\n### Related resources\n\n'
for link in links:
link_href = link['href']
link_rel = link['rel']
link_type = link['type']
if link_type:
item_links += f'=> {link_href} {link_rel} ({link_type})\n'
else:
item_links += f'=> {link_href} {link_rel}\n'
categories = item['categories'] if 'categories' in item else None
item_categories = ''
if categories:
item_categories = '\n### Categories\n\n'
for category in categories:
item_categories += f'{category}, '
item_categories = item_categories[0:len(item_categories)-2] + '.\n'
authors = item['authors'] if 'authors' in item else None
item_authors = ''
if authors:
item_authors = '\n### Authors\n\n'
for author in authors:
author_text = author['name'] or author['uri'] or author['email']
if 'email' in author and author['email']:
item_author_email = 'mailto:' + author['email']
item_authors += f'=> {author_text} {item_author_email}\n'
elif 'uri' in author and author['uri']:
item_author_uri = author['uri']
item_authors += f'=> {author_text} {item_author_uri}\n'
else:
item_authors += f'{author_text}\n'
atom_items. append(f'\n## {item_title}\n\n' +
f'Published: {item_published}\n' +
f'Updated: {item_updated}\n' +
item_contents +
item_links +
item_categories +
item_authors)
gmi_text = atom_header + '\n'.join(atom_items)
return gmi_text