utils.py 8.2KB

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