webutils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=missing-module-docstring, invalid-name
  3. from __future__ import annotations
  4. import os
  5. import pathlib
  6. import csv
  7. import hashlib
  8. import hmac
  9. import re
  10. import itertools
  11. import json
  12. from datetime import datetime, timedelta
  13. from typing import Iterable, List, Tuple, TYPE_CHECKING
  14. from io import StringIO
  15. from codecs import getincrementalencoder
  16. from flask_babel import gettext, format_date # type: ignore
  17. from searx import logger, get_setting
  18. from searx.engines import DEFAULT_CATEGORY
  19. if TYPE_CHECKING:
  20. from searx.enginelib import Engine
  21. from searx.results import ResultContainer
  22. from searx.search import SearchQuery
  23. from searx.results import UnresponsiveEngine
  24. VALID_LANGUAGE_CODE = re.compile(r'^[a-z]{2,3}(-[a-zA-Z]{2})?$')
  25. logger = logger.getChild('webutils')
  26. timeout_text = gettext('timeout')
  27. parsing_error_text = gettext('parsing error')
  28. http_protocol_error_text = gettext('HTTP protocol error')
  29. network_error_text = gettext('network error')
  30. ssl_cert_error_text = gettext("SSL error: certificate validation has failed")
  31. exception_classname_to_text = {
  32. None: gettext('unexpected crash'),
  33. 'timeout': timeout_text,
  34. 'asyncio.TimeoutError': timeout_text,
  35. 'httpx.TimeoutException': timeout_text,
  36. 'httpx.ConnectTimeout': timeout_text,
  37. 'httpx.ReadTimeout': timeout_text,
  38. 'httpx.WriteTimeout': timeout_text,
  39. 'httpx.HTTPStatusError': gettext('HTTP error'),
  40. 'httpx.ConnectError': gettext("HTTP connection error"),
  41. 'httpx.RemoteProtocolError': http_protocol_error_text,
  42. 'httpx.LocalProtocolError': http_protocol_error_text,
  43. 'httpx.ProtocolError': http_protocol_error_text,
  44. 'httpx.ReadError': network_error_text,
  45. 'httpx.WriteError': network_error_text,
  46. 'httpx.ProxyError': gettext("proxy error"),
  47. 'searx.exceptions.SearxEngineCaptchaException': gettext("CAPTCHA"),
  48. 'searx.exceptions.SearxEngineTooManyRequestsException': gettext("too many requests"),
  49. 'searx.exceptions.SearxEngineAccessDeniedException': gettext("access denied"),
  50. 'searx.exceptions.SearxEngineAPIException': gettext("server API error"),
  51. 'searx.exceptions.SearxEngineXPathException': parsing_error_text,
  52. 'KeyError': parsing_error_text,
  53. 'json.decoder.JSONDecodeError': parsing_error_text,
  54. 'lxml.etree.ParserError': parsing_error_text,
  55. 'ssl.SSLCertVerificationError': ssl_cert_error_text, # for Python > 3.7
  56. 'ssl.CertificateError': ssl_cert_error_text, # for Python 3.7
  57. }
  58. def get_translated_errors(unresponsive_engines: Iterable[UnresponsiveEngine]):
  59. translated_errors = []
  60. for unresponsive_engine in unresponsive_engines:
  61. error_user_text = exception_classname_to_text.get(unresponsive_engine.error_type)
  62. if not error_user_text:
  63. error_user_text = exception_classname_to_text[None]
  64. error_msg = gettext(error_user_text)
  65. if unresponsive_engine.suspended:
  66. error_msg = gettext('Suspended') + ': ' + error_msg
  67. translated_errors.append((unresponsive_engine.engine, error_msg))
  68. return sorted(translated_errors, key=lambda e: e[0])
  69. class CSVWriter:
  70. """A CSV writer which will write rows to CSV file "f", which is encoded in
  71. the given encoding."""
  72. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  73. # Redirect output to a queue
  74. self.queue = StringIO()
  75. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  76. self.stream = f
  77. self.encoder = getincrementalencoder(encoding)()
  78. def writerow(self, row):
  79. self.writer.writerow(row)
  80. # Fetch UTF-8 output from the queue ...
  81. data = self.queue.getvalue()
  82. data = data.strip('\x00')
  83. # ... and re-encode it into the target encoding
  84. data = self.encoder.encode(data)
  85. # write to the target stream
  86. self.stream.write(data.decode())
  87. # empty queue
  88. self.queue.truncate(0)
  89. def writerows(self, rows):
  90. for row in rows:
  91. self.writerow(row)
  92. def write_csv_response(csv: CSVWriter, rc: ResultContainer) -> None: # pylint: disable=redefined-outer-name
  93. """Write rows of the results to a query (``application/csv``) into a CSV
  94. table (:py:obj:`CSVWriter`). First line in the table contain the column
  95. names. The column "type" specifies the type, the following types are
  96. included in the table:
  97. - result
  98. - answer
  99. - suggestion
  100. - correction
  101. """
  102. keys = ('title', 'url', 'content', 'host', 'engine', 'score', 'type')
  103. csv.writerow(keys)
  104. for res in rc.get_ordered_results():
  105. row = res.as_dict()
  106. row['host'] = row['parsed_url'].netloc
  107. row['type'] = 'result'
  108. csv.writerow([row.get(key, '') for key in keys])
  109. for a in rc.answers:
  110. row = a.as_dict()
  111. row['host'] = row['parsed_url'].netloc
  112. csv.writerow([row.get(key, '') for key in keys])
  113. for a in rc.suggestions:
  114. row = {'title': a, 'type': 'suggestion'}
  115. csv.writerow([row.get(key, '') for key in keys])
  116. for a in rc.corrections:
  117. row = {'title': a, 'type': 'correction'}
  118. csv.writerow([row.get(key, '') for key in keys])
  119. class JSONEncoder(json.JSONEncoder): # pylint: disable=missing-class-docstring
  120. def default(self, o):
  121. if isinstance(o, datetime):
  122. return o.isoformat()
  123. if isinstance(o, timedelta):
  124. return o.total_seconds()
  125. if isinstance(o, set):
  126. return list(o)
  127. return super().default(o)
  128. def get_json_response(sq: SearchQuery, rc: ResultContainer) -> str:
  129. """Returns the JSON string of the results to a query (``application/json``)"""
  130. data = {
  131. 'query': sq.query,
  132. 'number_of_results': rc.number_of_results,
  133. 'results': [_.as_dict() for _ in rc.get_ordered_results()],
  134. 'answers': [_.as_dict() for _ in rc.answers],
  135. 'corrections': list(rc.corrections),
  136. 'infoboxes': rc.infoboxes,
  137. 'suggestions': list(rc.suggestions),
  138. 'unresponsive_engines': get_translated_errors(rc.unresponsive_engines),
  139. }
  140. response = json.dumps(data, cls=JSONEncoder)
  141. return response
  142. def get_themes(templates_path):
  143. """Returns available themes list."""
  144. return os.listdir(templates_path)
  145. def get_static_file_list() -> list[str]:
  146. file_list = []
  147. static_path = pathlib.Path(str(get_setting("ui.static_path")))
  148. def _walk(path: pathlib.Path):
  149. for f in path.iterdir():
  150. if f.name.startswith('.'):
  151. # ignore hidden file
  152. continue
  153. if f.is_file():
  154. file_list.append(str(f.relative_to(static_path)))
  155. if f.is_dir():
  156. _walk(f)
  157. _walk(static_path)
  158. return file_list
  159. def get_result_templates(templates_path):
  160. result_templates = set()
  161. templates_path_length = len(templates_path) + 1
  162. for directory, _, files in os.walk(templates_path):
  163. if directory.endswith('result_templates'):
  164. for filename in files:
  165. f = os.path.join(directory[templates_path_length:], filename)
  166. result_templates.add(f)
  167. return result_templates
  168. def new_hmac(secret_key, url):
  169. return hmac.new(secret_key.encode(), url, hashlib.sha256).hexdigest()
  170. def is_hmac_of(secret_key, value, hmac_to_check):
  171. hmac_of_value = new_hmac(secret_key, value)
  172. return len(hmac_of_value) == len(hmac_to_check) and hmac.compare_digest(hmac_of_value, hmac_to_check)
  173. def prettify_url(url, max_length=74):
  174. if len(url) > max_length:
  175. chunk_len = int(max_length / 2 + 1)
  176. return '{0}[...]{1}'.format(url[:chunk_len], url[-chunk_len:])
  177. return url
  178. def contains_cjko(s: str) -> bool:
  179. """This function check whether or not a string contains Chinese, Japanese,
  180. or Korean characters. It employs regex and uses the u escape sequence to
  181. match any character in a set of Unicode ranges.
  182. Args:
  183. s (str): string to be checked.
  184. Returns:
  185. bool: True if the input s contains the characters and False otherwise.
  186. """
  187. unicode_ranges = (
  188. '\u4e00-\u9fff' # Chinese characters
  189. '\u3040-\u309f' # Japanese hiragana
  190. '\u30a0-\u30ff' # Japanese katakana
  191. '\u4e00-\u9faf' # Japanese kanji
  192. '\uac00-\ud7af' # Korean hangul syllables
  193. '\u1100-\u11ff' # Korean hangul jamo
  194. )
  195. return bool(re.search(fr'[{unicode_ranges}]', s))
  196. def regex_highlight_cjk(word: str) -> str:
  197. """Generate the regex pattern to match for a given word according
  198. to whether or not the word contains CJK characters or not.
  199. If the word is and/or contains CJK character, the regex pattern
  200. will match standalone word by taking into account the presence
  201. of whitespace before and after it; if not, it will match any presence
  202. of the word throughout the text, ignoring the whitespace.
  203. Args:
  204. word (str): the word to be matched with regex pattern.
  205. Returns:
  206. str: the regex pattern for the word.
  207. """
  208. rword = re.escape(word)
  209. if contains_cjko(rword):
  210. return fr'({rword})'
  211. return fr'\b({rword})(?!\w)'
  212. def highlight_content(content, query):
  213. if not content:
  214. return None
  215. # ignoring html contents
  216. if content.find('<') != -1:
  217. return content
  218. querysplit = query.split()
  219. queries = []
  220. for qs in querysplit:
  221. qs = qs.replace("'", "").replace('"', '').replace(" ", "")
  222. if len(qs) > 0:
  223. queries.extend(re.findall(regex_highlight_cjk(qs), content, flags=re.I | re.U))
  224. if len(queries) > 0:
  225. regex = re.compile("|".join(map(regex_highlight_cjk, queries)))
  226. return regex.sub(lambda match: f'<span class="highlight">{match.group(0)}</span>'.replace('\\', r'\\'), content)
  227. return content
  228. def searxng_l10n_timespan(dt: datetime) -> str: # pylint: disable=invalid-name
  229. """Returns a human-readable and translated string indicating how long ago
  230. a date was in the past / the time span of the date to the present.
  231. On January 1st, midnight, the returned string only indicates how many years
  232. ago the date was.
  233. """
  234. # TODO, check if timezone is calculated right # pylint: disable=fixme
  235. d = dt.date()
  236. t = dt.time()
  237. if d.month == 1 and d.day == 1 and t.hour == 0 and t.minute == 0 and t.second == 0:
  238. return str(d.year)
  239. if dt.replace(tzinfo=None) >= datetime.now() - timedelta(days=1):
  240. timedifference = datetime.now() - dt.replace(tzinfo=None)
  241. minutes = int((timedifference.seconds / 60) % 60)
  242. hours = int(timedifference.seconds / 60 / 60)
  243. if hours == 0:
  244. return gettext('{minutes} minute(s) ago').format(minutes=minutes)
  245. return gettext('{hours} hour(s), {minutes} minute(s) ago').format(hours=hours, minutes=minutes)
  246. return format_date(dt)
  247. NO_SUBGROUPING = 'without further subgrouping'
  248. def group_engines_in_tab(engines: Iterable[Engine]) -> List[Tuple[str, Iterable[Engine]]]:
  249. """Groups an Iterable of engines by their first non tab category (first subgroup)"""
  250. def get_subgroup(eng):
  251. non_tab_categories = [c for c in eng.categories if c not in tabs + [DEFAULT_CATEGORY]]
  252. return non_tab_categories[0] if len(non_tab_categories) > 0 else NO_SUBGROUPING
  253. def group_sort_key(group):
  254. return (group[0] == NO_SUBGROUPING, group[0].lower())
  255. def engine_sort_key(engine):
  256. return (engine.about.get('language', ''), engine.name)
  257. tabs = list(get_setting('categories_as_tabs').keys())
  258. subgroups = itertools.groupby(sorted(engines, key=get_subgroup), get_subgroup)
  259. sorted_groups = sorted(((name, list(engines)) for name, engines in subgroups), key=group_sort_key)
  260. ret_val = []
  261. for groupname, _engines in sorted_groups:
  262. group_bang = '!' + groupname.replace(' ', '_') if groupname != NO_SUBGROUPING else ''
  263. ret_val.append((groupname, group_bang, sorted(_engines, key=engine_sort_key)))
  264. return ret_val