utils.py 14 KB

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