webutils.py 5.4 KB

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