Debian Codegraph @

asusrouter/tools/readers.py

raw
1 """Reading tools for AsusRouter."""
2
3 from __future__ import annotations
4
5 import ast
6 import json
7 import logging
8 import re
9 from typing import Any
10
11 from asusrouter.const import ContentType
12 from asusrouter.tools.converters import clean_input, safe_float, safe_float_nn
13 from asusrouter.tools.types import ARCallableType
14 from asusrouter.tools.units import (
15 DataRateUnitConverter,
16 UnitConverterBase,
17 UnitOfDataRate,
18 )
19
20 _LOGGER = logging.getLogger(__name__)
21
22
23 # Random symbols to avoid json errors
24 RANDOM_SYMBOLS: list[str] = [
25 "\u0000",
26 "\u0001",
27 "\u0002",
28 "\u0003",
29 "\u0004",
30 "\u0005",
31 "\u0006",
32 "\u0007",
33 "\u0008",
34 "\u0009",
35 ]
36
37
38 def is_non_negative(value: Any) -> bool:
39 """Check if the value is non-negative."""
40
41 return safe_float_nn(value) >= 0
42
43
44 def merge_dicts(
45 data: dict[Any, Any], merge_data: dict[Any, Any]
46 ) -> dict[Any, Any]:
47 """Merge two nested dicts into a single one.
48
49 Keep all the existing values.
50 """
51
52 # Create a new dictionary to store the merged data
53 merged_data = data.copy()
54
55 # Go through the merge data and fill the merged data
56 for key, value in merge_data.items():
57 # Check if the value is a dict
58 if isinstance(value, dict):
59 # Check if the key is in the merged data
60 if key not in merged_data or merged_data[key] is None:
61 # Add the key to the merged data
62 merged_data[key] = {}
63 # Merge the dicts
64 merged_data[key] = merge_dicts(merged_data[key], value)
65 # Continue to the next value
66 continue
67 # Check if the key is in the merged data
68 if key not in merged_data:
69 # Add the key to the merged data
70 merged_data[key] = value
71 # If the key is already in the merged data, compare the values
72 elif merged_data[key] is None:
73 # If the value in the merged data is None, take the value
74 # from the merge data
75 merged_data[key] = value
76 elif value is None:
77 # If the value in the merge data is not None
78 # and the value in the merge data is None, keep the value
79 # in the merged data
80 pass
81 else:
82 # If both values are not None, keep the value from the merged data
83 pass
84
85 # Return the merged data
86 return merged_data
87
88
89 def read_as_snake_case(data: str) -> str:
90 """Convert a string to snake case."""
91
92 string = (
93 re.sub(r"(?<=[a-z])(?=[A-Z])|[^a-zA-Z]", " ", data)
94 .strip()
95 .replace(" ", "_")
96 )
97 result = "".join(string.lower())
98 while "__" in result:
99 result = result.replace("__", "_")
100
101 return result
102
103
104 def read_content_type(headers: dict[str, str]) -> ContentType:
105 """Get the content type from the headers."""
106
107 # Get the content type from the headers
108 content_type = headers.get("content-type", "").split(";")[0].strip()
109 # Find the content type in ContentType enum and return correct
110 # ContentType enum
111 for content_type_enum in ContentType:
112 if content_type_enum.value == content_type:
113 return content_type_enum
114
115 # If the content type is not found, return the content type as text
116 return ContentType.UNKNOWN
117
118
119 @clean_input
120 def read_js_variables(content: str, **kwargs: Any) -> dict[str, Any]:
121 """Get all the JS variables from the content."""
122
123 # Create a dict to store the data
124 js_variables: dict[str, Any] = {}
125
126 # regex = re.compile(r"(\w+)\s*=\s*(.*?);$", re.DOTALL | re.MULTILINE)
127 regex = re.compile(
128 r"""(?m) # multiline mode
129 \b # word boundary before variable name
130 (\w+)\s*=\s* # variable name and assignment
131 (
132 (?:
133 "(?:[^"\\]|\\.)*" # double-quoted string
134 | '(?:[^'\\]|\\.)*' # single-quoted string
135 | [^;]*? # or anything up to semicolon
136 )
137 )
138 \s*; # semicolon ends the assignment
139 """,
140 re.VERBOSE,
141 )
142
143 for match in regex.finditer(content):
144 key, value = match.groups()
145
146 # Clean value from the array indexes
147 value = re.sub(r"\[\d+\]", "", value)
148
149 # Try JSON
150 try:
151 js_variables[key] = json.loads(value.encode().decode("utf-8-sig"))
152 continue
153 except json.JSONDecodeError:
154 pass
155 try:
156 # Try python literal eval
157 js_variables[key] = ast.literal_eval(value)
158 continue
159 except (ValueError, SyntaxError):
160 pass
161 # Clean the value of quotes if it starts and ends with them
162 if (value.startswith("'") and value.endswith("'")) or (
163 value.startswith('"') and value.endswith('"')
164 ):
165 value = value[1:-1]
166 js_variables[key] = value
167
168 # Return the JS variables
169 return js_variables
170
171
172 @clean_input
173 def read_json_content(content: str | None, **kwargs: Any) -> dict[str, Any]:
174 """Get the json content."""
175
176 if not content:
177 return {}
178
179 # Random control characters to avoid json errors
180 for symbol in RANDOM_SYMBOLS:
181 content = content.replace(symbol, "")
182
183 # Handle missing values in JSON
184 content = re.sub(r"\s*,\s*,", ", ", content)
185 content = re.sub(r"^\s*{\s*,", "{", content)
186 content = re.sub(r",\s*}\s*$", "}", content)
187
188 # Handle keys without values
189 content = re.sub(r":\s*(,|\})", ": null\\1", content)
190
191 # Return the json content
192 try:
193 json_data = json.loads(content.encode().decode("utf-8-sig"))
194 if isinstance(json_data, dict):
195 return json_data
196 return {}
197 except json.JSONDecodeError as ex:
198 _LOGGER.error(
199 "Unable to decode json content with exception `%s`.\
200 Please, copy this and fill in a bug report: %s",
201 ex,
202 content,
203 )
204 return {}
205
206
207 @clean_input
208 def readable_mac(raw: str | None) -> bool:
209 """Check if string is MAC address."""
210
211 return bool(
212 isinstance(raw, str)
213 and re.search(
214 re.compile("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$"), raw
215 )
216 )
217
218
219 def read_units_as_base(
220 converter: type[UnitConverterBase],
221 units: Any,
222 check_calls: ARCallableType | list[ARCallableType] | None = None,
223 fallback_value: float = 0.0,
224 ) -> ARCallableType:
225 """Create a reader from the units to the base."""
226
227 if not isinstance(converter, type) or not issubclass(
228 converter, UnitConverterBase
229 ):
230 raise TypeError("Converter must be a subclass of UnitConverterBase")
231
232 # Convert single check call to a list
233 if check_calls is not None and not isinstance(check_calls, list):
234 check_calls = [check_calls]
235
236 def reader(value: Any) -> float:
237 """Read the value as a base unit."""
238
239 # Use the converter with explicit None on unsupported types
240 fval = safe_float(value)
241
242 # Convert to base if all the checks passed
243 if isinstance(fval, float) and (
244 check_calls is None or all(call(fval) for call in check_calls)
245 ):
246 return converter.convert_to_base(fval, units)
247
248 return fallback_value
249
250 return reader
251
252
253 def read_units_data_rate(units: UnitOfDataRate) -> ARCallableType:
254 """Read data rate values from the specified unit type."""
255
256 return read_units_as_base(
257 DataRateUnitConverter, units, is_non_negative, 0.0
258 )