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