utils.py 9.1 KB

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