user_help.py 1.6 KB

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