__init__.py 5.1 KB

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