webutils.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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 datetime import datetime, timedelta
  11. from typing import Iterable, List, Tuple, Dict
  12. from io import StringIO
  13. from codecs import getincrementalencoder
  14. from flask_babel import gettext, format_date
  15. from searx import logger, settings
  16. from searx.engines import Engine, OTHER_CATEGORY
  17. VALID_LANGUAGE_CODE = re.compile(r'^[a-z]{2,3}(-[a-zA-Z]{2})?$')
  18. logger = logger.getChild('webutils')
  19. class UnicodeWriter:
  20. """
  21. A CSV writer which will write rows to CSV file "f",
  22. which is encoded in the given encoding.
  23. """
  24. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  25. # Redirect output to a queue
  26. self.queue = StringIO()
  27. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  28. self.stream = f
  29. self.encoder = getincrementalencoder(encoding)()
  30. def writerow(self, row):
  31. self.writer.writerow(row)
  32. # Fetch UTF-8 output from the queue ...
  33. data = self.queue.getvalue()
  34. data = data.strip('\x00')
  35. # ... and re-encode it into the target encoding
  36. data = self.encoder.encode(data)
  37. # write to the target stream
  38. self.stream.write(data.decode())
  39. # empty queue
  40. self.queue.truncate(0)
  41. def writerows(self, rows):
  42. for row in rows:
  43. self.writerow(row)
  44. def get_themes(templates_path):
  45. """Returns available themes list."""
  46. return os.listdir(templates_path)
  47. def get_hash_for_file(file: pathlib.Path) -> str:
  48. m = hashlib.sha1()
  49. with file.open('rb') as f:
  50. m.update(f.read())
  51. return m.hexdigest()
  52. def get_static_files(static_path: str) -> Dict[str, str]:
  53. static_files: Dict[str, str] = {}
  54. static_path_path = pathlib.Path(static_path)
  55. def walk(path: pathlib.Path):
  56. for file in path.iterdir():
  57. if file.name.startswith('.'):
  58. # ignore hidden file
  59. continue
  60. if file.is_file():
  61. static_files[str(file.relative_to(static_path_path))] = get_hash_for_file(file)
  62. if file.is_dir() and file.name not in ('node_modules', 'src'):
  63. # ignore "src" and "node_modules" directories
  64. walk(file)
  65. walk(static_path_path)
  66. return static_files
  67. def get_result_templates(templates_path):
  68. result_templates = set()
  69. templates_path_length = len(templates_path) + 1
  70. for directory, _, files in os.walk(templates_path):
  71. if directory.endswith('result_templates'):
  72. for filename in files:
  73. f = os.path.join(directory[templates_path_length:], filename)
  74. result_templates.add(f)
  75. return result_templates
  76. def new_hmac(secret_key, url):
  77. return hmac.new(secret_key.encode(), url, hashlib.sha256).hexdigest()
  78. def is_hmac_of(secret_key, value, hmac_to_check):
  79. hmac_of_value = new_hmac(secret_key, value)
  80. return len(hmac_of_value) == len(hmac_to_check) and hmac.compare_digest(hmac_of_value, hmac_to_check)
  81. def prettify_url(url, max_length=74):
  82. if len(url) > max_length:
  83. chunk_len = int(max_length / 2 + 1)
  84. return '{0}[...]{1}'.format(url[:chunk_len], url[-chunk_len:])
  85. else:
  86. return url
  87. def contains_cjko(s: str) -> bool:
  88. """This function check whether or not a string contains Chinese, Japanese,
  89. or Korean characters. It employs regex and uses the u escape sequence to
  90. match any character in a set of Unicode ranges.
  91. Args:
  92. s (str): string to be checked.
  93. Returns:
  94. bool: True if the input s contains the characters and False otherwise.
  95. """
  96. unicode_ranges = (
  97. '\u4e00-\u9fff' # Chinese characters
  98. '\u3040-\u309f' # Japanese hiragana
  99. '\u30a0-\u30ff' # Japanese katakana
  100. '\u4e00-\u9faf' # Japanese kanji
  101. '\uac00-\ud7af' # Korean hangul syllables
  102. '\u1100-\u11ff' # Korean hangul jamo
  103. )
  104. return bool(re.search(fr'[{unicode_ranges}]', s))
  105. def regex_highlight_cjk(word: str) -> str:
  106. """Generate the regex pattern to match for a given word according
  107. to whether or not the word contains CJK characters or not.
  108. If the word is and/or contains CJK character, the regex pattern
  109. will match standalone word by taking into account the presence
  110. of whitespace before and after it; if not, it will match any presence
  111. of the word throughout the text, ignoring the whitespace.
  112. Args:
  113. word (str): the word to be matched with regex pattern.
  114. Returns:
  115. str: the regex pattern for the word.
  116. """
  117. rword = re.escape(word)
  118. if contains_cjko(rword):
  119. return fr'({rword})'
  120. else:
  121. return fr'\b({rword})(?!\w)'
  122. def highlight_content(content, query):
  123. if not content:
  124. return None
  125. # ignoring html contents
  126. # TODO better html content detection
  127. if content.find('<') != -1:
  128. return content
  129. querysplit = query.split()
  130. queries = []
  131. for qs in querysplit:
  132. qs = qs.replace("'", "").replace('"', '').replace(" ", "")
  133. if len(qs) > 0:
  134. queries.extend(re.findall(regex_highlight_cjk(qs), content, flags=re.I | re.U))
  135. if len(queries) > 0:
  136. for q in set(queries):
  137. content = re.sub(
  138. regex_highlight_cjk(q), f'<span class="highlight">{q}</span>'.replace('\\', r'\\'), content
  139. )
  140. return content
  141. def searxng_l10n_timespan(dt: datetime) -> str: # pylint: disable=invalid-name
  142. """Returns a human-readable and translated string indicating how long ago
  143. a date was in the past / the time span of the date to the present.
  144. On January 1st, midnight, the returned string only indicates how many years
  145. ago the date was.
  146. """
  147. # TODO, check if timezone is calculated right # pylint: disable=fixme
  148. d = dt.date()
  149. t = dt.time()
  150. if d.month == 1 and d.day == 1 and t.hour == 0 and t.minute == 0 and t.second == 0:
  151. return str(d.year)
  152. if dt.replace(tzinfo=None) >= datetime.now() - timedelta(days=1):
  153. timedifference = datetime.now() - dt.replace(tzinfo=None)
  154. minutes = int((timedifference.seconds / 60) % 60)
  155. hours = int(timedifference.seconds / 60 / 60)
  156. if hours == 0:
  157. return gettext('{minutes} minute(s) ago').format(minutes=minutes)
  158. return gettext('{hours} hour(s), {minutes} minute(s) ago').format(hours=hours, minutes=minutes)
  159. return format_date(dt)
  160. def is_flask_run_cmdline():
  161. """Check if the application was started using "flask run" command line
  162. Inspect the callstack.
  163. See https://github.com/pallets/flask/blob/master/src/flask/__main__.py
  164. Returns:
  165. bool: True if the application was started using "flask run".
  166. """
  167. frames = inspect.stack()
  168. if len(frames) < 2:
  169. return False
  170. return frames[-2].filename.endswith('flask/cli.py')
  171. DEFAULT_GROUP_NAME = 'others'
  172. def group_engines_in_tab(engines: Iterable[Engine]) -> List[Tuple[str, Iterable[Engine]]]:
  173. """Groups an Iterable of engines by their first non tab category"""
  174. def get_group(eng):
  175. non_tab_categories = [
  176. c for c in eng.categories if c not in list(settings['categories_as_tabs'].keys()) + [OTHER_CATEGORY]
  177. ]
  178. return non_tab_categories[0] if len(non_tab_categories) > 0 else DEFAULT_GROUP_NAME
  179. groups = itertools.groupby(sorted(engines, key=get_group), get_group)
  180. def group_sort_key(group):
  181. return (group[0] == DEFAULT_GROUP_NAME, group[0].lower())
  182. sorted_groups = sorted(((name, list(engines)) for name, engines in groups), key=group_sort_key)
  183. def engine_sort_key(engine):
  184. return (engine.about.get('language', ''), engine.name)
  185. return [(groupname, sorted(engines, key=engine_sort_key)) for groupname, engines in sorted_groups]