utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import sys
  4. import re
  5. import json
  6. from imp import load_source
  7. from numbers import Number
  8. from os.path import splitext, join
  9. from io import open
  10. from random import choice
  11. from html.parser import HTMLParser
  12. from urllib.parse import urljoin, urlparse, unquote
  13. from lxml import html
  14. from lxml.etree import XPath, _ElementStringResult, _ElementUnicodeResult
  15. from babel.core import get_global
  16. from searx import settings
  17. from searx.version import VERSION_STRING
  18. from searx.languages import language_codes
  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. useragents = json.loads(open(os.path.dirname(os.path.realpath(__file__))
  26. + "/data/useragents.json", 'r', encoding='utf-8').read())
  27. xpath_cache = dict()
  28. lang_to_lc_cache = dict()
  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(useragents['ua'].format(os=os or choice(useragents['os']), version=choice(useragents['versions'])))
  39. class HTMLTextExtractorException(Exception):
  40. pass
  41. class HTMLTextExtractor(HTMLParser):
  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, d):
  57. if not self.is_valid_tag():
  58. return
  59. self.result.append(d)
  60. def handle_charref(self, number):
  61. if not self.is_valid_tag():
  62. return
  63. if number[0] in ('x', 'X'):
  64. codepoint = int(number[1:], 16)
  65. else:
  66. codepoint = int(number)
  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):
  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 type(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 type(xpath_results) in [_ElementStringResult, _ElementUnicodeResult]:
  110. # it's a string
  111. return ''.join(xpath_results)
  112. else:
  113. # it's a element
  114. text = html.tostring(
  115. xpath_results, encoding='unicode', method='text', with_tail=False
  116. )
  117. text = text.strip().replace('\n', ' ')
  118. return ' '.join(text.split())
  119. def normalize_url(url, base_url):
  120. """Normalize URL: add protocol, join URL with base_url, add trailing slash if there is no path
  121. Args:
  122. * url (str): Relative URL
  123. * base_url (str): Base URL, it must be an absolute URL.
  124. Example:
  125. >>> normalize_url('https://example.com', 'http://example.com/')
  126. 'https://example.com/'
  127. >>> normalize_url('//example.com', 'http://example.com/')
  128. 'http://example.com/'
  129. >>> normalize_url('//example.com', 'https://example.com/')
  130. 'https://example.com/'
  131. >>> normalize_url('/path?a=1', 'https://example.com')
  132. 'https://example.com/path?a=1'
  133. >>> normalize_url('', 'https://example.com')
  134. 'https://example.com/'
  135. >>> normalize_url('/test', '/path')
  136. raise Exception
  137. Raises:
  138. * lxml.etree.ParserError
  139. Returns:
  140. * str: normalized URL
  141. """
  142. if url.startswith('//'):
  143. # add http or https to this kind of url //example.com/
  144. parsed_search_url = urlparse(base_url)
  145. url = '{0}:{1}'.format(parsed_search_url.scheme or 'http', url)
  146. elif url.startswith('/'):
  147. # fix relative url to the search engine
  148. url = urljoin(base_url, url)
  149. # fix relative urls that fall through the crack
  150. if '://' not in url:
  151. url = urljoin(base_url, url)
  152. parsed_url = urlparse(url)
  153. # add a / at this end of the url if there is no path
  154. if not parsed_url.netloc:
  155. raise Exception('Cannot parse url')
  156. if not parsed_url.path:
  157. url += '/'
  158. return url
  159. def extract_url(xpath_results, base_url):
  160. """Extract and normalize URL from lxml Element
  161. Args:
  162. * xpath_results (Union[List[html.HtmlElement], html.HtmlElement]): lxml Element(s)
  163. * base_url (str): Base URL
  164. Example:
  165. >>> def f(s, search_url):
  166. >>> return searx.utils.extract_url(html.fromstring(s), search_url)
  167. >>> f('<span id="42">https://example.com</span>', 'http://example.com/')
  168. 'https://example.com/'
  169. >>> f('https://example.com', 'http://example.com/')
  170. 'https://example.com/'
  171. >>> f('//example.com', 'http://example.com/')
  172. 'http://example.com/'
  173. >>> f('//example.com', 'https://example.com/')
  174. 'https://example.com/'
  175. >>> f('/path?a=1', 'https://example.com')
  176. 'https://example.com/path?a=1'
  177. >>> f('', 'https://example.com')
  178. raise lxml.etree.ParserError
  179. >>> searx.utils.extract_url([], 'https://example.com')
  180. raise Exception
  181. Raises:
  182. * Exception
  183. * lxml.etree.ParserError
  184. Returns:
  185. * str: normalized URL
  186. """
  187. if xpath_results == []:
  188. raise Exception('Empty url resultset')
  189. url = extract_text(xpath_results)
  190. return normalize_url(url, base_url)
  191. def dict_subset(d, properties):
  192. """Extract a subset of a dict
  193. Examples:
  194. >>> dict_subset({'A': 'a', 'B': 'b', 'C': 'c'}, ['A', 'C'])
  195. {'A': 'a', 'C': 'c'}
  196. >>> >> dict_subset({'A': 'a', 'B': 'b', 'C': 'c'}, ['A', 'D'])
  197. {'A': 'a'}
  198. """
  199. result = {}
  200. for k in properties:
  201. if k in d:
  202. result[k] = d[k]
  203. return result
  204. def list_get(a_list, index, default=None):
  205. """Get element in list or default value
  206. Examples:
  207. >>> list_get(['A', 'B', 'C'], 0)
  208. 'A'
  209. >>> list_get(['A', 'B', 'C'], 3)
  210. None
  211. >>> list_get(['A', 'B', 'C'], 3, 'default')
  212. 'default'
  213. >>> list_get(['A', 'B', 'C'], -1)
  214. 'C'
  215. """
  216. if len(a_list) > index:
  217. return a_list[index]
  218. else:
  219. return default
  220. def get_torrent_size(filesize, filesize_multiplier):
  221. """
  222. Args:
  223. * filesize (str): size
  224. * filesize_multiplier (str): TB, GB, .... TiB, GiB...
  225. Returns:
  226. * int: number of bytes
  227. Example:
  228. >>> get_torrent_size('5', 'GB')
  229. 5368709120
  230. >>> get_torrent_size('3.14', 'MiB')
  231. 3140000
  232. """
  233. try:
  234. filesize = float(filesize)
  235. if filesize_multiplier == 'TB':
  236. filesize = int(filesize * 1024 * 1024 * 1024 * 1024)
  237. elif filesize_multiplier == 'GB':
  238. filesize = int(filesize * 1024 * 1024 * 1024)
  239. elif filesize_multiplier == 'MB':
  240. filesize = int(filesize * 1024 * 1024)
  241. elif filesize_multiplier == 'KB':
  242. filesize = int(filesize * 1024)
  243. elif filesize_multiplier == 'TiB':
  244. filesize = int(filesize * 1000 * 1000 * 1000 * 1000)
  245. elif filesize_multiplier == 'GiB':
  246. filesize = int(filesize * 1000 * 1000 * 1000)
  247. elif filesize_multiplier == 'MiB':
  248. filesize = int(filesize * 1000 * 1000)
  249. elif filesize_multiplier == 'KiB':
  250. filesize = int(filesize * 1000)
  251. except:
  252. filesize = None
  253. return filesize
  254. def convert_str_to_int(number_str):
  255. """Convert number_str to int or 0 if number_str is not a number."""
  256. if number_str.isdigit():
  257. return int(number_str)
  258. else:
  259. return 0
  260. def int_or_zero(num):
  261. """Convert num to int or 0. num can be either a str or a list.
  262. If num is a list, the first element is converted to int (or return 0 if the list is empty).
  263. If num is a str, see convert_str_to_int
  264. """
  265. if isinstance(num, list):
  266. if len(num) < 1:
  267. return 0
  268. num = num[0]
  269. return convert_str_to_int(num)
  270. def is_valid_lang(lang):
  271. """Return language code and name if lang describe a language.
  272. Examples:
  273. >>> is_valid_lang('zz')
  274. False
  275. >>> is_valid_lang('uk')
  276. (True, 'uk', 'ukrainian')
  277. >>> is_valid_lang(b'uk')
  278. (True, 'uk', 'ukrainian')
  279. >>> is_valid_lang('en')
  280. (True, 'en', 'english')
  281. >>> searx.utils.is_valid_lang('Español')
  282. (True, 'es', 'spanish')
  283. >>> searx.utils.is_valid_lang('Spanish')
  284. (True, 'es', 'spanish')
  285. """
  286. if isinstance(lang, bytes):
  287. lang = lang.decode()
  288. is_abbr = (len(lang) == 2)
  289. lang = lang.lower()
  290. if is_abbr:
  291. for l in language_codes:
  292. if l[0][:2] == lang:
  293. return (True, l[0][:2], l[3].lower())
  294. return False
  295. else:
  296. for l in language_codes:
  297. if l[1].lower() == lang or l[3].lower() == lang:
  298. return (True, l[0][:2], l[3].lower())
  299. return False
  300. def _get_lang_to_lc_dict(lang_list):
  301. key = str(lang_list)
  302. value = lang_to_lc_cache.get(key, None)
  303. if value is None:
  304. value = dict()
  305. for lc in lang_list:
  306. value.setdefault(lc.split('-')[0], lc)
  307. lang_to_lc_cache[key] = value
  308. return value
  309. def _match_language(lang_code, lang_list=[], custom_aliases={}):
  310. """auxiliary function to match lang_code in lang_list"""
  311. # replace language code with a custom alias if necessary
  312. if lang_code in custom_aliases:
  313. lang_code = custom_aliases[lang_code]
  314. if lang_code in lang_list:
  315. return lang_code
  316. # try to get the most likely country for this language
  317. subtags = get_global('likely_subtags').get(lang_code)
  318. if subtags:
  319. subtag_parts = subtags.split('_')
  320. new_code = subtag_parts[0] + '-' + subtag_parts[-1]
  321. if new_code in custom_aliases:
  322. new_code = custom_aliases[new_code]
  323. if new_code in lang_list:
  324. return new_code
  325. # try to get the any supported country for this language
  326. return _get_lang_to_lc_dict(lang_list).get(lang_code, None)
  327. def match_language(locale_code, lang_list=[], custom_aliases={}, fallback='en-US'):
  328. """get the language code from lang_list that best matches locale_code"""
  329. # try to get language from given locale_code
  330. language = _match_language(locale_code, lang_list, custom_aliases)
  331. if language:
  332. return language
  333. locale_parts = locale_code.split('-')
  334. lang_code = locale_parts[0]
  335. # try to get language using an equivalent country code
  336. if len(locale_parts) > 1:
  337. country_alias = get_global('territory_aliases').get(locale_parts[-1])
  338. if country_alias:
  339. language = _match_language(lang_code + '-' + country_alias[0], lang_list, custom_aliases)
  340. if language:
  341. return language
  342. # try to get language using an equivalent language code
  343. alias = get_global('language_aliases').get(lang_code)
  344. if alias:
  345. language = _match_language(alias, lang_list, custom_aliases)
  346. if language:
  347. return language
  348. if lang_code != locale_code:
  349. # try to get language from given language without giving the country
  350. language = _match_language(lang_code, lang_list, custom_aliases)
  351. return language or fallback
  352. def load_module(filename, module_dir):
  353. modname = splitext(filename)[0]
  354. if modname in sys.modules:
  355. del sys.modules[modname]
  356. filepath = join(module_dir, filename)
  357. module = load_source(modname, filepath)
  358. module.name = modname
  359. return module
  360. def to_string(obj):
  361. """Convert obj to its string representation."""
  362. if isinstance(obj, str):
  363. return obj
  364. if isinstance(obj, Number):
  365. return str(obj)
  366. if hasattr(obj, '__str__'):
  367. return obj.__str__()
  368. if hasattr(obj, '__repr__'):
  369. return obj.__repr__()
  370. def ecma_unescape(s):
  371. """Python implementation of the unescape javascript function
  372. https://www.ecma-international.org/ecma-262/6.0/#sec-unescape-string
  373. https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/unescape
  374. Examples:
  375. >>> ecma_unescape('%u5409')
  376. '吉'
  377. >>> ecma_unescape('%20')
  378. ' '
  379. >>> ecma_unescape('%F3')
  380. 'ó'
  381. """
  382. # "%u5409" becomes "吉"
  383. s = ecma_unescape4_re.sub(lambda e: chr(int(e.group(1), 16)), s)
  384. # "%20" becomes " ", "%F3" becomes "ó"
  385. s = ecma_unescape2_re.sub(lambda e: chr(int(e.group(1), 16)), s)
  386. return s
  387. def get_engine_from_settings(name):
  388. """Return engine configuration from settings.yml of a given engine name"""
  389. if 'engines' not in settings:
  390. return {}
  391. for engine in settings['engines']:
  392. if 'name' not in engine:
  393. continue
  394. if name == engine['name']:
  395. return engine
  396. return {}
  397. def get_xpath(xpath_str):
  398. """Return cached compiled XPath
  399. There is no thread lock.
  400. Worst case scenario, xpath_str is compiled more than one time.
  401. """
  402. result = xpath_cache.get(xpath_str, None)
  403. if result is None:
  404. result = XPath(xpath_str)
  405. xpath_cache[xpath_str] = result
  406. return result
  407. def eval_xpath(element, xpath_str):
  408. """Equivalent of element.xpath(xpath_str) but compile xpath_str once for all."""
  409. xpath = get_xpath(xpath_str)
  410. return xpath(element)