webutils.py 12 KB

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