__init__.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. # pyright: basic
  4. """Render SearXNG instance documentation.
  5. Usage in a Flask app route:
  6. .. code:: python
  7. from searx import infopage
  8. _INFO_PAGES = infopage.InfoPageSet(infopage.MistletoePage)
  9. @app.route('/info/<pagename>', methods=['GET'])
  10. def info(pagename):
  11. locale = request.preferences.get_value('locale')
  12. page = _INFO_PAGES.get_page(pagename, locale)
  13. """
  14. __all__ = ['InfoPage', 'MistletoePage', 'InfoPageSet']
  15. import os.path
  16. import logging
  17. from functools import cached_property
  18. import typing
  19. import urllib.parse
  20. import jinja2
  21. from flask.helpers import url_for
  22. import mistletoe
  23. from .. import get_setting
  24. from ..version import GIT_URL
  25. logger = logging.getLogger('doc')
  26. class InfoPage:
  27. """A page of the :py:obj:`online documentation <InfoPageSet>`."""
  28. def __init__(self, fname, base_url=None):
  29. self.fname = fname
  30. self.base_url = base_url
  31. @cached_property
  32. def raw_content(self):
  33. """Raw content of the page (without any jinja rendering)"""
  34. with open(self.fname, 'r', encoding='utf-8') as f:
  35. return f.read()
  36. @cached_property
  37. def content(self):
  38. """Content of the page (rendered in a Jinja conntext)"""
  39. ctx = self.get_ctx()
  40. template = jinja2.Environment().from_string(self.raw_content)
  41. return template.render(**ctx)
  42. @cached_property
  43. def title(self):
  44. """Title of the content (without any markup)"""
  45. t = ""
  46. for l in self.raw_content.split('\n'):
  47. if l.startswith('# '):
  48. t = l.strip('# ')
  49. return t
  50. def get_ctx(self): # pylint: disable=no-self-use
  51. """Jinja context to render :py:obj:`InfoPage.content`"""
  52. def _md_link(name, url):
  53. url = url_for(url)
  54. if self.base_url:
  55. url = self.base_url + url
  56. return "[%s](%s)" % (name, url)
  57. def _md_search(query):
  58. url = '%s?q=%s' % (url_for('search'), urllib.parse.quote(query))
  59. if self.base_url:
  60. url = self.base_url + url
  61. return '[%s](%s)' % (query, url)
  62. ctx = {}
  63. ctx['GIT_URL'] = GIT_URL
  64. ctx['get_setting'] = get_setting
  65. ctx['link'] = _md_link
  66. ctx['search'] = _md_search
  67. return ctx
  68. def render(self):
  69. """Render / return content"""
  70. return self.content
  71. class MistletoePage(InfoPage):
  72. """A HTML page of the :py:obj:`online documentation <InfoPageSet>`."""
  73. def __init__(self, *args, **kwargs):
  74. super().__init__(*args, **kwargs)
  75. @cached_property
  76. def html(self):
  77. """HTML representation of this page"""
  78. return self.render()
  79. def render(self):
  80. """Render Markdown (CommonMark_) to HTML by using mistletoe_.
  81. .. _CommonMark: https://commonmark.org/
  82. .. _mistletoe: https://github.com/miyuchina/mistletoe
  83. """
  84. return mistletoe.markdown(self.content)
  85. _INFO_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'info'))
  86. class InfoPageSet: # pylint: disable=too-few-public-methods
  87. """Cached rendering of the online documentation a SearXNG instance has.
  88. :param page_class: render online documentation by :py:obj:`InfoPage` parser.
  89. :type page_class: :py:obj:`InfoPage`
  90. """
  91. def __init__(self, page_class: typing.Type[InfoPage], base_url=None):
  92. self.page_class = page_class
  93. self.base_url = base_url
  94. self.CACHE: typing.Dict[tuple, InfoPage] = {}
  95. # future: could be set from settings.xml
  96. self.folder: str = _INFO_FOLDER
  97. """location of the Markdwon files"""
  98. self.i18n_origin: str = 'en'
  99. """default language"""
  100. self.l10n: typing.List = [
  101. 'en',
  102. ]
  103. """list of supported languages (aka locales)"""
  104. self.toc: typing.List = [
  105. 'search-syntax',
  106. 'about',
  107. ]
  108. """list of articles in the online documentation"""
  109. def get_page(self, pagename: str, locale: typing.Optional[str] = None):
  110. """Return ``pagename`` instance of :py:obj:`InfoPage`
  111. :param pagename: name of the page, a value from :py:obj:`InfoPageSet.toc`
  112. :type pagename: str
  113. :param locale: language of the page, e.g. ``en``, ``zh_Hans_CN``
  114. (default: :py:obj:`InfoPageSet.i18n_origin`)
  115. :type locale: str
  116. """
  117. if pagename not in self.toc:
  118. return None
  119. if locale is not None and locale not in self.l10n:
  120. return None
  121. locale = locale or self.i18n_origin
  122. cache_key = (pagename, locale)
  123. page = self.CACHE.get(cache_key)
  124. if page is not None:
  125. return page
  126. # not yet instantiated
  127. fname = os.path.join(self.folder, locale, pagename) + '.md'
  128. if not os.path.exists(fname):
  129. logger.error('file %s does not exists', fname)
  130. return None
  131. page = self.page_class(fname, self.base_url)
  132. self.CACHE[cache_key] = page
  133. return page
  134. def all_pages(self, locale: typing.Optional[str] = None):
  135. """Iterate over all pages"""
  136. locale = locale or self.i18n_origin
  137. for pagename in self.toc:
  138. page = self.get_page(pagename, locale)
  139. yield pagename, page