utils.py 7.9KB

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