.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
__init__.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""Render SearXNG instance documentation.
3
4Usage in a Flask app route:
5
6.. code:: python
7
8 from searx import infopage
9 from searx.extended_types import sxng_request
10
11 _INFO_PAGES = infopage.InfoPageSet(infopage.MistletoePage)
12
13 @app.route('/info/<pagename>', methods=['GET'])
14 def info(pagename):
15
16 locale = sxng_request.preferences.get_value('locale')
17 page = _INFO_PAGES.get_page(pagename, locale)
18
19"""
20
21__all__ = ['InfoPage', 'InfoPageSet']
22
23import typing as t
24
25import os
26import os.path
27import logging
28
29import urllib.parse
30from functools import cached_property
31import jinja2
32from flask.helpers import url_for
33from markdown_it import MarkdownIt
34
35from .. import get_setting
36from ..version import GIT_URL
37from ..locales import LOCALE_NAMES
38
39
40logger = logging.getLogger('searx.infopage')
41_INFO_FOLDER = os.path.abspath(os.path.dirname(__file__))
42INFO_PAGES: 'InfoPageSet'
43
44
45def __getattr__(name: str):
46 if name == 'INFO_PAGES':
47 global INFO_PAGES # pylint: disable=global-statement
48 INFO_PAGES = InfoPageSet()
49 return INFO_PAGES
50
51 raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
52
53
55 """A page of the :py:obj:`online documentation <InfoPageSet>`."""
56
57 def __init__(self, fname: str):
58 self.fname: str = fname
59
60 @cached_property
61 def raw_content(self):
62 """Raw content of the page (without any jinja rendering)"""
63 with open(self.fname, 'r', encoding='utf-8') as f:
64 return f.read()
65
66 @cached_property
67 def content(self):
68 """Content of the page (rendered in a Jinja context)"""
69 ctx = self.get_ctx()
70 template = jinja2.Environment().from_string(self.raw_content)
71 return template.render(**ctx)
72
73 @cached_property
74 def title(self):
75 """Title of the content (without any markup)"""
76 _t = ""
77 for l in self.raw_content.split('\n'):
78 if l.startswith('# '):
79 _t = l.strip('# ')
80 return _t
81
82 @cached_property
83 def html(self) -> str:
84 """Render Markdown (CommonMark_) to HTML by using markdown-it-py_.
85
86 .. _CommonMark: https://commonmark.org/
87 .. _markdown-it-py: https://github.com/executablebooks/markdown-it-py
88
89 """
90 return (
91 MarkdownIt("commonmark", {"typographer": True}).enable(["replacements", "smartquotes"]).render(self.content)
92 )
93
94 def get_ctx(self) -> dict[str, str]:
95 """Jinja context to render :py:obj:`InfoPage.content`"""
96
97 def _md_link(name: str, url: str):
98 url = url_for(url, _external=True)
99 return "[%s](%s)" % (name, url)
100
101 def _md_search(query: str):
102 url = '%s?q=%s' % (url_for('search', _external=True), urllib.parse.quote(query))
103 return '[%s](%s)' % (query, url)
104
105 ctx: dict[str, t.Any] = {}
106 ctx['GIT_URL'] = GIT_URL
107 ctx['get_setting'] = get_setting
108 ctx['link'] = _md_link
109 ctx['search'] = _md_search
110
111 return ctx
112
113 def __repr__(self):
114 return f'<{self.__class__.__name__} fname={self.fname!r}>'
115
116
117class InfoPageSet: # pylint: disable=too-few-public-methods
118 """Cached rendering of the online documentation a SearXNG instance has.
119
120 :param page_class: render online documentation by :py:obj:`InfoPage` parser.
121 :type page_class: :py:obj:`InfoPage`
122
123 :param info_folder: information directory
124 :type info_folder: str
125 """
126
127 def __init__(self, page_class: type[InfoPage] | None = None, info_folder: str | None = None):
128 self.page_class: type[InfoPage] = page_class or InfoPage
129 self.folder: str = info_folder or _INFO_FOLDER
130 """location of the Markdown files"""
131
132 self.CACHE: dict[tuple[str, str], InfoPage | None] = {}
133
134 self.locale_default: str = 'en'
135 """default language"""
136
137 self.locales: list[str] = [
138 locale.replace('_', '-') for locale in os.listdir(_INFO_FOLDER) if locale.replace('_', '-') in LOCALE_NAMES
139 ]
140 """list of supported languages (aka locales)"""
141
142 self.toc: list[str] = [
143 'search-syntax',
144 'about',
145 'donate',
146 ]
147 """list of articles in the online documentation"""
148
149 def get_page(self, pagename: str, locale: str | None = None):
150 """Return ``pagename`` instance of :py:obj:`InfoPage`
151
152 :param pagename: name of the page, a value from :py:obj:`InfoPageSet.toc`
153 :type pagename: str
154
155 :param locale: language of the page, e.g. ``en``, ``zh_Hans_CN``
156 (default: :py:obj:`InfoPageSet.i18n_origin`)
157 :type locale: str
158
159 """
160 locale = locale or self.locale_default
161
162 if pagename not in self.toc:
163 return None
164 if locale not in self.locales:
165 return None
166
167 cache_key = (pagename, locale)
168
169 if cache_key in self.CACHE:
170 return self.CACHE[cache_key]
171
172 # not yet instantiated
173
174 fname = os.path.join(self.folder, locale.replace('-', '_'), pagename) + '.md'
175 if not os.path.exists(fname):
176 logger.info('file %s does not exists', fname)
177 self.CACHE[cache_key] = None
178 return None
179
180 page = self.page_class(fname)
181 self.CACHE[cache_key] = page
182 return page
183
184 def iter_pages(self, locale: str | None = None, fallback_to_default: bool = False):
185 """Iterate over all pages of the TOC"""
186 locale = locale or self.locale_default
187 for page_name in self.toc:
188 page_locale = locale
189 page = self.get_page(page_name, locale)
190 if fallback_to_default and page is None:
191 page_locale = self.locale_default
192 page = self.get_page(page_name, self.locale_default)
193 if page is not None:
194 # page is None if the page was deleted by the administrator
195 yield page_name, page_locale, page
get_page(self, str pagename, str|None locale=None)
Definition __init__.py:149
type[InfoPage] page_class
Definition __init__.py:128
iter_pages(self, str|None locale=None, bool fallback_to_default=False)
Definition __init__.py:184
__init__(self, type[InfoPage]|None page_class=None, str|None info_folder=None)
Definition __init__.py:127
dict[str, str] get_ctx(self)
Definition __init__.py:94
__init__(self, str fname)
Definition __init__.py:57
__getattr__(str name)
Definition __init__.py:45