Debian Codegraph @

asusrouter/modules/endpoint/__init__.py

raw
1 """Endpoint module for AsusRouter."""
2
3 from __future__ import annotations
4
5 from collections.abc import Awaitable, Callable
6 from concurrent.futures import ThreadPoolExecutor
7 from enum import Enum
8 import importlib
9 import logging
10 from types import ModuleType
11 from typing import Any, Final
12
13 from asusrouter.const import HTTPStatus, RequestType
14 from asusrouter.error import AsusRouter404Error, AsusRouterRequestFormatError
15 from asusrouter.modules.data import AsusData, AsusDataState
16 from asusrouter.modules.firmware import Firmware
17 from asusrouter.modules.wlan import Wlan
18
19 _LOGGER = logging.getLogger(__name__)
20
21
22 class Endpoint(str, Enum):
23 """Endpoint enum.
24
25 These endpoints are used to receive data from the device.
26 """
27
28 CERT_INFO = "ajax_certinfo.asp"
29 DDNS_CODE = "ajax_ddnscode.asp"
30 DEVICEMAP = "ajax_status.xml"
31 DSL = "ajax_AdslStatus.asp"
32 ETHERNET_PORTS = "ajax_ethernet_ports.asp"
33 FIRMWARE = "detect_firmware.asp"
34 FIRMWARE_NOTE = "release_note0.asp"
35 FIRMWARE_NOTE_AIMESH = "release_note_amas.asp"
36 HOOK = "appGet.cgi"
37 NETWORKMAPD = "update_networkmapd.asp"
38 ONBOARDING = "ajax_onboarding.asp"
39 PORT_STATUS = "get_port_status.cgi"
40 STATE = "state.js"
41 SYSINFO = "ajax_sysinfo.asp"
42 TEMPERATURE = "ajax_coretmp.asp"
43 UPDATE_CLIENTS = "update_clients.asp"
44 VPN = "ajax_vpn_status.asp"
45 # Endpoints known but not used / not available on test devices
46 # RGB = "light_effect.html"
47
48
49 class EndpointControl(str, Enum):
50 """Control endpoint enum.
51
52 These endpoints are used to set parameters to the device.
53 """
54
55 APPLY = "apply.cgi"
56 COMMAND = "applyapp.cgi"
57
58
59 class EndpointService(str, Enum):
60 """Service endpoints."""
61
62 LOGIN = "login.cgi"
63 LOGOUT = "Logout.asp"
64
65
66 class EndpointTools(str, Enum):
67 """Tools endpoints."""
68
69 # AURA control / RGB
70 AURA = "set_ledg.cgi"
71 # Network tools: ping, jitter, loss
72 NETWORK = "netool.cgi"
73 # Traffic analysis group
74 TRAFFIC_BACKHAUL = "get_diag_sta_traffic.cgi"
75 TRAFFIC_ETHERNET = "get_diag_eth_traffic.cgi"
76 TRAFFIC_WIFI = "get_diag_wifi_traffic.cgi"
77
78
79 class EndpointNoCheck(str, Enum):
80 """Endpoints that should not be checked for availability."""
81
82 # AURA control / RGB
83 AURA = "set_ledg.cgi"
84
85
86 # Typehint for the endpoint
87 EndpointType = Endpoint | EndpointControl | EndpointService | EndpointTools
88
89
90 # Force request type for the endpoint
91 ENDPOINT_FORCE_REQUEST = {
92 Endpoint.PORT_STATUS: RequestType.GET,
93 EndpointTools.NETWORK: RequestType.GET,
94 EndpointTools.TRAFFIC_BACKHAUL: RequestType.GET,
95 EndpointTools.TRAFFIC_ETHERNET: RequestType.GET,
96 EndpointTools.TRAFFIC_WIFI: RequestType.GET,
97 }
98
99
100 SENSITIVE_ENDPOINTS: Final[frozenset[EndpointType]] = frozenset(
101 {
102 EndpointService.LOGIN,
103 EndpointControl.APPLY,
104 }
105 )
106
107
108 def get_request_type(endpoint: EndpointType) -> RequestType | None:
109 """Get the request type for the endpoint."""
110
111 return ENDPOINT_FORCE_REQUEST.get(endpoint, RequestType.POST)
112
113
114 def is_sensitive_endpoint(endpoint: EndpointType) -> bool:
115 """Check if the endpoint is sensitive."""
116
117 return endpoint in SENSITIVE_ENDPOINTS
118
119
120 def _get_module(
121 endpoint: EndpointType,
122 ) -> ModuleType | None:
123 """Attempt to get the module for the endpoint."""
124
125 try:
126 # Get the module name from the endpoint
127 module_name = f"asusrouter.modules.endpoint.{endpoint.name.lower()}"
128
129 # Import the module in a separate thread
130 # to avoid blocking the main thread
131 with ThreadPoolExecutor(max_workers=1) as executor:
132 future = executor.submit(importlib.import_module, module_name)
133 # Return the module
134 return future.result()
135
136 except ModuleNotFoundError:
137 _LOGGER.debug("No module found for endpoint %s", endpoint)
138 return None
139
140
141 def read(
142 endpoint: EndpointType,
143 content: str,
144 **kwargs: Any,
145 ) -> dict[str, Any]:
146 """Read the data from an endpoint."""
147
148 _LOGGER.debug("Reading data from endpoint %s", endpoint)
149
150 # Get the module
151 submodule = _get_module(endpoint)
152
153 # Read the data if module found
154 if submodule:
155 result = submodule.read(content, **kwargs)
156 if isinstance(result, dict):
157 return result
158 return {}
159
160 return {}
161
162
163 def process(
164 endpoint: Endpoint,
165 data: dict[str, Any],
166 history: dict[AsusData, AsusDataState] | None = None,
167 firmware: Firmware | None = None,
168 wlan: list[Wlan] | None = None,
169 ) -> dict[AsusData, Any]:
170 """Process the data from an endpoint."""
171
172 _LOGGER.debug("Processing data from endpoint %s", endpoint)
173
174 # Get the module
175 submodule = _get_module(endpoint)
176
177 # Process the data if module found
178 if submodule:
179 # Check if the submodule requires history
180 require_history = getattr(submodule, "REQUIRE_HISTORY", False)
181 if require_history:
182 data_set(data, history=history)
183 # Check if the submodule requires identity
184 require_firmware = getattr(submodule, "REQUIRE_FIRMWARE", False)
185 if require_firmware:
186 data_set(data, firmware=firmware)
187 # Check if the submodule requires wlan
188 require_wlan = getattr(submodule, "REQUIRE_WLAN", False)
189 if require_wlan:
190 data_set(data, wlan=wlan)
191
192 # Process the data
193 try:
194 result = submodule.process(data)
195 if isinstance(result, dict):
196 return result
197 return {}
198 # Consider attribute and value errors to be possible
199 # in case of unexpected data structure
200 except (AttributeError, ValueError) as ex:
201 _LOGGER.error(
202 "Error processing data from endpoint %s: %s",
203 endpoint,
204 ex,
205 )
206 return {}
207
208 return {}
209
210
211 def data_set(data: dict[str, Any], **kwargs: Any) -> dict[str, Any]:
212 """Append the data to the data dict."""
213
214 # Update the data dict with kwargs using dictionary comprehension
215 data.update(dict(kwargs.items()))
216
217 # Return the data
218 return data
219
220
221 def data_get(data: dict[str, Any], key: str) -> Any | None:
222 """Extract value from the data dict and update the data dict."""
223
224 # Get the value
225 value = data.get(key)
226
227 # Remove the value from the data dict
228 data.pop(key, None)
229
230 # Return the value
231 return value
232
233
234 async def check_available(
235 endpoint: Endpoint | EndpointTools,
236 api_query: Callable[..., Awaitable[Any]],
237 ) -> tuple[bool, Any | None]:
238 """Check whether the endpoint is available or returns 404."""
239
240 try:
241 status, _, content = await api_query(endpoint)
242 if status == HTTPStatus.OK:
243 return (True, content)
244 except AsusRouterRequestFormatError:
245 return (True, None)
246 except AsusRouter404Error:
247 return (False, None)
248
249 return (False, None)