utils.py 19 KB

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