utils.py 19 KB

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