utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import csv
  2. import hashlib
  3. import hmac
  4. import os
  5. import re
  6. from babel.core import get_global
  7. from babel.dates import format_date
  8. from codecs import getincrementalencoder
  9. from imp import load_source
  10. from numbers import Number
  11. from os.path import splitext, join
  12. from random import choice
  13. import sys
  14. from searx import settings
  15. from searx.version import VERSION_STRING
  16. from searx.languages import language_codes
  17. from searx import settings
  18. from searx import logger
  19. try:
  20. from cStringIO import StringIO
  21. except:
  22. from io import StringIO
  23. try:
  24. from HTMLParser import HTMLParser
  25. except:
  26. from html.parser import HTMLParser
  27. if sys.version_info[0] == 3:
  28. unichr = chr
  29. unicode = str
  30. IS_PY2 = False
  31. basestring = str
  32. else:
  33. IS_PY2 = True
  34. logger = logger.getChild('utils')
  35. ua_versions = ('52.8.1',
  36. '53.0',
  37. '54.0',
  38. '55.0',
  39. '56.0',
  40. '57.0',
  41. '58.0',
  42. '59.0',
  43. '60.0.2')
  44. ua_os = ('Windows NT 6.3; WOW64',
  45. 'X11; Linux x86_64',
  46. 'X11; Linux x86')
  47. ua = "Mozilla/5.0 ({os}; rv:{version}) Gecko/20100101 Firefox/{version}"
  48. blocked_tags = ('script',
  49. 'style')
  50. def gen_useragent(os=None):
  51. # TODO
  52. return ua.format(os=os or choice(ua_os), version=choice(ua_versions))
  53. def searx_useragent():
  54. return 'searx/{searx_version} {suffix}'.format(
  55. searx_version=VERSION_STRING,
  56. suffix=settings['outgoing'].get('useragent_suffix', ''))
  57. def highlight_content(content, query):
  58. if not content:
  59. return None
  60. # ignoring html contents
  61. # TODO better html content detection
  62. if content.find('<') != -1:
  63. return content
  64. query = query.decode('utf-8')
  65. if content.lower().find(query.lower()) > -1:
  66. query_regex = u'({0})'.format(re.escape(query))
  67. content = re.sub(query_regex, '<span class="highlight">\\1</span>',
  68. content, flags=re.I | re.U)
  69. else:
  70. regex_parts = []
  71. for chunk in query.split():
  72. if len(chunk) == 1:
  73. regex_parts.append(u'\\W+{0}\\W+'.format(re.escape(chunk)))
  74. else:
  75. regex_parts.append(u'{0}'.format(re.escape(chunk)))
  76. query_regex = u'({0})'.format('|'.join(regex_parts))
  77. content = re.sub(query_regex, '<span class="highlight">\\1</span>',
  78. content, flags=re.I | re.U)
  79. return content
  80. class HTMLTextExtractor(HTMLParser):
  81. def __init__(self):
  82. HTMLParser.__init__(self)
  83. self.result = []
  84. self.tags = []
  85. def handle_starttag(self, tag, attrs):
  86. self.tags.append(tag)
  87. def handle_endtag(self, tag):
  88. if not self.tags:
  89. return
  90. if tag != self.tags[-1]:
  91. raise Exception("invalid html")
  92. self.tags.pop()
  93. def is_valid_tag(self):
  94. return not self.tags or self.tags[-1] not in blocked_tags
  95. def handle_data(self, d):
  96. if not self.is_valid_tag():
  97. return
  98. self.result.append(d)
  99. def handle_charref(self, number):
  100. if not self.is_valid_tag():
  101. return
  102. if number[0] in (u'x', u'X'):
  103. codepoint = int(number[1:], 16)
  104. else:
  105. codepoint = int(number)
  106. self.result.append(unichr(codepoint))
  107. def handle_entityref(self, name):
  108. if not self.is_valid_tag():
  109. return
  110. # codepoint = htmlentitydefs.name2codepoint[name]
  111. # self.result.append(unichr(codepoint))
  112. self.result.append(name)
  113. def get_text(self):
  114. return u''.join(self.result).strip()
  115. def html_to_text(html):
  116. html = html.replace('\n', ' ')
  117. html = ' '.join(html.split())
  118. s = HTMLTextExtractor()
  119. s.feed(html)
  120. return s.get_text()
  121. class UnicodeWriter:
  122. """
  123. A CSV writer which will write rows to CSV file "f",
  124. which is encoded in the given encoding.
  125. """
  126. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  127. # Redirect output to a queue
  128. self.queue = StringIO()
  129. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  130. self.stream = f
  131. self.encoder = getincrementalencoder(encoding)()
  132. def writerow(self, row):
  133. if IS_PY2:
  134. row = [s.encode("utf-8") if hasattr(s, 'encode') else s for s in row]
  135. self.writer.writerow(row)
  136. # Fetch UTF-8 output from the queue ...
  137. data = self.queue.getvalue()
  138. if IS_PY2:
  139. data = data.decode("utf-8")
  140. else:
  141. data = data.strip('\x00')
  142. # ... and reencode it into the target encoding
  143. data = self.encoder.encode(data)
  144. # write to the target stream
  145. if IS_PY2:
  146. self.stream.write(data)
  147. else:
  148. self.stream.write(data.decode("utf-8"))
  149. # empty queue
  150. self.queue.truncate(0)
  151. def writerows(self, rows):
  152. for row in rows:
  153. self.writerow(row)
  154. def get_resources_directory(searx_directory, subdirectory, resources_directory):
  155. if not resources_directory:
  156. resources_directory = os.path.join(searx_directory, subdirectory)
  157. if not os.path.isdir(resources_directory):
  158. raise Exception(directory + " is not a directory")
  159. return resources_directory
  160. def get_themes(templates_path):
  161. """Returns available themes list."""
  162. themes = os.listdir(templates_path)
  163. if '__common__' in themes:
  164. themes.remove('__common__')
  165. return themes
  166. def get_static_files(static_path):
  167. static_files = set()
  168. static_path_length = len(static_path) + 1
  169. for directory, _, files in os.walk(static_path):
  170. for filename in files:
  171. f = os.path.join(directory[static_path_length:], filename)
  172. static_files.add(f)
  173. return static_files
  174. def get_result_templates(templates_path):
  175. result_templates = set()
  176. templates_path_length = len(templates_path) + 1
  177. for directory, _, files in os.walk(templates_path):
  178. if directory.endswith('result_templates'):
  179. for filename in files:
  180. f = os.path.join(directory[templates_path_length:], filename)
  181. result_templates.add(f)
  182. return result_templates
  183. def format_date_by_locale(date, locale_string):
  184. # strftime works only on dates after 1900
  185. if date.year <= 1900:
  186. return date.isoformat().split('T')[0]
  187. if locale_string == 'all':
  188. locale_string = settings['ui']['default_locale'] or 'en_US'
  189. # to avoid crashing if locale is not supported by babel
  190. try:
  191. formatted_date = format_date(date, locale=locale_string)
  192. except:
  193. formatted_date = format_date(date, "YYYY-MM-dd")
  194. return formatted_date
  195. def dict_subset(d, properties):
  196. result = {}
  197. for k in properties:
  198. if k in d:
  199. result[k] = d[k]
  200. return result
  201. def prettify_url(url, max_length=74):
  202. if len(url) > max_length:
  203. chunk_len = int(max_length / 2 + 1)
  204. return u'{0}[...]{1}'.format(url[:chunk_len], url[-chunk_len:])
  205. else:
  206. return url
  207. # get element in list or default value
  208. def list_get(a_list, index, default=None):
  209. if len(a_list) > index:
  210. return a_list[index]
  211. else:
  212. return default
  213. def get_torrent_size(filesize, filesize_multiplier):
  214. try:
  215. filesize = float(filesize)
  216. if filesize_multiplier == 'TB':
  217. filesize = int(filesize * 1024 * 1024 * 1024 * 1024)
  218. elif filesize_multiplier == 'GB':
  219. filesize = int(filesize * 1024 * 1024 * 1024)
  220. elif filesize_multiplier == 'MB':
  221. filesize = int(filesize * 1024 * 1024)
  222. elif filesize_multiplier == 'KB':
  223. filesize = int(filesize * 1024)
  224. elif filesize_multiplier == 'TiB':
  225. filesize = int(filesize * 1000 * 1000 * 1000 * 1000)
  226. elif filesize_multiplier == 'GiB':
  227. filesize = int(filesize * 1000 * 1000 * 1000)
  228. elif filesize_multiplier == 'MiB':
  229. filesize = int(filesize * 1000 * 1000)
  230. elif filesize_multiplier == 'KiB':
  231. filesize = int(filesize * 1000)
  232. except:
  233. filesize = None
  234. return filesize
  235. def convert_str_to_int(number_str):
  236. if number_str.isdigit():
  237. return int(number_str)
  238. else:
  239. return 0
  240. # convert a variable to integer or return 0 if it's not a number
  241. def int_or_zero(num):
  242. if isinstance(num, list):
  243. if len(num) < 1:
  244. return 0
  245. num = num[0]
  246. return convert_str_to_int(num)
  247. def is_valid_lang(lang):
  248. is_abbr = (len(lang) == 2)
  249. if is_abbr:
  250. for l in language_codes:
  251. if l[0][:2] == lang.lower():
  252. return (True, l[0][:2], l[3].lower())
  253. return False
  254. else:
  255. for l in language_codes:
  256. if l[1].lower() == lang.lower():
  257. return (True, l[0][:2], l[3].lower())
  258. return False
  259. # auxiliary function to match lang_code in lang_list
  260. def _match_language(lang_code, lang_list=[], custom_aliases={}):
  261. # replace language code with a custom alias if necessary
  262. if lang_code in custom_aliases:
  263. lang_code = custom_aliases[lang_code]
  264. if lang_code in lang_list:
  265. return lang_code
  266. # try to get the most likely country for this language
  267. subtags = get_global('likely_subtags').get(lang_code)
  268. if subtags:
  269. subtag_parts = subtags.split('_')
  270. new_code = subtag_parts[0] + '-' + subtag_parts[-1]
  271. if new_code in custom_aliases:
  272. new_code = custom_aliases[new_code]
  273. if new_code in lang_list:
  274. return new_code
  275. # try to get the any supported country for this language
  276. for lc in lang_list:
  277. if lang_code == lc.split('-')[0]:
  278. return lc
  279. return None
  280. # get the language code from lang_list that best matches locale_code
  281. def match_language(locale_code, lang_list=[], custom_aliases={}, fallback='en-US'):
  282. # try to get language from given locale_code
  283. language = _match_language(locale_code, lang_list, custom_aliases)
  284. if language:
  285. return language
  286. locale_parts = locale_code.split('-')
  287. lang_code = locale_parts[0]
  288. # try to get language using an equivalent country code
  289. if len(locale_parts) > 1:
  290. country_alias = get_global('territory_aliases').get(locale_parts[-1])
  291. if country_alias:
  292. language = _match_language(lang_code + '-' + country_alias[0], lang_list, custom_aliases)
  293. if language:
  294. return language
  295. # try to get language using an equivalent language code
  296. alias = get_global('language_aliases').get(lang_code)
  297. if alias:
  298. language = _match_language(alias, lang_list, custom_aliases)
  299. if language:
  300. return language
  301. if lang_code != locale_code:
  302. # try to get language from given language without giving the country
  303. language = _match_language(lang_code, lang_list, custom_aliases)
  304. return language or fallback
  305. def load_module(filename, module_dir):
  306. modname = splitext(filename)[0]
  307. if modname in sys.modules:
  308. del sys.modules[modname]
  309. filepath = join(module_dir, filename)
  310. module = load_source(modname, filepath)
  311. module.name = modname
  312. return module
  313. def new_hmac(secret_key, url):
  314. if sys.version_info[0] == 2:
  315. return hmac.new(bytes(secret_key), url, hashlib.sha256).hexdigest()
  316. else:
  317. return hmac.new(bytes(secret_key, 'utf-8'), url, hashlib.sha256).hexdigest()
  318. def to_string(obj):
  319. if isinstance(obj, basestring):
  320. return obj
  321. if isinstance(obj, Number):
  322. return unicode(obj)
  323. if hasattr(obj, '__str__'):
  324. return obj.__str__()
  325. if hasattr(obj, '__repr__'):
  326. return obj.__repr__()