webutils.py 4.2 KB

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