user_help.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # pyright: basic
  2. from typing import Dict, NamedTuple
  3. import pkg_resources
  4. import flask
  5. from flask.helpers import url_for
  6. import mistletoe
  7. from . import get_setting
  8. from .version import GIT_URL
  9. class HelpPage(NamedTuple):
  10. title: str
  11. content: str
  12. # Whenever a new .md file is added to help/ it needs to be added here
  13. _TOC = ('about',)
  14. PAGES: Dict[str, HelpPage] = {}
  15. """ Maps a filename under help/ without the file extension to the rendered page. """
  16. def render(app: flask.Flask):
  17. """
  18. Renders the user documentation. Must be called after all Flask routes have been
  19. registered, because the documentation might try to link to them with Flask's `url_for`.
  20. We render the user documentation once on startup to improve performance.
  21. """
  22. link_targets = {
  23. 'brand.git_url': GIT_URL,
  24. 'brand.public_instances': get_setting('brand.public_instances'),
  25. 'brand.docs_url': get_setting('brand.docs_url'),
  26. }
  27. base_url = get_setting('server.base_url') or None
  28. # we specify base_url so that url_for works for base_urls that have a non-root path
  29. with app.test_request_context(base_url=base_url):
  30. link_targets['url_for:index'] = url_for('index')
  31. link_targets['url_for:preferences'] = url_for('preferences')
  32. link_targets['url_for:stats'] = url_for('stats')
  33. define_link_targets = ''.join(f'[{name}]: {url}\n' for name, url in link_targets.items())
  34. for pagename in _TOC:
  35. file_content = pkg_resources.resource_string(__name__, 'help/' + pagename + '.md').decode()
  36. markdown = define_link_targets + file_content
  37. assert file_content.startswith('# ')
  38. title = file_content.split('\n', maxsplit=1)[0].strip('# ')
  39. content: str = mistletoe.markdown(markdown)
  40. if pagename == 'about':
  41. try:
  42. content += pkg_resources.resource_string(__name__, 'templates/__common__/aboutextend.html').decode()
  43. except FileNotFoundError:
  44. pass
  45. PAGES[pagename] = HelpPage(title=title, content=content)