utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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 XPath, _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 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. def searx_useragent():
  26. """Return the searx User Agent"""
  27. return 'searx/{searx_version} {suffix}'.format(
  28. searx_version=VERSION_STRING,
  29. suffix=settings['outgoing'].get('useragent_suffix', ''))
  30. def gen_useragent(os=None):
  31. """Return a random browser User Agent
  32. See searx/data/useragents.json
  33. """
  34. return str(USER_AGENTS['ua'].format(os=os or choice(USER_AGENTS['os']), version=choice(USER_AGENTS['versions'])))
  35. class HTMLTextExtractorException(Exception):
  36. pass
  37. class HTMLTextExtractor(HTMLParser):
  38. def __init__(self):
  39. HTMLParser.__init__(self)
  40. self.result = []
  41. self.tags = []
  42. def handle_starttag(self, tag, attrs):
  43. self.tags.append(tag)
  44. def handle_endtag(self, tag):
  45. if not self.tags:
  46. return
  47. if tag != self.tags[-1]:
  48. raise HTMLTextExtractorException()
  49. self.tags.pop()
  50. def is_valid_tag(self):
  51. return not self.tags or self.tags[-1] not in blocked_tags
  52. def handle_data(self, d):
  53. if not self.is_valid_tag():
  54. return
  55. self.result.append(d)
  56. def handle_charref(self, number):
  57. if not self.is_valid_tag():
  58. return
  59. if number[0] in ('x', 'X'):
  60. codepoint = int(number[1:], 16)
  61. else:
  62. codepoint = int(number)
  63. self.result.append(chr(codepoint))
  64. def handle_entityref(self, name):
  65. if not self.is_valid_tag():
  66. return
  67. # codepoint = htmlentitydefs.name2codepoint[name]
  68. # self.result.append(chr(codepoint))
  69. self.result.append(name)
  70. def get_text(self):
  71. return ''.join(self.result).strip()
  72. def html_to_text(html_str):
  73. """Extract text from a HTML string
  74. Args:
  75. * html_str (str): string HTML
  76. Returns:
  77. * str: extracted text
  78. Examples:
  79. >>> html_to_text('Example <span id="42">#2</span>')
  80. 'Example #2'
  81. >>> html_to_text('<style>.span { color: red; }</style><span>Example</span>')
  82. 'Example'
  83. """
  84. html_str = html_str.replace('\n', ' ')
  85. html_str = ' '.join(html_str.split())
  86. s = HTMLTextExtractor()
  87. try:
  88. s.feed(html_str)
  89. except HTMLTextExtractorException:
  90. logger.debug("HTMLTextExtractor: invalid HTML\n%s", html_str)
  91. return s.get_text()
  92. def extract_text(xpath_results):
  93. """Extract text from a lxml result
  94. * if xpath_results is list, extract the text from each result and concat the list
  95. * if xpath_results is a xml element, extract all the text node from it
  96. ( text_content() method from lxml )
  97. * if xpath_results is a string element, then it's already done
  98. """
  99. if type(xpath_results) == list:
  100. # it's list of result : concat everything using recursive call
  101. result = ''
  102. for e in xpath_results:
  103. result = result + extract_text(e)
  104. return result.strip()
  105. elif type(xpath_results) in [_ElementStringResult, _ElementUnicodeResult]:
  106. # it's a string
  107. return ''.join(xpath_results)
  108. else:
  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. def normalize_url(url, base_url):
  116. """Normalize URL: add protocol, join URL with base_url, add trailing slash if there is no path
  117. Args:
  118. * url (str): Relative URL
  119. * base_url (str): Base URL, it must be an absolute URL.
  120. Example:
  121. >>> normalize_url('https://example.com', 'http://example.com/')
  122. 'https://example.com/'
  123. >>> normalize_url('//example.com', 'http://example.com/')
  124. 'http://example.com/'
  125. >>> normalize_url('//example.com', 'https://example.com/')
  126. 'https://example.com/'
  127. >>> normalize_url('/path?a=1', 'https://example.com')
  128. 'https://example.com/path?a=1'
  129. >>> normalize_url('', 'https://example.com')
  130. 'https://example.com/'
  131. >>> normalize_url('/test', '/path')
  132. raise Exception
  133. Raises:
  134. * lxml.etree.ParserError
  135. Returns:
  136. * str: normalized URL
  137. """
  138. if url.startswith('//'):
  139. # add http or https to this kind of url //example.com/
  140. parsed_search_url = urlparse(base_url)
  141. url = '{0}:{1}'.format(parsed_search_url.scheme or 'http', url)
  142. elif url.startswith('/'):
  143. # fix relative url to the search engine
  144. url = urljoin(base_url, url)
  145. # fix relative urls that fall through the crack
  146. if '://' not in url:
  147. url = urljoin(base_url, url)
  148. parsed_url = urlparse(url)
  149. # add a / at this end of the url if there is no path
  150. if not parsed_url.netloc:
  151. raise Exception('Cannot parse url')
  152. if not parsed_url.path:
  153. url += '/'
  154. return url
  155. def extract_url(xpath_results, base_url):
  156. """Extract and normalize URL from lxml Element
  157. Args:
  158. * xpath_results (Union[List[html.HtmlElement], html.HtmlElement]): lxml Element(s)
  159. * base_url (str): Base URL
  160. Example:
  161. >>> def f(s, search_url):
  162. >>> return searx.utils.extract_url(html.fromstring(s), search_url)
  163. >>> f('<span id="42">https://example.com</span>', 'http://example.com/')
  164. 'https://example.com/'
  165. >>> f('https://example.com', 'http://example.com/')
  166. 'https://example.com/'
  167. >>> f('//example.com', 'http://example.com/')
  168. 'http://example.com/'
  169. >>> f('//example.com', 'https://example.com/')
  170. 'https://example.com/'
  171. >>> f('/path?a=1', 'https://example.com')
  172. 'https://example.com/path?a=1'
  173. >>> f('', 'https://example.com')
  174. raise lxml.etree.ParserError
  175. >>> searx.utils.extract_url([], 'https://example.com')
  176. raise Exception
  177. Raises:
  178. * Exception
  179. * lxml.etree.ParserError
  180. Returns:
  181. * str: normalized URL
  182. """
  183. if xpath_results == []:
  184. raise Exception('Empty url resultset')
  185. url = extract_text(xpath_results)
  186. return normalize_url(url, base_url)
  187. def dict_subset(d, properties):
  188. """Extract a subset of a dict
  189. Examples:
  190. >>> dict_subset({'A': 'a', 'B': 'b', 'C': 'c'}, ['A', 'C'])
  191. {'A': 'a', 'C': 'c'}
  192. >>> >> dict_subset({'A': 'a', 'B': 'b', 'C': 'c'}, ['A', 'D'])
  193. {'A': 'a'}
  194. """
  195. result = {}
  196. for k in properties:
  197. if k in d:
  198. result[k] = d[k]
  199. return result
  200. def list_get(a_list, index, default=None):
  201. """Get element in list or default value
  202. Examples:
  203. >>> list_get(['A', 'B', 'C'], 0)
  204. 'A'
  205. >>> list_get(['A', 'B', 'C'], 3)
  206. None
  207. >>> list_get(['A', 'B', 'C'], 3, 'default')
  208. 'default'
  209. >>> list_get(['A', 'B', 'C'], -1)
  210. 'C'
  211. """
  212. if len(a_list) > index:
  213. return a_list[index]
  214. else:
  215. return default
  216. def get_torrent_size(filesize, filesize_multiplier):
  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. filesize = float(filesize)
  231. if filesize_multiplier == 'TB':
  232. filesize = int(filesize * 1024 * 1024 * 1024 * 1024)
  233. elif filesize_multiplier == 'GB':
  234. filesize = int(filesize * 1024 * 1024 * 1024)
  235. elif filesize_multiplier == 'MB':
  236. filesize = int(filesize * 1024 * 1024)
  237. elif filesize_multiplier == 'KB':
  238. filesize = int(filesize * 1024)
  239. elif filesize_multiplier == 'TiB':
  240. filesize = int(filesize * 1000 * 1000 * 1000 * 1000)
  241. elif filesize_multiplier == 'GiB':
  242. filesize = int(filesize * 1000 * 1000 * 1000)
  243. elif filesize_multiplier == 'MiB':
  244. filesize = int(filesize * 1000 * 1000)
  245. elif filesize_multiplier == 'KiB':
  246. filesize = int(filesize * 1000)
  247. except:
  248. filesize = None
  249. return filesize
  250. def convert_str_to_int(number_str):
  251. """Convert number_str to int or 0 if number_str is not a number."""
  252. if number_str.isdigit():
  253. return int(number_str)
  254. else:
  255. return 0
  256. def int_or_zero(num):
  257. """Convert num to int or 0. num can be either a str or a list.
  258. If num is a list, the first element is converted to int (or return 0 if the list is empty).
  259. If num is a str, see convert_str_to_int
  260. """
  261. if isinstance(num, list):
  262. if len(num) < 1:
  263. return 0
  264. num = num[0]
  265. return convert_str_to_int(num)
  266. def is_valid_lang(lang):
  267. """Return language code and name if lang describe a language.
  268. Examples:
  269. >>> is_valid_lang('zz')
  270. False
  271. >>> is_valid_lang('uk')
  272. (True, 'uk', 'ukrainian')
  273. >>> is_valid_lang(b'uk')
  274. (True, 'uk', 'ukrainian')
  275. >>> is_valid_lang('en')
  276. (True, 'en', 'english')
  277. >>> searx.utils.is_valid_lang('Español')
  278. (True, 'es', 'spanish')
  279. >>> searx.utils.is_valid_lang('Spanish')
  280. (True, 'es', 'spanish')
  281. """
  282. if isinstance(lang, bytes):
  283. lang = lang.decode()
  284. is_abbr = (len(lang) == 2)
  285. lang = lang.lower()
  286. if is_abbr:
  287. for l in language_codes:
  288. if l[0][:2] == lang:
  289. return (True, l[0][:2], l[3].lower())
  290. return False
  291. else:
  292. for l in language_codes:
  293. if l[1].lower() == lang or l[3].lower() == lang:
  294. return (True, l[0][:2], l[3].lower())
  295. return False
  296. def _get_lang_to_lc_dict(lang_list):
  297. key = str(lang_list)
  298. value = lang_to_lc_cache.get(key, None)
  299. if value is None:
  300. value = dict()
  301. for lc in lang_list:
  302. value.setdefault(lc.split('-')[0], lc)
  303. lang_to_lc_cache[key] = value
  304. return value
  305. def _match_language(lang_code, lang_list=[], custom_aliases={}):
  306. """auxiliary function to match lang_code in lang_list"""
  307. # replace language code with a custom alias if necessary
  308. if lang_code in custom_aliases:
  309. lang_code = custom_aliases[lang_code]
  310. if lang_code in lang_list:
  311. return lang_code
  312. # try to get the most likely country for this language
  313. subtags = get_global('likely_subtags').get(lang_code)
  314. if subtags:
  315. subtag_parts = subtags.split('_')
  316. new_code = subtag_parts[0] + '-' + subtag_parts[-1]
  317. if new_code in custom_aliases:
  318. new_code = custom_aliases[new_code]
  319. if new_code in lang_list:
  320. return new_code
  321. # try to get the any supported country for this language
  322. return _get_lang_to_lc_dict(lang_list).get(lang_code, None)
  323. def match_language(locale_code, lang_list=[], custom_aliases={}, fallback='en-US'):
  324. """get the language code from lang_list that best matches locale_code"""
  325. # try to get language from given locale_code
  326. language = _match_language(locale_code, lang_list, custom_aliases)
  327. if language:
  328. return language
  329. locale_parts = locale_code.split('-')
  330. lang_code = locale_parts[0]
  331. # try to get language using an equivalent country code
  332. if len(locale_parts) > 1:
  333. country_alias = get_global('territory_aliases').get(locale_parts[-1])
  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_global('language_aliases').get(lang_code)
  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. if modname in sys.modules:
  351. del sys.modules[modname]
  352. filepath = join(module_dir, filename)
  353. # and https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
  354. spec = importlib.util.spec_from_file_location(modname, filepath)
  355. module = importlib.util.module_from_spec(spec)
  356. sys.modules[modname] = module
  357. spec.loader.exec_module(module)
  358. return module
  359. def to_string(obj):
  360. """Convert obj to its string representation."""
  361. if isinstance(obj, str):
  362. return obj
  363. if isinstance(obj, Number):
  364. return str(obj)
  365. if hasattr(obj, '__str__'):
  366. return obj.__str__()
  367. if hasattr(obj, '__repr__'):
  368. return obj.__repr__()
  369. def ecma_unescape(s):
  370. """Python implementation of the unescape javascript function
  371. https://www.ecma-international.org/ecma-262/6.0/#sec-unescape-string
  372. https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/unescape
  373. Examples:
  374. >>> ecma_unescape('%u5409')
  375. '吉'
  376. >>> ecma_unescape('%20')
  377. ' '
  378. >>> ecma_unescape('%F3')
  379. 'ó'
  380. """
  381. # "%u5409" becomes "吉"
  382. s = ecma_unescape4_re.sub(lambda e: chr(int(e.group(1), 16)), s)
  383. # "%20" becomes " ", "%F3" becomes "ó"
  384. s = ecma_unescape2_re.sub(lambda e: chr(int(e.group(1), 16)), s)
  385. return s
  386. def get_string_replaces_function(replaces):
  387. rep = {re.escape(k): v for k, v in replaces.items()}
  388. pattern = re.compile("|".join(rep.keys()))
  389. def f(text):
  390. return pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
  391. return f
  392. def get_engine_from_settings(name):
  393. """Return engine configuration from settings.yml of a given engine name"""
  394. if 'engines' not in settings:
  395. return {}
  396. for engine in settings['engines']:
  397. if 'name' not in engine:
  398. continue
  399. if name == engine['name']:
  400. return engine
  401. return {}
  402. def get_xpath(xpath_str):
  403. """Return cached compiled XPath
  404. There is no thread lock.
  405. Worst case scenario, xpath_str is compiled more than one time.
  406. """
  407. result = xpath_cache.get(xpath_str, None)
  408. if result is None:
  409. result = XPath(xpath_str)
  410. xpath_cache[xpath_str] = result
  411. return result
  412. def eval_xpath(element, xpath_str):
  413. """Equivalent of element.xpath(xpath_str) but compile xpath_str once for all."""
  414. xpath = get_xpath(xpath_str)
  415. return xpath(element)