webutils.py 4.0 KB

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