__init__.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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 (
  59. MarkdownIt("commonmark", {"typographer": True}).enable(["replacements", "smartquotes"]).render(self.content)
  60. )
  61. def get_ctx(self):
  62. """Jinja context to render :py:obj:`InfoPage.content`"""
  63. def _md_link(name, url):
  64. url = url_for(url, _external=True)
  65. return "[%s](%s)" % (name, url)
  66. def _md_search(query):
  67. url = '%s?q=%s' % (url_for('search', _external=True), urllib.parse.quote(query))
  68. return '[%s](%s)' % (query, url)
  69. ctx = {}
  70. ctx['GIT_URL'] = GIT_URL
  71. ctx['get_setting'] = get_setting
  72. ctx['link'] = _md_link
  73. ctx['search'] = _md_search
  74. return ctx
  75. def __repr__(self):
  76. return f'<{self.__class__.__name__} fname={self.fname!r}>'
  77. class InfoPageSet: # pylint: disable=too-few-public-methods
  78. """Cached rendering of the online documentation a SearXNG instance has.
  79. :param page_class: render online documentation by :py:obj:`InfoPage` parser.
  80. :type page_class: :py:obj:`InfoPage`
  81. :param info_folder: information directory
  82. :type info_folder: str
  83. """
  84. def __init__(
  85. self, page_class: typing.Optional[typing.Type[InfoPage]] = None, info_folder: typing.Optional[str] = None
  86. ):
  87. self.page_class = page_class or InfoPage
  88. self.folder: str = info_folder or _INFO_FOLDER
  89. """location of the Markdwon files"""
  90. self.CACHE: typing.Dict[tuple, typing.Optional[InfoPage]] = {}
  91. self.locale_default: str = 'en'
  92. """default language"""
  93. self.locales: typing.List[str] = [
  94. locale.replace('_', '-') for locale in os.listdir(_INFO_FOLDER) if locale.replace('_', '-') in LOCALE_NAMES
  95. ]
  96. """list of supported languages (aka locales)"""
  97. self.toc: typing.List[str] = [
  98. 'search-syntax',
  99. 'about',
  100. 'donate',
  101. ]
  102. """list of articles in the online documentation"""
  103. def get_page(self, pagename: str, locale: typing.Optional[str] = None):
  104. """Return ``pagename`` instance of :py:obj:`InfoPage`
  105. :param pagename: name of the page, a value from :py:obj:`InfoPageSet.toc`
  106. :type pagename: str
  107. :param locale: language of the page, e.g. ``en``, ``zh_Hans_CN``
  108. (default: :py:obj:`InfoPageSet.i18n_origin`)
  109. :type locale: str
  110. """
  111. locale = locale or self.locale_default
  112. if pagename not in self.toc:
  113. return None
  114. if locale not in self.locales:
  115. return None
  116. cache_key = (pagename, locale)
  117. page = self.CACHE.get(cache_key)
  118. if page is not None:
  119. return page
  120. # not yet instantiated
  121. fname = os.path.join(self.folder, locale.replace('-', '_'), pagename) + '.md'
  122. if not os.path.exists(fname):
  123. logger.info('file %s does not exists', fname)
  124. self.CACHE[cache_key] = None
  125. return None
  126. page = self.page_class(fname)
  127. self.CACHE[cache_key] = page
  128. return page
  129. def iter_pages(self, locale: typing.Optional[str] = None, fallback_to_default=False):
  130. """Iterate over all pages of the TOC"""
  131. locale = locale or self.locale_default
  132. for page_name in self.toc:
  133. page_locale = locale
  134. page = self.get_page(page_name, locale)
  135. if fallback_to_default and page is None:
  136. page_locale = self.locale_default
  137. page = self.get_page(page_name, self.locale_default)
  138. yield page_name, page_locale, page