impl.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. import typing
  3. import types
  4. import functools
  5. import itertools
  6. from time import time
  7. from urllib.parse import urlparse
  8. import re
  9. import cld3
  10. import requests.exceptions
  11. from searx import poolrequests, logger
  12. from searx.results import ResultContainer
  13. from searx.search.models import SearchQuery, EngineRef
  14. from searx.search.processors import EngineProcessor
  15. HTML_TAGS = [
  16. 'embed', 'iframe', 'object', 'param', 'picture', 'source', 'svg', 'math', 'canvas', 'noscript', 'script',
  17. 'del', 'ins', 'area', 'audio', 'img', 'map', 'track', 'video', 'a', 'abbr', 'b', 'bdi', 'bdo', 'br', 'cite',
  18. 'code', 'data', 'dfn', 'em', 'i', 'kdb', 'mark', 'q', 'rb', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'small',
  19. 'span', 'strong', 'sub', 'sup', 'time', 'u', 'var', 'wbr', 'style', 'blockquote', 'dd', 'div', 'dl', 'dt',
  20. 'figcaption', 'figure', 'hr', 'li', 'ol', 'p', 'pre', 'ul', 'button', 'datalist', 'fieldset', 'form', 'input',
  21. 'label', 'legend', 'meter', 'optgroup', 'option', 'output', 'progress', 'select', 'textarea', 'applet',
  22. 'frame', 'frameset'
  23. ]
  24. def get_check_no_html():
  25. rep = ['<' + tag + '[^\>]*>' for tag in HTML_TAGS]
  26. rep += ['</' + tag + '>' for tag in HTML_TAGS]
  27. pattern = re.compile('|'.join(rep))
  28. def f(text):
  29. return pattern.search(text.lower()) is None
  30. return f
  31. _check_no_html = get_check_no_html()
  32. def _is_url(url):
  33. try:
  34. result = urlparse(url)
  35. except ValueError:
  36. return False
  37. if result.scheme not in ('http', 'https'):
  38. return False
  39. return True
  40. @functools.lru_cache(maxsize=8192)
  41. def _is_url_image(image_url):
  42. if not isinstance(image_url, str):
  43. return False
  44. if image_url.startswith('//'):
  45. image_url = 'https:' + image_url
  46. if image_url.startswith('data:'):
  47. return image_url.startswith('data:image/')
  48. if not _is_url(image_url):
  49. return False
  50. retry = 2
  51. while retry > 0:
  52. a = time()
  53. try:
  54. poolrequests.set_timeout_for_thread(10.0, time())
  55. r = poolrequests.get(image_url, timeout=10.0, allow_redirects=True, headers={
  56. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0',
  57. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  58. 'Accept-Language': 'en-US;q=0.5,en;q=0.3',
  59. 'Accept-Encoding': 'gzip, deflate, br',
  60. 'DNT': '1',
  61. 'Connection': 'keep-alive',
  62. 'Upgrade-Insecure-Requests': '1',
  63. 'Sec-GPC': '1',
  64. 'Cache-Control': 'max-age=0'
  65. })
  66. if r.headers["content-type"].startswith('image/'):
  67. return True
  68. return False
  69. except requests.exceptions.Timeout:
  70. logger.error('Timeout for %s: %i', image_url, int(time() - a))
  71. retry -= 1
  72. except requests.exceptions.RequestException:
  73. logger.exception('Exception for %s', image_url)
  74. return False
  75. def _search_query_to_dict(search_query: SearchQuery) -> typing.Dict[str, typing.Any]:
  76. return {
  77. 'query': search_query.query,
  78. 'lang': search_query.lang,
  79. 'pageno': search_query.pageno,
  80. 'safesearch': search_query.safesearch,
  81. 'time_range': search_query.time_range,
  82. }
  83. def _search_query_diff(sq1: SearchQuery, sq2: SearchQuery)\
  84. -> typing.Tuple[typing.Dict[str, typing.Any], typing.Dict[str, typing.Any]]:
  85. param1 = _search_query_to_dict(sq1)
  86. param2 = _search_query_to_dict(sq2)
  87. common = {}
  88. diff = {}
  89. for k, value1 in param1.items():
  90. value2 = param2[k]
  91. if value1 == value2:
  92. common[k] = value1
  93. else:
  94. diff[k] = (value1, value2)
  95. return (common, diff)
  96. class TestResults:
  97. __slots__ = 'errors', 'broken_urls'
  98. def __init__(self):
  99. self.errors: typing.Dict[str, typing.List[str]] = {}
  100. self.broken_urls = []
  101. def add_error(self, test, message):
  102. errors_for_test = self.errors.setdefault(test, [])
  103. if message not in errors_for_test:
  104. errors_for_test.append(message)
  105. def add_broken_url(self, url):
  106. if url not in self.broken_urls:
  107. self.broken_urls.append(url)
  108. @property
  109. def succesfull(self):
  110. return len(self.errors) == 0
  111. def __iter__(self):
  112. for test_name, errors in self.errors.items():
  113. for error in sorted(errors):
  114. yield (test_name, error)
  115. class ResultContainerTests:
  116. __slots__ = 'test_name', 'search_query', 'result_container', 'languages', 'stop_test', 'test_results'
  117. def __init__(self,
  118. test_results: TestResults,
  119. test_name: str,
  120. search_query: SearchQuery,
  121. result_container: ResultContainer):
  122. self.test_name = test_name
  123. self.search_query = search_query
  124. self.result_container = result_container
  125. self.languages: typing.Set[str] = set()
  126. self.test_results = test_results
  127. self.stop_test = False
  128. @property
  129. def result_urls(self):
  130. results = self.result_container.get_ordered_results()
  131. return [result['url'] for result in results]
  132. def _record_error(self, message: str) -> None:
  133. self.test_results.add_error(self.test_name, message)
  134. def _add_language(self, text: str) -> typing.Optional[str]:
  135. r = cld3.get_language(str(text)) # pylint: disable=E1101
  136. if r is not None and r.probability >= 0.9 and r.is_reliable:
  137. self.languages.add(r.language)
  138. return None
  139. def _check_result(self, result):
  140. if not _check_no_html(result.get('title', '')):
  141. self._record_error('HTML in title')
  142. if not _check_no_html(result.get('content', '')):
  143. self._record_error('HTML in content')
  144. self._add_language(result.get('title', ''))
  145. self._add_language(result.get('content', ''))
  146. template = result.get('template', 'default.html')
  147. if template == 'default.html':
  148. return
  149. if template == 'code.html':
  150. return
  151. if template == 'torrent.html':
  152. return
  153. if template == 'map.html':
  154. return
  155. if template == 'images.html':
  156. thumbnail_src = result.get('thumbnail_src')
  157. if thumbnail_src is not None:
  158. if not _is_url_image(thumbnail_src):
  159. self.test_results.add_broken_url(thumbnail_src)
  160. self._record_error('thumbnail_src URL is invalid')
  161. elif not _is_url_image(result.get('img_src')):
  162. self.test_results.add_broken_url(result.get('img_src'))
  163. self._record_error('img_src URL is invalid')
  164. if template == 'videos.html' and not _is_url_image(result.get('thumbnail')):
  165. self._record_error('thumbnail URL is invalid')
  166. def _check_results(self, results: list):
  167. for result in results:
  168. self._check_result(result)
  169. def _check_answers(self, answers):
  170. for answer in answers:
  171. if not _check_no_html(answer):
  172. self._record_error('HTML in answer')
  173. def _check_infoboxes(self, infoboxes):
  174. for infobox in infoboxes:
  175. if not _check_no_html(infobox.get('content', '')):
  176. self._record_error('HTML in infobox content')
  177. self._add_language(infobox.get('content', ''))
  178. for attribute in infobox.get('attributes', {}):
  179. if not _check_no_html(attribute.get('value', '')):
  180. self._record_error('HTML in infobox attribute value')
  181. def check_basic(self):
  182. if len(self.result_container.unresponsive_engines) > 0:
  183. for message in self.result_container.unresponsive_engines:
  184. self._record_error(message[1] + ' ' + (message[2] or ''))
  185. self.stop_test = True
  186. return
  187. results = self.result_container.get_ordered_results()
  188. if len(results) > 0:
  189. self._check_results(results)
  190. if len(self.result_container.answers) > 0:
  191. self._check_answers(self.result_container.answers)
  192. if len(self.result_container.infoboxes) > 0:
  193. self._check_infoboxes(self.result_container.infoboxes)
  194. def has_infobox(self):
  195. """Check the ResultContainer has at least one infobox"""
  196. if len(self.result_container.infoboxes) == 0:
  197. self._record_error('No infobox')
  198. def has_answer(self):
  199. """Check the ResultContainer has at least one answer"""
  200. if len(self.result_container.answers) == 0:
  201. self._record_error('No answer')
  202. def has_language(self, lang):
  203. """Check at least one title or content of the results is written in the `lang`.
  204. Detected using pycld3, may be not accurate"""
  205. if lang not in self.languages:
  206. self._record_error(lang + ' not found')
  207. def not_empty(self):
  208. """Check the ResultContainer has at least one answer or infobox or result"""
  209. result_types = set()
  210. results = self.result_container.get_ordered_results()
  211. if len(results) > 0:
  212. result_types.add('results')
  213. if len(self.result_container.answers) > 0:
  214. result_types.add('answers')
  215. if len(self.result_container.infoboxes) > 0:
  216. result_types.add('infoboxes')
  217. if len(result_types) == 0:
  218. self._record_error('No result')
  219. def one_title_contains(self, title: str):
  220. """Check one of the title contains `title` (case insensitive comparaison)"""
  221. title = title.lower()
  222. for result in self.result_container.get_ordered_results():
  223. if title in result['title'].lower():
  224. return
  225. self._record_error(('{!r} not found in the title'.format(title)))
  226. class CheckerTests:
  227. __slots__ = 'test_results', 'test_name', 'result_container_tests_list'
  228. def __init__(self,
  229. test_results: TestResults,
  230. test_name: str,
  231. result_container_tests_list: typing.List[ResultContainerTests]):
  232. self.test_results = test_results
  233. self.test_name = test_name
  234. self.result_container_tests_list = result_container_tests_list
  235. def unique_results(self):
  236. """Check the results of each ResultContain is unique"""
  237. urls_list = [rct.result_urls for rct in self.result_container_tests_list]
  238. if len(urls_list[0]) > 0:
  239. # results on the first page
  240. for i, urls_i in enumerate(urls_list):
  241. for j, urls_j in enumerate(urls_list):
  242. if i < j and urls_i == urls_j:
  243. common, diff = _search_query_diff(self.result_container_tests_list[i].search_query,
  244. self.result_container_tests_list[j].search_query)
  245. common_str = ' '.join(['{}={!r}'.format(k, v) for k, v in common.items()])
  246. diff1_str = ', ' .join(['{}={!r}'.format(k, v1) for (k, (v1, v2)) in diff.items()])
  247. diff2_str = ', ' .join(['{}={!r}'.format(k, v2) for (k, (v1, v2)) in diff.items()])
  248. self.test_results.add_error(self.test_name,
  249. 'results are identitical for {} and {} ({})'
  250. .format(diff1_str, diff2_str, common_str))
  251. class Checker:
  252. __slots__ = 'processor', 'tests', 'test_results'
  253. def __init__(self, processor: EngineProcessor):
  254. self.processor = processor
  255. self.tests = self.processor.get_tests()
  256. self.test_results = TestResults()
  257. @property
  258. def engineref_list(self):
  259. engine_name = self.processor.engine_name
  260. engine_category = self.processor.engine.categories[0]
  261. return [EngineRef(engine_name, engine_category)]
  262. @staticmethod
  263. def search_query_matrix_iterator(engineref_list, matrix):
  264. p = []
  265. for name, values in matrix.items():
  266. if isinstance(values, (tuple, list)):
  267. l = [(name, value) for value in values]
  268. else:
  269. l = [(name, values)]
  270. p.append(l)
  271. for kwargs in itertools.product(*p):
  272. kwargs = {k: v for k, v in kwargs}
  273. query = kwargs['query']
  274. params = dict(kwargs)
  275. del params['query']
  276. yield SearchQuery(query, engineref_list, **params)
  277. def call_test(self, obj, test_description):
  278. if isinstance(test_description, (tuple, list)):
  279. method, args = test_description[0], test_description[1:]
  280. else:
  281. method = test_description
  282. args = ()
  283. if isinstance(method, str) and hasattr(obj, method):
  284. getattr(obj, method)(*args)
  285. elif isinstance(method, types.FunctionType):
  286. method(*args)
  287. else:
  288. self.test_results.add_error(obj.test_name,
  289. 'method {!r} ({}) not found for {}'
  290. .format(method, method.__class__.__name__, obj.__class__.__name__))
  291. def call_tests(self, obj, test_descriptions):
  292. for test_description in test_descriptions:
  293. self.call_test(obj, test_description)
  294. def search(self, search_query: SearchQuery) -> ResultContainer:
  295. result_container = ResultContainer()
  296. engineref_category = search_query.engineref_list[0].category
  297. params = self.processor.get_params(search_query, engineref_category)
  298. if params is not None:
  299. self.processor.search(search_query.query, params, result_container, time(), 5)
  300. return result_container
  301. def get_result_container_tests(self, test_name: str, search_query: SearchQuery) -> ResultContainerTests:
  302. result_container = self.search(search_query)
  303. result_container_check = ResultContainerTests(self.test_results, test_name, search_query, result_container)
  304. result_container_check.check_basic()
  305. return result_container_check
  306. def run_test(self, test_name):
  307. test_parameters = self.tests[test_name]
  308. search_query_list = list(Checker.search_query_matrix_iterator(self.engineref_list, test_parameters['matrix']))
  309. rct_list = [self.get_result_container_tests(test_name, search_query) for search_query in search_query_list]
  310. stop_test = False
  311. if 'result_container' in test_parameters:
  312. for rct in rct_list:
  313. stop_test = stop_test or rct.stop_test
  314. if not rct.stop_test:
  315. self.call_tests(rct, test_parameters['result_container'])
  316. if not stop_test:
  317. if 'test' in test_parameters:
  318. checker_tests = CheckerTests(self.test_results, test_name, rct_list)
  319. self.call_tests(checker_tests, test_parameters['test'])
  320. def run(self):
  321. for test_name in self.tests:
  322. self.run_test(test_name)