utils.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. # pyright: basic
  4. """Utility functions for the engines
  5. """
  6. import re
  7. import importlib
  8. import importlib.util
  9. import types
  10. from typing import Optional, Union, Any, Set, List, Dict, MutableMapping, Tuple, Callable
  11. from numbers import Number
  12. from os.path import splitext, join
  13. from random import choice
  14. from html.parser import HTMLParser
  15. from urllib.parse import urljoin, urlparse
  16. from lxml import html
  17. from lxml.etree import ElementBase, XPath, XPathError, XPathSyntaxError, _ElementStringResult, _ElementUnicodeResult
  18. from babel.core import get_global
  19. from searx import settings
  20. from searx.data import USER_AGENTS
  21. from searx.version import VERSION_TAG
  22. from searx.languages import language_codes
  23. from searx.exceptions import SearxXPathSyntaxException, SearxEngineXPathException
  24. from searx import logger
  25. logger = logger.getChild('utils')
  26. XPathSpecType = Union[str, XPath]
  27. _BLOCKED_TAGS = ('script', 'style')
  28. _ECMA_UNESCAPE4_RE = re.compile(r'%u([0-9a-fA-F]{4})', re.UNICODE)
  29. _ECMA_UNESCAPE2_RE = re.compile(r'%([0-9a-fA-F]{2})', re.UNICODE)
  30. _STORAGE_UNIT_VALUE: Dict[str, int] = {
  31. 'TB': 1024 * 1024 * 1024 * 1024,
  32. 'GB': 1024 * 1024 * 1024,
  33. 'MB': 1024 * 1024,
  34. 'TiB': 1000 * 1000 * 1000 * 1000,
  35. 'MiB': 1000 * 1000,
  36. 'KiB': 1000,
  37. }
  38. _XPATH_CACHE: Dict[str, XPath] = {}
  39. _LANG_TO_LC_CACHE: Dict[str, Dict[str, str]] = {}
  40. class _NotSetClass: # pylint: disable=too-few-public-methods
  41. """Internal class for this module, do not create instance of this class.
  42. Replace the None value, allow explicitly pass None as a function argument"""
  43. _NOTSET = _NotSetClass()
  44. def searx_useragent() -> str:
  45. """Return the searx User Agent"""
  46. return 'searx/{searx_version} {suffix}'.format(
  47. searx_version=VERSION_TAG, suffix=settings['outgoing']['useragent_suffix']
  48. ).strip()
  49. def gen_useragent(os_string: Optional[str] = None) -> str:
  50. """Return a random browser User Agent
  51. See searx/data/useragents.json
  52. """
  53. return USER_AGENTS['ua'].format(os=os_string or choice(USER_AGENTS['os']), version=choice(USER_AGENTS['versions']))
  54. class _HTMLTextExtractorException(Exception):
  55. """Internal exception raised when the HTML is invalid"""
  56. class _HTMLTextExtractor(HTMLParser): # pylint: disable=W0223 # (see https://bugs.python.org/issue31844)
  57. """Internal class to extract text from HTML"""
  58. def __init__(self):
  59. HTMLParser.__init__(self)
  60. self.result = []
  61. self.tags = []
  62. def handle_starttag(self, tag, attrs):
  63. self.tags.append(tag)
  64. if tag == 'br':
  65. self.result.append(' ')
  66. def handle_endtag(self, tag):
  67. if not self.tags:
  68. return
  69. if tag != self.tags[-1]:
  70. raise _HTMLTextExtractorException()
  71. self.tags.pop()
  72. def is_valid_tag(self):
  73. return not self.tags or self.tags[-1] not in _BLOCKED_TAGS
  74. def handle_data(self, data):
  75. if not self.is_valid_tag():
  76. return
  77. self.result.append(data)
  78. def handle_charref(self, name):
  79. if not self.is_valid_tag():
  80. return
  81. if name[0] in ('x', 'X'):
  82. codepoint = int(name[1:], 16)
  83. else:
  84. codepoint = int(name)
  85. self.result.append(chr(codepoint))
  86. def handle_entityref(self, name):
  87. if not self.is_valid_tag():
  88. return
  89. # codepoint = htmlentitydefs.name2codepoint[name]
  90. # self.result.append(chr(codepoint))
  91. self.result.append(name)
  92. def get_text(self):
  93. return ''.join(self.result).strip()
  94. def html_to_text(html_str: str) -> str:
  95. """Extract text from a HTML string
  96. Args:
  97. * html_str (str): string HTML
  98. Returns:
  99. * str: extracted text
  100. Examples:
  101. >>> html_to_text('Example <span id="42">#2</span>')
  102. 'Example #2'
  103. >>> html_to_text('<style>.span { color: red; }</style><span>Example</span>')
  104. 'Example'
  105. """
  106. html_str = html_str.replace('\n', ' ').replace('\r', ' ')
  107. html_str = ' '.join(html_str.split())
  108. s = _HTMLTextExtractor()
  109. try:
  110. s.feed(html_str)
  111. except _HTMLTextExtractorException:
  112. logger.debug("HTMLTextExtractor: invalid HTML\n%s", html_str)
  113. return s.get_text()
  114. def extract_text(xpath_results, allow_none: bool = False) -> Optional[str]:
  115. """Extract text from a lxml result
  116. * if xpath_results is list, extract the text from each result and concat the list
  117. * if xpath_results is a xml element, extract all the text node from it
  118. ( text_content() method from lxml )
  119. * if xpath_results is a string element, then it's already done
  120. """
  121. if isinstance(xpath_results, list):
  122. # it's list of result : concat everything using recursive call
  123. result = ''
  124. for e in xpath_results:
  125. result = result + (extract_text(e) or '')
  126. return result.strip()
  127. if isinstance(xpath_results, ElementBase):
  128. # it's a element
  129. text: str = html.tostring(xpath_results, encoding='unicode', method='text', with_tail=False)
  130. text = text.strip().replace('\n', ' ')
  131. return ' '.join(text.split())
  132. if isinstance(xpath_results, (_ElementStringResult, _ElementUnicodeResult, str, Number, bool)):
  133. return str(xpath_results)
  134. if xpath_results is None and allow_none:
  135. return None
  136. if xpath_results is None and not allow_none:
  137. raise ValueError('extract_text(None, allow_none=False)')
  138. raise ValueError('unsupported type')
  139. def normalize_url(url: str, base_url: str) -> str:
  140. """Normalize URL: add protocol, join URL with base_url, add trailing slash if there is no path
  141. Args:
  142. * url (str): Relative URL
  143. * base_url (str): Base URL, it must be an absolute URL.
  144. Example:
  145. >>> normalize_url('https://example.com', 'http://example.com/')
  146. 'https://example.com/'
  147. >>> normalize_url('//example.com', 'http://example.com/')
  148. 'http://example.com/'
  149. >>> normalize_url('//example.com', 'https://example.com/')
  150. 'https://example.com/'
  151. >>> normalize_url('/path?a=1', 'https://example.com')
  152. 'https://example.com/path?a=1'
  153. >>> normalize_url('', 'https://example.com')
  154. 'https://example.com/'
  155. >>> normalize_url('/test', '/path')
  156. raise ValueError
  157. Raises:
  158. * lxml.etree.ParserError
  159. Returns:
  160. * str: normalized URL
  161. """
  162. if url.startswith('//'):
  163. # add http or https to this kind of url //example.com/
  164. parsed_search_url = urlparse(base_url)
  165. url = '{0}:{1}'.format(parsed_search_url.scheme or 'http', url)
  166. elif url.startswith('/'):
  167. # fix relative url to the search engine
  168. url = urljoin(base_url, url)
  169. # fix relative urls that fall through the crack
  170. if '://' not in url:
  171. url = urljoin(base_url, url)
  172. parsed_url = urlparse(url)
  173. # add a / at this end of the url if there is no path
  174. if not parsed_url.netloc:
  175. raise ValueError('Cannot parse url')
  176. if not parsed_url.path:
  177. url += '/'
  178. return url
  179. def extract_url(xpath_results, base_url) -> str:
  180. """Extract and normalize URL from lxml Element
  181. Args:
  182. * xpath_results (Union[List[html.HtmlElement], html.HtmlElement]): lxml Element(s)
  183. * base_url (str): Base URL
  184. Example:
  185. >>> def f(s, search_url):
  186. >>> return searx.utils.extract_url(html.fromstring(s), search_url)
  187. >>> f('<span id="42">https://example.com</span>', 'http://example.com/')
  188. 'https://example.com/'
  189. >>> f('https://example.com', 'http://example.com/')
  190. 'https://example.com/'
  191. >>> f('//example.com', 'http://example.com/')
  192. 'http://example.com/'
  193. >>> f('//example.com', 'https://example.com/')
  194. 'https://example.com/'
  195. >>> f('/path?a=1', 'https://example.com')
  196. 'https://example.com/path?a=1'
  197. >>> f('', 'https://example.com')
  198. raise lxml.etree.ParserError
  199. >>> searx.utils.extract_url([], 'https://example.com')
  200. raise ValueError
  201. Raises:
  202. * ValueError
  203. * lxml.etree.ParserError
  204. Returns:
  205. * str: normalized URL
  206. """
  207. if xpath_results == []:
  208. raise ValueError('Empty url resultset')
  209. url = extract_text(xpath_results)
  210. if url:
  211. return normalize_url(url, base_url)
  212. raise ValueError('URL not found')
  213. def dict_subset(dictionary: MutableMapping, properties: Set[str]) -> Dict:
  214. """Extract a subset of a dict
  215. Examples:
  216. >>> dict_subset({'A': 'a', 'B': 'b', 'C': 'c'}, ['A', 'C'])
  217. {'A': 'a', 'C': 'c'}
  218. >>> >> dict_subset({'A': 'a', 'B': 'b', 'C': 'c'}, ['A', 'D'])
  219. {'A': 'a'}
  220. """
  221. return {k: dictionary[k] for k in properties if k in dictionary}
  222. def get_torrent_size(filesize: str, filesize_multiplier: str) -> Optional[int]:
  223. """
  224. Args:
  225. * filesize (str): size
  226. * filesize_multiplier (str): TB, GB, .... TiB, GiB...
  227. Returns:
  228. * int: number of bytes
  229. Example:
  230. >>> get_torrent_size('5', 'GB')
  231. 5368709120
  232. >>> get_torrent_size('3.14', 'MiB')
  233. 3140000
  234. """
  235. try:
  236. multiplier = _STORAGE_UNIT_VALUE.get(filesize_multiplier, 1)
  237. return int(float(filesize) * multiplier)
  238. except ValueError:
  239. return None
  240. def convert_str_to_int(number_str: str) -> int:
  241. """Convert number_str to int or 0 if number_str is not a number."""
  242. if number_str.isdigit():
  243. return int(number_str)
  244. return 0
  245. def int_or_zero(num: Union[List[str], str]) -> int:
  246. """Convert num to int or 0. num can be either a str or a list.
  247. If num is a list, the first element is converted to int (or return 0 if the list is empty).
  248. If num is a str, see convert_str_to_int
  249. """
  250. if isinstance(num, list):
  251. if len(num) < 1:
  252. return 0
  253. num = num[0]
  254. return convert_str_to_int(num)
  255. def is_valid_lang(lang) -> Optional[Tuple[bool, str, str]]:
  256. """Return language code and name if lang describe a language.
  257. Examples:
  258. >>> is_valid_lang('zz')
  259. None
  260. >>> is_valid_lang('uk')
  261. (True, 'uk', 'ukrainian')
  262. >>> is_valid_lang(b'uk')
  263. (True, 'uk', 'ukrainian')
  264. >>> is_valid_lang('en')
  265. (True, 'en', 'english')
  266. >>> searx.utils.is_valid_lang('Español')
  267. (True, 'es', 'spanish')
  268. >>> searx.utils.is_valid_lang('Spanish')
  269. (True, 'es', 'spanish')
  270. """
  271. if isinstance(lang, bytes):
  272. lang = lang.decode()
  273. is_abbr = len(lang) == 2
  274. lang = lang.lower()
  275. if is_abbr:
  276. for l in language_codes:
  277. if l[0][:2] == lang:
  278. return (True, l[0][:2], l[3].lower())
  279. return None
  280. for l in language_codes:
  281. if l[1].lower() == lang or l[3].lower() == lang:
  282. return (True, l[0][:2], l[3].lower())
  283. return None
  284. def _get_lang_to_lc_dict(lang_list: List[str]) -> Dict[str, str]:
  285. key = str(lang_list)
  286. value = _LANG_TO_LC_CACHE.get(key, None)
  287. if value is None:
  288. value = {}
  289. for lang in lang_list:
  290. value.setdefault(lang.split('-')[0], lang)
  291. _LANG_TO_LC_CACHE[key] = value
  292. return value
  293. # babel's get_global contains all sorts of miscellaneous locale and territory related data
  294. # see get_global in: https://github.com/python-babel/babel/blob/master/babel/core.py
  295. def _get_from_babel(lang_code: str, key):
  296. match = get_global(key).get(lang_code.replace('-', '_'))
  297. # for some keys, such as territory_aliases, match may be a list
  298. if isinstance(match, str):
  299. return match.replace('_', '-')
  300. return match
  301. def _match_language(lang_code: str, lang_list=[], custom_aliases={}) -> Optional[str]: # pylint: disable=W0102
  302. """auxiliary function to match lang_code in lang_list"""
  303. # replace language code with a custom alias if necessary
  304. if lang_code in custom_aliases:
  305. lang_code = custom_aliases[lang_code]
  306. if lang_code in lang_list:
  307. return lang_code
  308. # try to get the most likely country for this language
  309. subtags = _get_from_babel(lang_code, 'likely_subtags')
  310. if subtags:
  311. if subtags in lang_list:
  312. return subtags
  313. subtag_parts = subtags.split('-')
  314. new_code = subtag_parts[0] + '-' + subtag_parts[-1]
  315. if new_code in custom_aliases:
  316. new_code = custom_aliases[new_code]
  317. if new_code in lang_list:
  318. return new_code
  319. # try to get the any supported country for this language
  320. return _get_lang_to_lc_dict(lang_list).get(lang_code)
  321. def match_language( # pylint: disable=W0102
  322. locale_code, lang_list=[], custom_aliases={}, fallback: Optional[str] = 'en-US'
  323. ) -> Optional[str]:
  324. """get the language code from lang_list that best matches locale_code"""
  325. # try to get language from given locale_code
  326. language = _match_language(locale_code, lang_list, custom_aliases)
  327. if language:
  328. return language
  329. locale_parts = locale_code.split('-')
  330. lang_code = locale_parts[0]
  331. # if locale_code has script, try matching without it
  332. if len(locale_parts) > 2:
  333. language = _match_language(lang_code + '-' + locale_parts[-1], lang_list, custom_aliases)
  334. if language:
  335. return language
  336. # try to get language using an equivalent country code
  337. if len(locale_parts) > 1:
  338. country_alias = _get_from_babel(locale_parts[-1], 'territory_aliases')
  339. if country_alias:
  340. language = _match_language(lang_code + '-' + country_alias[0], lang_list, custom_aliases)
  341. if language:
  342. return language
  343. # try to get language using an equivalent language code
  344. alias = _get_from_babel(lang_code, 'language_aliases')
  345. if alias:
  346. language = _match_language(alias, lang_list, custom_aliases)
  347. if language:
  348. return language
  349. if lang_code != locale_code:
  350. # try to get language from given language without giving the country
  351. language = _match_language(lang_code, lang_list, custom_aliases)
  352. return language or fallback
  353. def load_module(filename: str, module_dir: str) -> types.ModuleType:
  354. modname = splitext(filename)[0]
  355. modpath = join(module_dir, filename)
  356. # and https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
  357. spec = importlib.util.spec_from_file_location(modname, modpath)
  358. if not spec:
  359. raise ValueError(f"Error loading '{modpath}' module")
  360. module = importlib.util.module_from_spec(spec)
  361. if not spec.loader:
  362. raise ValueError(f"Error loading '{modpath}' module")
  363. spec.loader.exec_module(module)
  364. return module
  365. def to_string(obj: Any) -> str:
  366. """Convert obj to its string representation."""
  367. if isinstance(obj, str):
  368. return obj
  369. if hasattr(obj, '__str__'):
  370. return str(obj)
  371. return repr(obj)
  372. def ecma_unescape(string: str) -> str:
  373. """Python implementation of the unescape javascript function
  374. https://www.ecma-international.org/ecma-262/6.0/#sec-unescape-string
  375. https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/unescape
  376. Examples:
  377. >>> ecma_unescape('%u5409')
  378. '吉'
  379. >>> ecma_unescape('%20')
  380. ' '
  381. >>> ecma_unescape('%F3')
  382. 'ó'
  383. """
  384. # "%u5409" becomes "吉"
  385. string = _ECMA_UNESCAPE4_RE.sub(lambda e: chr(int(e.group(1), 16)), string)
  386. # "%20" becomes " ", "%F3" becomes "ó"
  387. string = _ECMA_UNESCAPE2_RE.sub(lambda e: chr(int(e.group(1), 16)), string)
  388. return string
  389. def get_string_replaces_function(replaces: Dict[str, str]) -> Callable[[str], str]:
  390. rep = {re.escape(k): v for k, v in replaces.items()}
  391. pattern = re.compile("|".join(rep.keys()))
  392. def func(text):
  393. return pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
  394. return func
  395. def get_engine_from_settings(name: str) -> Dict:
  396. """Return engine configuration from settings.yml of a given engine name"""
  397. if 'engines' not in settings:
  398. return {}
  399. for engine in settings['engines']:
  400. if 'name' not in engine:
  401. continue
  402. if name == engine['name']:
  403. return engine
  404. return {}
  405. def get_xpath(xpath_spec: XPathSpecType) -> XPath:
  406. """Return cached compiled XPath
  407. There is no thread lock.
  408. Worst case scenario, xpath_str is compiled more than one time.
  409. Args:
  410. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath
  411. Returns:
  412. * result (bool, float, list, str): Results.
  413. Raises:
  414. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  415. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  416. """
  417. if isinstance(xpath_spec, str):
  418. result = _XPATH_CACHE.get(xpath_spec, None)
  419. if result is None:
  420. try:
  421. result = XPath(xpath_spec)
  422. except XPathSyntaxError as e:
  423. raise SearxXPathSyntaxException(xpath_spec, str(e.msg)) from e
  424. _XPATH_CACHE[xpath_spec] = result
  425. return result
  426. if isinstance(xpath_spec, XPath):
  427. return xpath_spec
  428. raise TypeError('xpath_spec must be either a str or a lxml.etree.XPath')
  429. def eval_xpath(element: ElementBase, xpath_spec: XPathSpecType):
  430. """Equivalent of element.xpath(xpath_str) but compile xpath_str once for all.
  431. See https://lxml.de/xpathxslt.html#xpath-return-values
  432. Args:
  433. * element (ElementBase): [description]
  434. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath
  435. Returns:
  436. * result (bool, float, list, str): Results.
  437. Raises:
  438. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  439. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  440. * SearxEngineXPathException: Raise when the XPath can't be evaluated.
  441. """
  442. xpath = get_xpath(xpath_spec)
  443. try:
  444. return xpath(element)
  445. except XPathError as e:
  446. arg = ' '.join([str(i) for i in e.args])
  447. raise SearxEngineXPathException(xpath_spec, arg) from e
  448. def eval_xpath_list(element: ElementBase, xpath_spec: XPathSpecType, min_len: Optional[int] = None):
  449. """Same as eval_xpath, check if the result is a list
  450. Args:
  451. * element (ElementBase): [description]
  452. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath
  453. * min_len (int, optional): [description]. Defaults to None.
  454. Raises:
  455. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  456. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  457. * SearxEngineXPathException: raise if the result is not a list
  458. Returns:
  459. * result (bool, float, list, str): Results.
  460. """
  461. result = eval_xpath(element, xpath_spec)
  462. if not isinstance(result, list):
  463. raise SearxEngineXPathException(xpath_spec, 'the result is not a list')
  464. if min_len is not None and min_len > len(result):
  465. raise SearxEngineXPathException(xpath_spec, 'len(xpath_str) < ' + str(min_len))
  466. return result
  467. def eval_xpath_getindex(elements: ElementBase, xpath_spec: XPathSpecType, index: int, default=_NOTSET):
  468. """Call eval_xpath_list then get one element using the index parameter.
  469. If the index does not exist, either aise an exception is default is not set,
  470. other return the default value (can be None).
  471. Args:
  472. * elements (ElementBase): lxml element to apply the xpath.
  473. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath.
  474. * index (int): index to get
  475. * default (Object, optional): Defaults if index doesn't exist.
  476. Raises:
  477. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  478. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  479. * SearxEngineXPathException: if the index is not found. Also see eval_xpath.
  480. Returns:
  481. * result (bool, float, list, str): Results.
  482. """
  483. result = eval_xpath_list(elements, xpath_spec)
  484. if -len(result) <= index < len(result):
  485. return result[index]
  486. if default == _NOTSET:
  487. # raise an SearxEngineXPathException instead of IndexError
  488. # to record xpath_spec
  489. raise SearxEngineXPathException(xpath_spec, 'index ' + str(index) + ' not found')
  490. return default