utils.py 12 KB

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