webutils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. class JSONEncoder(json.JSONEncoder):
  119. def default(self, o):
  120. if isinstance(o, datetime):
  121. return o.isoformat()
  122. if isinstance(o, timedelta):
  123. return o.total_seconds()
  124. if isinstance(o, set):
  125. return list(o)
  126. return super().default(o)
  127. def get_json_response(sq: SearchQuery, rc: ResultContainer) -> str:
  128. """Returns the JSON string of the results to a query (``application/json``)"""
  129. results = rc.number_of_results
  130. x = {
  131. 'query': sq.query,
  132. 'number_of_results': results,
  133. 'results': rc.get_ordered_results(),
  134. 'answers': list(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(x, 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_hash_for_file(file: pathlib.Path) -> str:
  146. m = hashlib.sha1()
  147. with file.open('rb') as f:
  148. m.update(f.read())
  149. return m.hexdigest()
  150. def get_static_files(static_path: str) -> Dict[str, str]:
  151. static_files: Dict[str, str] = {}
  152. static_path_path = pathlib.Path(static_path)
  153. def walk(path: pathlib.Path):
  154. for file in path.iterdir():
  155. if file.name.startswith('.'):
  156. # ignore hidden file
  157. continue
  158. if file.is_file():
  159. static_files[str(file.relative_to(static_path_path))] = get_hash_for_file(file)
  160. if file.is_dir() and file.name not in ('node_modules', 'src'):
  161. # ignore "src" and "node_modules" directories
  162. walk(file)
  163. walk(static_path_path)
  164. return static_files
  165. def get_result_templates(templates_path):
  166. result_templates = set()
  167. templates_path_length = len(templates_path) + 1
  168. for directory, _, files in os.walk(templates_path):
  169. if directory.endswith('result_templates'):
  170. for filename in files:
  171. f = os.path.join(directory[templates_path_length:], filename)
  172. result_templates.add(f)
  173. return result_templates
  174. def new_hmac(secret_key, url):
  175. return hmac.new(secret_key.encode(), url, hashlib.sha256).hexdigest()
  176. def is_hmac_of(secret_key, value, hmac_to_check):
  177. hmac_of_value = new_hmac(secret_key, value)
  178. return len(hmac_of_value) == len(hmac_to_check) and hmac.compare_digest(hmac_of_value, hmac_to_check)
  179. def prettify_url(url, max_length=74):
  180. if len(url) > max_length:
  181. chunk_len = int(max_length / 2 + 1)
  182. return '{0}[...]{1}'.format(url[:chunk_len], url[-chunk_len:])
  183. else:
  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. else:
  219. return fr'\b({rword})(?!\w)'
  220. def highlight_content(content, query):
  221. if not content:
  222. return None
  223. # ignoring html contents
  224. # TODO better html content detection
  225. if content.find('<') != -1:
  226. return content
  227. querysplit = query.split()
  228. queries = []
  229. for qs in querysplit:
  230. qs = qs.replace("'", "").replace('"', '').replace(" ", "")
  231. if len(qs) > 0:
  232. queries.extend(re.findall(regex_highlight_cjk(qs), content, flags=re.I | re.U))
  233. if len(queries) > 0:
  234. for q in set(queries):
  235. content = re.sub(
  236. regex_highlight_cjk(q), f'<span class="highlight">{q}</span>'.replace('\\', r'\\'), content
  237. )
  238. return content
  239. def searxng_l10n_timespan(dt: datetime) -> str: # pylint: disable=invalid-name
  240. """Returns a human-readable and translated string indicating how long ago
  241. a date was in the past / the time span of the date to the present.
  242. On January 1st, midnight, the returned string only indicates how many years
  243. ago the date was.
  244. """
  245. # TODO, check if timezone is calculated right # pylint: disable=fixme
  246. d = dt.date()
  247. t = dt.time()
  248. if d.month == 1 and d.day == 1 and t.hour == 0 and t.minute == 0 and t.second == 0:
  249. return str(d.year)
  250. if dt.replace(tzinfo=None) >= datetime.now() - timedelta(days=1):
  251. timedifference = datetime.now() - dt.replace(tzinfo=None)
  252. minutes = int((timedifference.seconds / 60) % 60)
  253. hours = int(timedifference.seconds / 60 / 60)
  254. if hours == 0:
  255. return gettext('{minutes} minute(s) ago').format(minutes=minutes)
  256. return gettext('{hours} hour(s), {minutes} minute(s) ago').format(hours=hours, minutes=minutes)
  257. return format_date(dt)
  258. def is_flask_run_cmdline():
  259. """Check if the application was started using "flask run" command line
  260. Inspect the callstack.
  261. See https://github.com/pallets/flask/blob/master/src/flask/__main__.py
  262. Returns:
  263. bool: True if the application was started using "flask run".
  264. """
  265. frames = inspect.stack()
  266. if len(frames) < 2:
  267. return False
  268. return frames[-2].filename.endswith('flask/cli.py')
  269. NO_SUBGROUPING = 'without further subgrouping'
  270. def group_engines_in_tab(engines: Iterable[Engine]) -> List[Tuple[str, Iterable[Engine]]]:
  271. """Groups an Iterable of engines by their first non tab category (first subgroup)"""
  272. def get_subgroup(eng):
  273. non_tab_categories = [c for c in eng.categories if c not in tabs + [DEFAULT_CATEGORY]]
  274. return non_tab_categories[0] if len(non_tab_categories) > 0 else NO_SUBGROUPING
  275. def group_sort_key(group):
  276. return (group[0] == NO_SUBGROUPING, group[0].lower())
  277. def engine_sort_key(engine):
  278. return (engine.about.get('language', ''), engine.name)
  279. tabs = list(settings['categories_as_tabs'].keys())
  280. subgroups = itertools.groupby(sorted(engines, key=get_subgroup), get_subgroup)
  281. sorted_groups = sorted(((name, list(engines)) for name, engines in subgroups), key=group_sort_key)
  282. ret_val = []
  283. for groupname, engines in sorted_groups:
  284. group_bang = '!' + groupname.replace(' ', '_') if groupname != NO_SUBGROUPING else ''
  285. ret_val.append((groupname, group_bang, sorted(engines, key=engine_sort_key)))
  286. return ret_val