utils.py 20 KB

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