123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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 random import choice
  9. from searx.version import VERSION_STRING
  10. from searx import settings
  11. from searx import logger
  12. logger = logger.getChild('utils')
  13. ua_versions = ('33.0',
  14. '34.0',
  15. '35.0',
  16. '36.0',
  17. '37.0',
  18. '38.0',
  19. '39.0',
  20. '40.0')
  21. ua_os = ('Windows NT 6.3; WOW64',
  22. 'X11; Linux x86_64',
  23. 'X11; Linux x86')
  24. ua = "Mozilla/5.0 ({os}; rv:{version}) Gecko/20100101 Firefox/{version}"
  25. blocked_tags = ('script',
  26. 'style')
  27. def gen_useragent():
  28. # TODO
  29. return ua.format(os=choice(ua_os), version=choice(ua_versions))
  30. def searx_useragent():
  31. return 'searx/{searx_version} {suffix}'.format(
  32. searx_version=VERSION_STRING,
  33. suffix=settings['outgoing'].get('useragent_suffix', ''))
  34. def highlight_content(content, query):
  35. if not content:
  36. return None
  37. # ignoring html contents
  38. # TODO better html content detection
  39. if content.find('<') != -1:
  40. return content
  41. query = query.decode('utf-8')
  42. if content.lower().find(query.lower()) > -1:
  43. query_regex = u'({0})'.format(re.escape(query))
  44. content = re.sub(query_regex, '<span class="highlight">\\1</span>',
  45. content, flags=re.I | re.U)
  46. else:
  47. regex_parts = []
  48. for chunk in query.split():
  49. if len(chunk) == 1:
  50. regex_parts.append(u'\W+{0}\W+'.format(re.escape(chunk)))
  51. else:
  52. regex_parts.append(u'{0}'.format(re.escape(chunk)))
  53. query_regex = u'({0})'.format('|'.join(regex_parts))
  54. content = re.sub(query_regex, '<span class="highlight">\\1</span>',
  55. content, flags=re.I | re.U)
  56. return content
  57. class HTMLTextExtractor(HTMLParser):
  58. def __init__(self):
  59. HTMLParser.__init__(self)
  60. self.result = []
  61. self.tags = []
  62. def handle_starttag(self, tag, attrs):
  63. self.tags.append(tag)
  64. def handle_endtag(self, tag):
  65. if not self.tags:
  66. return
  67. if tag != self.tags[-1]:
  68. raise Exception("invalid html")
  69. self.tags.pop()
  70. def is_valid_tag(self):
  71. return not self.tags or self.tags[-1] not in blocked_tags
  72. def handle_data(self, d):
  73. if not self.is_valid_tag():
  74. return
  75. self.result.append(d)
  76. def handle_charref(self, number):
  77. if not self.is_valid_tag():
  78. return
  79. if number[0] in (u'x', u'X'):
  80. codepoint = int(number[1:], 16)
  81. else:
  82. codepoint = int(number)
  83. self.result.append(unichr(codepoint))
  84. def handle_entityref(self, name):
  85. if not self.is_valid_tag():
  86. return
  87. # codepoint = htmlentitydefs.name2codepoint[name]
  88. # self.result.append(unichr(codepoint))
  89. self.result.append(name)
  90. def get_text(self):
  91. return u''.join(self.result).strip()
  92. def html_to_text(html):
  93. html = html.replace('\n', ' ')
  94. html = ' '.join(html.split())
  95. s = HTMLTextExtractor()
  96. s.feed(html)
  97. return s.get_text()
  98. class UnicodeWriter:
  99. """
  100. A CSV writer which will write rows to CSV file "f",
  101. which is encoded in the given encoding.
  102. """
  103. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  104. # Redirect output to a queue
  105. self.queue = cStringIO.StringIO()
  106. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  107. self.stream = f
  108. self.encoder = getincrementalencoder(encoding)()
  109. def writerow(self, row):
  110. unicode_row = []
  111. for col in row:
  112. if type(col) == str or type(col) == unicode:
  113. unicode_row.append(col.encode('utf-8').strip())
  114. else:
  115. unicode_row.append(col)
  116. self.writer.writerow(unicode_row)
  117. # Fetch UTF-8 output from the queue ...
  118. data = self.queue.getvalue()
  119. data = data.decode("utf-8")
  120. # ... and reencode it into the target encoding
  121. data = self.encoder.encode(data)
  122. # write to the target stream
  123. self.stream.write(data)
  124. # empty queue
  125. self.queue.truncate(0)
  126. def writerows(self, rows):
  127. for row in rows:
  128. self.writerow(row)
  129. def get_themes(root):
  130. """Returns available themes list."""
  131. static_path = os.path.join(root, 'static')
  132. templates_path = os.path.join(root, 'templates')
  133. themes = os.listdir(os.path.join(static_path, 'themes'))
  134. return static_path, templates_path, themes
  135. def get_static_files(base_path):
  136. base_path = os.path.join(base_path, 'static')
  137. static_files = set()
  138. base_path_length = len(base_path) + 1
  139. for directory, _, files in os.walk(base_path):
  140. for filename in files:
  141. f = os.path.join(directory[base_path_length:], filename)
  142. static_files.add(f)
  143. return static_files
  144. def get_result_templates(base_path):
  145. base_path = os.path.join(base_path, 'templates')
  146. result_templates = set()
  147. base_path_length = len(base_path) + 1
  148. for directory, _, files in os.walk(base_path):
  149. if directory.endswith('result_templates'):
  150. for filename in files:
  151. f = os.path.join(directory[base_path_length:], filename)
  152. result_templates.add(f)
  153. return result_templates
  154. def format_date_by_locale(date, locale_string):
  155. # strftime works only on dates after 1900
  156. if date.year <= 1900:
  157. return date.isoformat().split('T')[0]
  158. if locale_string == 'all':
  159. locale_string = settings['ui']['default_locale'] or 'en_US'
  160. return format_date(date, locale=locale_string)
  161. def dict_subset(d, properties):
  162. result = {}
  163. for k in properties:
  164. if k in d:
  165. result[k] = d[k]
  166. return result
  167. def prettify_url(url, max_length=74):
  168. if len(url) > max_length:
  169. chunk_len = max_length / 2 + 1
  170. return u'{0}[...]{1}'.format(url[:chunk_len], url[-chunk_len:])
  171. else:
  172. return url
  173. # get element in list or default value
  174. def list_get(a_list, index, default=None):
  175. if len(a_list) > index:
  176. return a_list[index]
  177. else:
  178. return default
  179. def get_blocked_engines(engines, cookies):
  180. if 'blocked_engines' not in cookies:
  181. return [(engine_name, category) for engine_name in engines
  182. for category in engines[engine_name].categories if engines[engine_name].disabled]
  183. blocked_engine_strings = cookies.get('blocked_engines', '').split(',')
  184. blocked_engines = []
  185. if not blocked_engine_strings:
  186. return blocked_engines
  187. for engine_string in blocked_engine_strings:
  188. if engine_string.find('__') > -1:
  189. engine, category = engine_string.split('__', 1)
  190. if engine in engines and category in engines[engine].categories:
  191. blocked_engines.append((engine, category))
  192. elif engine_string in engines:
  193. for category in engines[engine_string].categories:
  194. blocked_engines.append((engine_string, category))
  195. return blocked_engines