webutils.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import csv
  4. import hashlib
  5. import hmac
  6. import re
  7. import inspect
  8. import itertools
  9. from io import StringIO
  10. from codecs import getincrementalencoder
  11. from searx import logger, settings
  12. from searx.engines import OTHER_CATEGORY
  13. VALID_LANGUAGE_CODE = re.compile(r'^[a-z]{2,3}(-[a-zA-Z]{2})?$')
  14. logger = logger.getChild('webutils')
  15. class UnicodeWriter:
  16. """
  17. A CSV writer which will write rows to CSV file "f",
  18. which is encoded in the given encoding.
  19. """
  20. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  21. # Redirect output to a queue
  22. self.queue = StringIO()
  23. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  24. self.stream = f
  25. self.encoder = getincrementalencoder(encoding)()
  26. def writerow(self, row):
  27. self.writer.writerow(row)
  28. # Fetch UTF-8 output from the queue ...
  29. data = self.queue.getvalue()
  30. data = data.strip('\x00')
  31. # ... and reencode it into the target encoding
  32. data = self.encoder.encode(data)
  33. # write to the target stream
  34. self.stream.write(data.decode())
  35. # empty queue
  36. self.queue.truncate(0)
  37. def writerows(self, rows):
  38. for row in rows:
  39. self.writerow(row)
  40. def get_themes(templates_path):
  41. """Returns available themes list."""
  42. themes = os.listdir(templates_path)
  43. if '__common__' in themes:
  44. themes.remove('__common__')
  45. return themes
  46. def get_static_files(static_path):
  47. static_files = set()
  48. static_path_length = len(static_path) + 1
  49. for directory, _, files in os.walk(static_path):
  50. for filename in files:
  51. f = os.path.join(directory[static_path_length:], filename)
  52. static_files.add(f)
  53. return static_files
  54. def get_result_templates(templates_path):
  55. result_templates = set()
  56. templates_path_length = len(templates_path) + 1
  57. for directory, _, files in os.walk(templates_path):
  58. if directory.endswith('result_templates'):
  59. for filename in files:
  60. f = os.path.join(directory[templates_path_length:], filename)
  61. result_templates.add(f)
  62. return result_templates
  63. def new_hmac(secret_key, url):
  64. return hmac.new(secret_key.encode(), url, hashlib.sha256).hexdigest()
  65. def is_hmac_of(secret_key, value, hmac_to_check):
  66. hmac_of_value = new_hmac(secret_key, value)
  67. return len(hmac_of_value) == len(hmac_to_check) and hmac.compare_digest(hmac_of_value, hmac_to_check)
  68. def prettify_url(url, max_length=74):
  69. if len(url) > max_length:
  70. chunk_len = int(max_length / 2 + 1)
  71. return '{0}[...]{1}'.format(url[:chunk_len], url[-chunk_len:])
  72. else:
  73. return url
  74. def highlight_content(content, query):
  75. if not content:
  76. return None
  77. # ignoring html contents
  78. # TODO better html content detection
  79. if content.find('<') != -1:
  80. return content
  81. if content.lower().find(query.lower()) > -1:
  82. query_regex = '({0})'.format(re.escape(query))
  83. content = re.sub(query_regex, '<span class="highlight">\\1</span>', content, flags=re.I | re.U)
  84. else:
  85. regex_parts = []
  86. for chunk in query.split():
  87. chunk = chunk.replace('"', '')
  88. if len(chunk) == 0:
  89. continue
  90. elif len(chunk) == 1:
  91. regex_parts.append('\\W+{0}\\W+'.format(re.escape(chunk)))
  92. else:
  93. regex_parts.append('{0}'.format(re.escape(chunk)))
  94. query_regex = '({0})'.format('|'.join(regex_parts))
  95. content = re.sub(query_regex, '<span class="highlight">\\1</span>', content, flags=re.I | re.U)
  96. return content
  97. def is_flask_run_cmdline():
  98. """Check if the application was started using "flask run" command line
  99. Inspect the callstack.
  100. See https://github.com/pallets/flask/blob/master/src/flask/__main__.py
  101. Returns:
  102. bool: True if the application was started using "flask run".
  103. """
  104. frames = inspect.stack()
  105. if len(frames) < 2:
  106. return False
  107. return frames[-2].filename.endswith('flask/cli.py')
  108. DEFAULT_GROUP_NAME = 'others'
  109. def group_engines_in_tab(engines):
  110. def engine_sort_key(engine):
  111. return (engine.about.get('language', ''), engine.name)
  112. def group_sort_key(group):
  113. return (group[0] == DEFAULT_GROUP_NAME, group[0].lower())
  114. def get_group(eng):
  115. non_tab_categories = [c for c in eng.categories if c not in settings['categories_as_tabs'] + [OTHER_CATEGORY]]
  116. return non_tab_categories[0] if len(non_tab_categories) > 0 else DEFAULT_GROUP_NAME
  117. return [
  118. (groupname, sorted(engines, key=engine_sort_key))
  119. for groupname, engines in sorted(
  120. ((name, list(engines)) for name, engines in itertools.groupby(sorted(engines, key=get_group), get_group)),
  121. key=group_sort_key,
  122. )
  123. ]