user_help.py 2.1 KB

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