.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
10 _INFO_PAGES = infopage.InfoPageSet(infopage.MistletoePage)
11
12 @app.route('/info/<pagename>', methods=['GET'])
13 def info(pagename):
14
15 locale = request.preferences.get_value('locale')
16 page = _INFO_PAGES.get_page(pagename, locale)
17
18"""
19
20from __future__ import annotations
21
22__all__ = ['InfoPage', 'InfoPageSet']
23
24import os
25import os.path
26import logging
27import typing
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):
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):
58 self.fname = 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):
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.contentcontent)
92 )
93
94 def get_ctx(self):
95 """Jinja context to render :py:obj:`InfoPage.content`"""
96
97 def _md_link(name, url):
98 url = url_for(url, _external=True)
99 return "[%s](%s)" % (name, url)
100
101 def _md_search(query):
102 url = '%s?q=%s' % (url_for('search', _external=True), urllib.parse.quote(query))
103 return '[%s](%s)' % (query, url)
104
105 ctx = {}
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
128 self, page_class: typing.Optional[typing.Type[InfoPage]] = None, info_folder: typing.Optional[str] = None
129 ):
130 self.page_class = page_class or InfoPage
131 self.folder: str = info_folder or _INFO_FOLDER
132 """location of the Markdown files"""
133
134 self.CACHECACHE: typing.Dict[tuple, typing.Optional[InfoPage]] = {}
135
136 self.locale_default: str = 'en'
137 """default language"""
138
139 self.localeslocales: typing.List[str] = [
140 locale.replace('_', '-') for locale in os.listdir(_INFO_FOLDER) if locale.replace('_', '-') in LOCALE_NAMES
141 ]
142 """list of supported languages (aka locales)"""
143
144 self.toc: typing.List[str] = [
145 'search-syntax',
146 'about',
147 'donate',
148 ]
149 """list of articles in the online documentation"""
150
151 def get_page(self, pagename: str, locale: typing.Optional[str] = None):
152 """Return ``pagename`` instance of :py:obj:`InfoPage`
153
154 :param pagename: name of the page, a value from :py:obj:`InfoPageSet.toc`
155 :type pagename: str
156
157 :param locale: language of the page, e.g. ``en``, ``zh_Hans_CN``
158 (default: :py:obj:`InfoPageSet.i18n_origin`)
159 :type locale: str
160
161 """
162 locale = locale or self.locale_default
163
164 if pagename not in self.toc:
165 return None
166 if locale not in self.localeslocales:
167 return None
168
169 cache_key = (pagename, locale)
170
171 if cache_key in self.CACHECACHE:
172 return self.CACHECACHE[cache_key]
173
174 # not yet instantiated
175
176 fname = os.path.join(self.folder, locale.replace('-', '_'), pagename) + '.md'
177 if not os.path.exists(fname):
178 logger.info('file %s does not exists', fname)
179 self.CACHECACHE[cache_key] = None
180 return None
181
182 page = self.page_class(fname)
183 self.CACHECACHE[cache_key] = page
184 return page
185
186 def iter_pages(self, locale: typing.Optional[str] = None, fallback_to_default=False):
187 """Iterate over all pages of the TOC"""
188 locale = locale or self.locale_default
189 for page_name in self.toc:
190 page_locale = locale
191 page = self.get_page(page_name, locale)
192 if fallback_to_default and page is None:
193 page_locale = self.locale_default
194 page = self.get_page(page_name, self.locale_default)
195 if page is not None:
196 # page is None if the page was deleted by the administrator
197 yield page_name, page_locale, page
iter_pages(self, typing.Optional[str] locale=None, fallback_to_default=False)
Definition __init__.py:186
get_page(self, str pagename, typing.Optional[str] locale=None)
Definition __init__.py:151
__init__(self, typing.Optional[typing.Type[InfoPage]] page_class=None, typing.Optional[str] info_folder=None)
Definition __init__.py:129
__init__(self, fname)
Definition __init__.py:57
__getattr__(name)
Definition __init__.py:45