user_help.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # pyright: basic
  2. from typing import Dict
  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. HELP: Dict[str, str] = {}
  11. """ Maps a filename under help/ without the file extension to the rendered HTML. """
  12. def render(app: flask.Flask):
  13. """
  14. Renders the user documentation. Must be called after all Flask routes have been
  15. registered, because the documentation might try to link to them with Flask's `url_for`.
  16. We render the user documentation once on startup to improve performance.
  17. """
  18. link_targets = {
  19. 'brand.git_url': GIT_URL,
  20. 'brand.public_instances': get_setting('brand.public_instances'),
  21. 'brand.docs_url': get_setting('brand.docs_url'),
  22. }
  23. base_url = get_setting('server.base_url') or None
  24. # we specify base_url so that url_for works for base_urls that have a non-root path
  25. with app.test_request_context(base_url=base_url):
  26. link_targets['url_for:index'] = url_for('index')
  27. link_targets['url_for:preferences'] = url_for('preferences')
  28. link_targets['url_for:stats'] = url_for('stats')
  29. define_link_targets = ''.join(f'[{name}]: {url}\n' for name, url in link_targets.items())
  30. for filename in pkg_resources.resource_listdir(__name__, 'help'):
  31. rootname, ext = os.path.splitext(filename)
  32. if ext != '.md':
  33. continue
  34. markdown = pkg_resources.resource_string(__name__, 'help/' + filename).decode()
  35. markdown = define_link_targets + markdown
  36. HELP[rootname] = mistletoe.markdown(markdown)