utils.py 19 KB

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