webutils.py 8.0 KB

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