utils.py 20 KB

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