webutils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. # -*- coding: utf-8 -*-
  2. from __future__ import annotations
  3. import os
  4. import pathlib
  5. import csv
  6. import hashlib
  7. import hmac
  8. import re
  9. import inspect
  10. import itertools
  11. import json
  12. from datetime import datetime, timedelta
  13. from typing import Iterable, List, Tuple, Dict, 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, settings
  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:
  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. results = rc.get_ordered_results()
  103. keys = ('title', 'url', 'content', 'host', 'engine', 'score', 'type')
  104. csv.writerow(keys)
  105. for row in results:
  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 = {'title': a, 'type': 'answer'}
  111. csv.writerow([row.get(key, '') for key in keys])
  112. for a in rc.suggestions:
  113. row = {'title': a, 'type': 'suggestion'}
  114. csv.writerow([row.get(key, '') for key in keys])
  115. for a in rc.corrections:
  116. row = {'title': a, 'type': 'correction'}
  117. csv.writerow([row.get(key, '') for key in keys])
  118. def get_json_response(sq: SearchQuery, rc: ResultContainer) -> str:
  119. """Returns the JSON string of the results to a query (``application/json``)"""
  120. results = rc.number_of_results
  121. x = {
  122. 'query': sq.query,
  123. 'number_of_results': results,
  124. 'results': rc.get_ordered_results(),
  125. 'answers': list(rc.answers),
  126. 'corrections': list(rc.corrections),
  127. 'infoboxes': rc.infoboxes,
  128. 'suggestions': list(rc.suggestions),
  129. 'unresponsive_engines': get_translated_errors(rc.unresponsive_engines),
  130. }
  131. response = json.dumps(x, default=lambda item: list(item) if isinstance(item, set) else item)
  132. return response
  133. def get_themes(templates_path):
  134. """Returns available themes list."""
  135. return os.listdir(templates_path)
  136. def get_hash_for_file(file: pathlib.Path) -> str:
  137. m = hashlib.sha1()
  138. with file.open('rb') as f:
  139. m.update(f.read())
  140. return m.hexdigest()
  141. def get_static_files(static_path: str) -> Dict[str, str]:
  142. static_files: Dict[str, str] = {}
  143. static_path_path = pathlib.Path(static_path)
  144. def walk(path: pathlib.Path):
  145. for file in path.iterdir():
  146. if file.name.startswith('.'):
  147. # ignore hidden file
  148. continue
  149. if file.is_file():
  150. static_files[str(file.relative_to(static_path_path))] = get_hash_for_file(file)
  151. if file.is_dir() and file.name not in ('node_modules', 'src'):
  152. # ignore "src" and "node_modules" directories
  153. walk(file)
  154. walk(static_path_path)
  155. return static_files
  156. def get_result_templates(templates_path):
  157. result_templates = set()
  158. templates_path_length = len(templates_path) + 1
  159. for directory, _, files in os.walk(templates_path):
  160. if directory.endswith('result_templates'):
  161. for filename in files:
  162. f = os.path.join(directory[templates_path_length:], filename)
  163. result_templates.add(f)
  164. return result_templates
  165. def new_hmac(secret_key, url):
  166. return hmac.new(secret_key.encode(), url, hashlib.sha256).hexdigest()
  167. def is_hmac_of(secret_key, value, hmac_to_check):
  168. hmac_of_value = new_hmac(secret_key, value)
  169. return len(hmac_of_value) == len(hmac_to_check) and hmac.compare_digest(hmac_of_value, hmac_to_check)
  170. def prettify_url(url, max_length=74):
  171. if len(url) > max_length:
  172. chunk_len = int(max_length / 2 + 1)
  173. return '{0}[...]{1}'.format(url[:chunk_len], url[-chunk_len:])
  174. else:
  175. return url
  176. def contains_cjko(s: str) -> bool:
  177. """This function check whether or not a string contains Chinese, Japanese,
  178. or Korean characters. It employs regex and uses the u escape sequence to
  179. match any character in a set of Unicode ranges.
  180. Args:
  181. s (str): string to be checked.
  182. Returns:
  183. bool: True if the input s contains the characters and False otherwise.
  184. """
  185. unicode_ranges = (
  186. '\u4e00-\u9fff' # Chinese characters
  187. '\u3040-\u309f' # Japanese hiragana
  188. '\u30a0-\u30ff' # Japanese katakana
  189. '\u4e00-\u9faf' # Japanese kanji
  190. '\uac00-\ud7af' # Korean hangul syllables
  191. '\u1100-\u11ff' # Korean hangul jamo
  192. )
  193. return bool(re.search(fr'[{unicode_ranges}]', s))
  194. def regex_highlight_cjk(word: str) -> str:
  195. """Generate the regex pattern to match for a given word according
  196. to whether or not the word contains CJK characters or not.
  197. If the word is and/or contains CJK character, the regex pattern
  198. will match standalone word by taking into account the presence
  199. of whitespace before and after it; if not, it will match any presence
  200. of the word throughout the text, ignoring the whitespace.
  201. Args:
  202. word (str): the word to be matched with regex pattern.
  203. Returns:
  204. str: the regex pattern for the word.
  205. """
  206. rword = re.escape(word)
  207. if contains_cjko(rword):
  208. return fr'({rword})'
  209. else:
  210. return fr'\b({rword})(?!\w)'
  211. def highlight_content(content, query):
  212. if not content:
  213. return None
  214. # ignoring html contents
  215. # TODO better html content detection
  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. for q in set(queries):
  226. content = re.sub(
  227. regex_highlight_cjk(q), f'<span class="highlight">{q}</span>'.replace('\\', r'\\'), content
  228. )
  229. return content
  230. def searxng_l10n_timespan(dt: datetime) -> str: # pylint: disable=invalid-name
  231. """Returns a human-readable and translated string indicating how long ago
  232. a date was in the past / the time span of the date to the present.
  233. On January 1st, midnight, the returned string only indicates how many years
  234. ago the date was.
  235. """
  236. # TODO, check if timezone is calculated right # pylint: disable=fixme
  237. d = dt.date()
  238. t = dt.time()
  239. if d.month == 1 and d.day == 1 and t.hour == 0 and t.minute == 0 and t.second == 0:
  240. return str(d.year)
  241. if dt.replace(tzinfo=None) >= datetime.now() - timedelta(days=1):
  242. timedifference = datetime.now() - dt.replace(tzinfo=None)
  243. minutes = int((timedifference.seconds / 60) % 60)
  244. hours = int(timedifference.seconds / 60 / 60)
  245. if hours == 0:
  246. return gettext('{minutes} minute(s) ago').format(minutes=minutes)
  247. return gettext('{hours} hour(s), {minutes} minute(s) ago').format(hours=hours, minutes=minutes)
  248. return format_date(dt)
  249. def is_flask_run_cmdline():
  250. """Check if the application was started using "flask run" command line
  251. Inspect the callstack.
  252. See https://github.com/pallets/flask/blob/master/src/flask/__main__.py
  253. Returns:
  254. bool: True if the application was started using "flask run".
  255. """
  256. frames = inspect.stack()
  257. if len(frames) < 2:
  258. return False
  259. return frames[-2].filename.endswith('flask/cli.py')
  260. NO_SUBGROUPING = 'without further subgrouping'
  261. def group_engines_in_tab(engines: Iterable[Engine]) -> List[Tuple[str, Iterable[Engine]]]:
  262. """Groups an Iterable of engines by their first non tab category (first subgroup)"""
  263. def get_subgroup(eng):
  264. non_tab_categories = [c for c in eng.categories if c not in tabs + [DEFAULT_CATEGORY]]
  265. return non_tab_categories[0] if len(non_tab_categories) > 0 else NO_SUBGROUPING
  266. def group_sort_key(group):
  267. return (group[0] == NO_SUBGROUPING, group[0].lower())
  268. def engine_sort_key(engine):
  269. return (engine.about.get('language', ''), engine.name)
  270. tabs = list(settings['categories_as_tabs'].keys())
  271. subgroups = itertools.groupby(sorted(engines, key=get_subgroup), get_subgroup)
  272. sorted_groups = sorted(((name, list(engines)) for name, engines in subgroups), key=group_sort_key)
  273. ret_val = []
  274. for groupname, engines in sorted_groups:
  275. group_bang = '!' + groupname.replace(' ', '_') if groupname != NO_SUBGROUPING else ''
  276. ret_val.append((groupname, group_bang, sorted(engines, key=engine_sort_key)))
  277. return ret_val