utils.py 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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 = ('40.0',
  14. '41.0',
  15. '42.0',
  16. '43.0',
  17. '44.0',
  18. '45.0',
  19. '46.0',
  20. '47.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. # to avoid crashing if locale is not supported by babel
  161. try:
  162. formatted_date = format_date(date, locale=locale_string)
  163. except:
  164. formatted_date = format_date(date, "YYYY-MM-dd")
  165. return formatted_date
  166. def dict_subset(d, properties):
  167. result = {}
  168. for k in properties:
  169. if k in d:
  170. result[k] = d[k]
  171. return result
  172. def prettify_url(url, max_length=74):
  173. if len(url) > max_length:
  174. chunk_len = max_length / 2 + 1
  175. return u'{0}[...]{1}'.format(url[:chunk_len], url[-chunk_len:])
  176. else:
  177. return url
  178. # get element in list or default value
  179. def list_get(a_list, index, default=None):
  180. if len(a_list) > index:
  181. return a_list[index]
  182. else:
  183. return default
  184. def get_torrent_size(filesize, filesize_multiplier):
  185. try:
  186. filesize = float(filesize)
  187. if filesize_multiplier == 'TB':
  188. filesize = int(filesize * 1024 * 1024 * 1024 * 1024)
  189. elif filesize_multiplier == 'GB':
  190. filesize = int(filesize * 1024 * 1024 * 1024)
  191. elif filesize_multiplier == 'MB':
  192. filesize = int(filesize * 1024 * 1024)
  193. elif filesize_multiplier == 'KB':
  194. filesize = int(filesize * 1024)
  195. except:
  196. filesize = None
  197. return filesize