__init__.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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', 'InfoPageSet']
  15. import os
  16. import os.path
  17. import logging
  18. import typing
  19. import urllib.parse
  20. import jinja2
  21. from flask.helpers import url_for
  22. from markdown_it import MarkdownIt
  23. from .. import get_setting
  24. from ..compat import cached_property
  25. from ..version import GIT_URL
  26. from ..locales import LOCALE_NAMES
  27. logger = logging.getLogger('searx.infopage')
  28. _INFO_FOLDER = os.path.abspath(os.path.dirname(__file__))
  29. class InfoPage:
  30. """A page of the :py:obj:`online documentation <InfoPageSet>`."""
  31. def __init__(self, fname):
  32. self.fname = fname
  33. @cached_property
  34. def raw_content(self):
  35. """Raw content of the page (without any jinja rendering)"""
  36. with open(self.fname, 'r', encoding='utf-8') as f:
  37. return f.read()
  38. @cached_property
  39. def content(self):
  40. """Content of the page (rendered in a Jinja conntext)"""
  41. ctx = self.get_ctx()
  42. template = jinja2.Environment().from_string(self.raw_content)
  43. return template.render(**ctx)
  44. @cached_property
  45. def title(self):
  46. """Title of the content (without any markup)"""
  47. t = ""
  48. for l in self.raw_content.split('\n'):
  49. if l.startswith('# '):
  50. t = l.strip('# ')
  51. return t
  52. @cached_property
  53. def html(self):
  54. """Render Markdown (CommonMark_) to HTML by using markdown-it-py_.
  55. .. _CommonMark: https://commonmark.org/
  56. .. _markdown-it-py: https://github.com/executablebooks/markdown-it-py
  57. """
  58. return MarkdownIt(
  59. "commonmark", {"typographer": True}
  60. ).enable(
  61. ["replacements", "smartquotes"]
  62. ).render(self.content)
  63. def get_ctx(self): # pylint: disable=no-self-use
  64. """Jinja context to render :py:obj:`InfoPage.content`"""
  65. def _md_link(name, url):
  66. url = url_for(url, _external=True)
  67. return "[%s](%s)" % (name, url)
  68. def _md_search(query):
  69. url = '%s?q=%s' % (url_for('search', _external=True), urllib.parse.quote(query))
  70. return '[%s](%s)' % (query, url)
  71. ctx = {}
  72. ctx['GIT_URL'] = GIT_URL
  73. ctx['get_setting'] = get_setting
  74. ctx['link'] = _md_link
  75. ctx['search'] = _md_search
  76. return ctx
  77. def __repr__(self):
  78. return f'<{self.__class__.__name__} fname={self.fname!r}>'
  79. class InfoPageSet: # pylint: disable=too-few-public-methods
  80. """Cached rendering of the online documentation a SearXNG instance has.
  81. :param page_class: render online documentation by :py:obj:`InfoPage` parser.
  82. :type page_class: :py:obj:`InfoPage`
  83. :param info_folder: information directory
  84. :type info_folder: str
  85. """
  86. def __init__(
  87. self, page_class: typing.Optional[typing.Type[InfoPage]] = None, info_folder: typing.Optional[str] = None
  88. ):
  89. self.page_class = page_class or InfoPage
  90. self.folder: str = info_folder or _INFO_FOLDER
  91. """location of the Markdwon files"""
  92. self.CACHE: typing.Dict[tuple, typing.Optional[InfoPage]] = {}
  93. self.locale_default: str = 'en'
  94. """default language"""
  95. self.locales: typing.List[str] = [
  96. locale.replace('_', '-') for locale in os.listdir(_INFO_FOLDER) if locale.replace('_', '-') in LOCALE_NAMES
  97. ]
  98. """list of supported languages (aka locales)"""
  99. self.toc: typing.List[str] = [
  100. 'search-syntax',
  101. 'about',
  102. ]
  103. """list of articles in the online documentation"""
  104. def get_page(self, pagename: str, locale: typing.Optional[str] = None):
  105. """Return ``pagename`` instance of :py:obj:`InfoPage`
  106. :param pagename: name of the page, a value from :py:obj:`InfoPageSet.toc`
  107. :type pagename: str
  108. :param locale: language of the page, e.g. ``en``, ``zh_Hans_CN``
  109. (default: :py:obj:`InfoPageSet.i18n_origin`)
  110. :type locale: str
  111. """
  112. locale = locale or self.locale_default
  113. if pagename not in self.toc:
  114. return None
  115. if locale not in self.locales:
  116. return None
  117. cache_key = (pagename, locale)
  118. page = self.CACHE.get(cache_key)
  119. if page is not None:
  120. return page
  121. # not yet instantiated
  122. fname = os.path.join(self.folder, locale.replace('-', '_'), pagename) + '.md'
  123. if not os.path.exists(fname):
  124. logger.info('file %s does not exists', fname)
  125. self.CACHE[cache_key] = None
  126. return None
  127. page = self.page_class(fname)
  128. self.CACHE[cache_key] = page
  129. return page
  130. def iter_pages(self, locale: typing.Optional[str] = None, fallback_to_default=False):
  131. """Iterate over all pages of the TOC"""
  132. locale = locale or self.locale_default
  133. for page_name in self.toc:
  134. page_locale = locale
  135. page = self.get_page(page_name, locale)
  136. if fallback_to_default and page is None:
  137. page_locale = self.locale_default
  138. page = self.get_page(page_name, self.locale_default)
  139. yield page_name, page_locale, page