summaryrefslogtreecommitdiff
path: root/searx/utils.py
diff options
context:
space:
mode:
authorAlexandre Flament <alex@al-f.net>2023-09-09 10:18:39 +0000
committerAlexandre Flament <alex@al-f.net>2023-09-09 13:02:36 +0200
commitd07c006aed12631a7e0f9a5c82288a8ef7c5bfad (patch)
tree3d44039eb5302fc7db7d398f6ec92f03635142c3 /searx/utils.py
parent8e45ac42717da130017b53fd332afa416e36b194 (diff)
downloadsearxng-d07c006aed12631a7e0f9a5c82288a8ef7c5bfad.tar.gz
searxng-d07c006aed12631a7e0f9a5c82288a8ef7c5bfad.zip
Replace chompjs with pure Python code
The new implementation is good enough for the current usage (brave)
Diffstat (limited to 'searx/utils.py')
-rw-r--r--searx/utils.py73
1 files changed, 73 insertions, 0 deletions
diff --git a/searx/utils.py b/searx/utils.py
index 7ddd2305a..9457ca87d 100644
--- a/searx/utils.py
+++ b/searx/utils.py
@@ -7,6 +7,7 @@
import re
import importlib
import importlib.util
+import json
import types
from typing import Optional, Union, Any, Set, List, Dict, MutableMapping, Tuple, Callable
@@ -37,6 +38,9 @@ _BLOCKED_TAGS = ('script', 'style')
_ECMA_UNESCAPE4_RE = re.compile(r'%u([0-9a-fA-F]{4})', re.UNICODE)
_ECMA_UNESCAPE2_RE = re.compile(r'%([0-9a-fA-F]{2})', re.UNICODE)
+_JS_QUOTE_KEYS_RE = re.compile(r'([\{\s,])(\w+)(:)')
+_JS_VOID_RE = re.compile(r'void\s+[0-9]+|void\s*\([0-9]+\)')
+
_STORAGE_UNIT_VALUE: Dict[str, int] = {
'TB': 1024 * 1024 * 1024 * 1024,
'GB': 1024 * 1024 * 1024,
@@ -645,3 +649,72 @@ def detect_language(text: str, threshold: float = 0.3, only_search_languages: bo
return None
return language
return None
+
+
+def js_variable_to_python(js_variable):
+ """Convert a javascript variable into JSON and then load the value
+
+ It does not deal with all cases, but it is good enough for now.
+ chompjs has a better implementation.
+ """
+ # when in_string is not None, it contains the character that has opened the string
+ # either simple quote or double quote
+ in_string = None
+ # cut the string:
+ # r"""{ a:"f\"irst", c:'sec"ond'}"""
+ # becomes
+ # ['{ a:', '"', 'f\\', '"', 'irst', '"', ', c:', "'", 'sec', '"', 'ond', "'", '}']
+ parts = re.split(r'(["\'])', js_variable)
+ # previous part (to check the escape character antislash)
+ previous_p = ""
+ for i, p in enumerate(parts):
+ # parse characters inside a ECMA string
+ if in_string:
+ # we are in a JS string: replace the colon by a temporary character
+ # so quote_keys_regex doesn't have to deal with colon inside the JS strings
+ parts[i] = parts[i].replace(':', chr(1))
+ if in_string == "'":
+ # the JS string is delimited by simple quote.
+ # This is not supported by JSON.
+ # simple quote delimited string are converted to double quote delimited string
+ # here, inside a JS string, we escape the double quote
+ parts[i] = parts[i].replace('"', r'\"')
+
+ # deal with delimieters and escape character
+ if not in_string and p in ('"', "'"):
+ # we are not in string
+ # but p is double or simple quote
+ # that's the start of a new string
+ # replace simple quote by double quote
+ # (JSON doesn't support simple quote)
+ parts[i] = '"'
+ in_string = p
+ continue
+ if p == in_string:
+ # we are in a string and the current part MAY close the string
+ if len(previous_p) > 0 and previous_p[-1] == '\\':
+ # there is an antislash just before: the ECMA string continue
+ continue
+ # the current p close the string
+ # replace simple quote by double quote
+ parts[i] = '"'
+ in_string = None
+ #
+ if not in_string:
+ # replace void 0 by null
+ # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
+ # we are sure there is no string in p
+ parts[i] = _JS_VOID_RE.sub("null", p)
+ # update previous_p
+ previous_p = p
+ # join the string
+ s = ''.join(parts)
+ # add quote arround the key
+ # { a: 12 }
+ # becomes
+ # { "a": 12 }
+ s = _JS_QUOTE_KEYS_RE.sub(r'\1"\2"\3', s)
+ # replace the surogate character by colon
+ s = s.replace(chr(1), ':')
+ # load the JSON and return the result
+ return json.loads(s)