| 1 |
"""Update Clients endpoint module.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from json import JSONDecodeError |
| 6 |
import logging |
| 7 |
import re |
| 8 |
from typing import Any |
| 9 |
from urllib import parse |
| 10 |
|
| 11 |
from asusrouter.modules.data import AsusData |
| 12 |
from asusrouter.tools.cleaners import clean_dict, clean_dict_key |
| 13 |
from asusrouter.tools.readers import ( |
| 14 |
merge_dicts, |
| 15 |
read_json_content, |
| 16 |
readable_mac, |
| 17 |
) |
| 18 |
|
| 19 |
_LOGGER = logging.getLogger(__name__) |
| 20 |
|
| 21 |
|
| 22 |
LEGACY_WLAN: dict[str, int] = { |
| 23 |
"2g": 1, |
| 24 |
"5g": 2, |
| 25 |
"5g_2": 3, |
| 26 |
} |
| 27 |
|
| 28 |
|
| 29 |
def read(content: str, **kwargs: Any) -> dict[str, Any]: |
| 30 |
"""Read update clients data.""" |
| 31 |
|
| 32 |
update_clients: dict[str, Any] = {} |
| 33 |
|
| 34 |
# Our JSON data is between `originData =` and `networkmap_fullscan = ` |
| 35 |
regex = re.compile(r"originData = (.*)networkmap_fullscan = ") |
| 36 |
match = regex.search(content.replace("\n", "")) |
| 37 |
if match: |
| 38 |
# Old firmwares have a different format |
| 39 |
if "staticList" in match.group(1): |
| 40 |
_LOGGER.debug("Reading legacy update clients data") |
| 41 |
return read_legacy(match.group(1)) |
| 42 |
# Modern firmware |
| 43 |
_LOGGER.debug("Reading modern update clients data") |
| 44 |
content = ( |
| 45 |
match.group(1) |
| 46 |
.replace("fromNetworkmapd", '"fromNetworkmapd"') |
| 47 |
.replace("nmpClient :", '"nmpClient" :') |
| 48 |
) |
| 49 |
|
| 50 |
# Read the json content |
| 51 |
update_clients = read_json_content(content) |
| 52 |
|
| 53 |
return update_clients |
| 54 |
|
| 55 |
|
| 56 |
def read_legacy(content: str) -> dict[str, Any]: |
| 57 |
"""Read update clients data from legacy firmwares.""" |
| 58 |
|
| 59 |
clients: dict[str, Any] = {} |
| 60 |
|
| 61 |
data = read_legacy_as_json(content) |
| 62 |
|
| 63 |
# Networkmap |
| 64 |
read_legacy_networmap(clients, data.get("fromNetworkmapd")) |
| 65 |
# Staticlist |
| 66 |
read_legacy_staticlist(clients, data.get("staticList")) |
| 67 |
# Wlan list |
| 68 |
read_legacy_wlan_list(clients, data) |
| 69 |
# Wlan info |
| 70 |
read_legacy_wlan_info(clients, data) |
| 71 |
# nmpClient |
| 72 |
read_legacy_nmpclient(clients, data.get("nmpClient")) |
| 73 |
|
| 74 |
# Just so that we don't need to process it anyhow special |
| 75 |
# This will be compatible with the new format |
| 76 |
return {"fromNetworkmapd": [clients]} |
| 77 |
|
| 78 |
|
| 79 |
def read_legacy_as_json(content: str) -> dict[str, Any]: |
| 80 |
"""Read update clients data from legacy firmwares as JSON.""" |
| 81 |
|
| 82 |
# Step 0 - replace all `'` with `"` |
| 83 |
data = content.replace("'", '"') |
| 84 |
|
| 85 |
# Step 1 - remove all the replace and split statements |
| 86 |
to_replace = [ |
| 87 |
'.replace(/>/g, ">")', |
| 88 |
'.replace(/</g, "<")', |
| 89 |
'.split("<")', |
| 90 |
'.split(">")', |
| 91 |
] |
| 92 |
for replace in to_replace: |
| 93 |
data = data.replace(replace, "") |
| 94 |
|
| 95 |
# Step 2 - remove the `decodeURIComponent` statements |
| 96 |
data = data.replace("decodeURIComponent(", "").replace(")", "") |
| 97 |
|
| 98 |
# Step 3 - Remove the `{}` in the beginning and end, |
| 99 |
# also clean trailing and leading spaces |
| 100 |
data = data[1:-1].strip() |
| 101 |
|
| 102 |
# Step 4 - decode |
| 103 |
data = parse.unquote(data) |
| 104 |
|
| 105 |
# Step 5 - replace the keys by the regex |
| 106 |
# Find all `, [a-zA-Z0-9_]+:` where [a-zA-Z0-9_]+ |
| 107 |
# is the key and add `"` around the key |
| 108 |
data = re.sub(r", ?([a-zA-Z0-9_]+):", r',"\1":', data) |
| 109 |
|
| 110 |
# Step 6 - replace `customList` with `"customList"` |
| 111 |
data = data.replace("customList", '"customList"') |
| 112 |
|
| 113 |
# Step 7 - find `"wlList_2g": \[[.*]\]` as well as `"wlList_5g": \[[.*]\]` |
| 114 |
# and `"wlList_5g_2": \[[.*]\]` and replace them with `"wlList_2g": {[.*]}` |
| 115 |
# as well as `"wlList_5g": {[.*]}` and `"wlList_5g_2": {[.*]}` |
| 116 |
# Keep the content inside the brackets as is |
| 117 |
# Stop the regex search on the first occurence of the `]` so that we |
| 118 |
# don't match the last `]` |
| 119 |
data = re.sub( |
| 120 |
r'"wlList_2g": \[([^\]]*)\]', r'"wlList_2g": {\1}', data, count=1 |
| 121 |
) |
| 122 |
data = re.sub( |
| 123 |
r'"wlList_5g": \[([^\]]*)\]', r'"wlList_5g": {\1}', data, count=1 |
| 124 |
) |
| 125 |
data = re.sub( |
| 126 |
r'"wlList_5g_2": \[([^\]]*)\]', r'"wlList_5g_2": {\1}', data, count=1 |
| 127 |
) |
| 128 |
|
| 129 |
data = "{" + data + "}" |
| 130 |
try: |
| 131 |
return read_json_content(data) |
| 132 |
except JSONDecodeError: |
| 133 |
_LOGGER.debug("Failed to read legacy update clients data") |
| 134 |
return {} |
| 135 |
|
| 136 |
|
| 137 |
def read_legacy_networmap( |
| 138 |
output: dict[str, Any], networkmap: str | None |
| 139 |
) -> None: |
| 140 |
"""Read legacy networkmap to the output dict.""" |
| 141 |
|
| 142 |
if not networkmap: |
| 143 |
return |
| 144 |
|
| 145 |
client_list = networkmap.split("<") |
| 146 |
for client_line in client_list: |
| 147 |
if client_line == "": |
| 148 |
continue |
| 149 |
client = client_line.split(">") |
| 150 |
if len(client) < 4 or not readable_mac(client[3].upper()): # noqa: PLR2004 |
| 151 |
continue |
| 152 |
mac = client[3].upper() |
| 153 |
output[mac] = { |
| 154 |
"mac": mac, |
| 155 |
"name": client[1] if len(client) > 1 else None, |
| 156 |
"ip": client[2] if len(client) > 2 else None, # noqa: PLR2004 |
| 157 |
"ipMethod": "dhcp", |
| 158 |
"isWL": 0, |
| 159 |
"isOnline": 1, |
| 160 |
} |
| 161 |
|
| 162 |
|
| 163 |
def read_legacy_nmpclient( |
| 164 |
output: dict[str, Any], nmp_client: str | None |
| 165 |
) -> None: |
| 166 |
"""Read legacy nmpclient to the output dict.""" |
| 167 |
|
| 168 |
if not nmp_client: |
| 169 |
return |
| 170 |
|
| 171 |
client_list = nmp_client.split("<") |
| 172 |
for client_info in client_list: |
| 173 |
# Skip empty strings |
| 174 |
if client_info == "": |
| 175 |
continue |
| 176 |
# Split the string into a list by `>` |
| 177 |
client = client_info.split(">") |
| 178 |
# Check if client has enough elements |
| 179 |
if len(client) < 5: # noqa: PLR2004 |
| 180 |
continue |
| 181 |
# 0 element is the MAC address written in lowercase and without `:` |
| 182 |
# We need to convert it to uppercase and add `:` |
| 183 |
mac = ":".join([client[0][i : i + 2].upper() for i in range(0, 12, 2)]) |
| 184 |
client_type = client[4] if len(client) > 4 else None # noqa: PLR2004 |
| 185 |
if mac in output: |
| 186 |
output[mac]["type"] = client_type |
| 187 |
continue |
| 188 |
output[mac] = { |
| 189 |
"mac": mac, |
| 190 |
"name": client[2] if len(client) > 2 else None, # noqa: PLR2004 |
| 191 |
"type": client_type, |
| 192 |
"isOnline": 0, |
| 193 |
} |
| 194 |
|
| 195 |
|
| 196 |
def read_legacy_staticlist( |
| 197 |
output: dict[str, Any], static_list: str | None |
| 198 |
) -> None: |
| 199 |
"""Read legacy staticlist to the output dict.""" |
| 200 |
|
| 201 |
if not static_list: |
| 202 |
return |
| 203 |
|
| 204 |
client_list = static_list.split("<") |
| 205 |
for client_line in client_list: |
| 206 |
if client_line == "": |
| 207 |
continue |
| 208 |
client = client_line.split(">") |
| 209 |
mac = client[0].upper() |
| 210 |
if not readable_mac(mac): |
| 211 |
continue |
| 212 |
if mac in output: |
| 213 |
output[mac]["ipMethod"] = "static" |
| 214 |
continue |
| 215 |
output[mac] = { |
| 216 |
"mac": mac, |
| 217 |
"name": client[2] if len(client) > 2 else None, # noqa: PLR2004 |
| 218 |
"ip": client[1] if len(client) > 1 else None, |
| 219 |
"ipMethod": "static", |
| 220 |
"isWL": 0, |
| 221 |
"isOnline": 0, |
| 222 |
} |
| 223 |
|
| 224 |
|
| 225 |
def read_legacy_wlan_info( |
| 226 |
output: dict[str, Any], data: dict[str, Any] |
| 227 |
) -> None: |
| 228 |
"""Read legacy wlan info to the output dict.""" |
| 229 |
|
| 230 |
for wlan in LEGACY_WLAN: |
| 231 |
wlan_info = data.get(f"wlListInfo_{wlan}") |
| 232 |
if not wlan_info: |
| 233 |
continue |
| 234 |
|
| 235 |
for client in wlan_info: |
| 236 |
mac = client[0].upper() |
| 237 |
if not readable_mac(mac): |
| 238 |
continue |
| 239 |
cur_tx = client[1] if len(client) > 1 else None |
| 240 |
cur_rx = client[2] if len(client) > 2 else None # noqa: PLR2004 |
| 241 |
wl_connect_time = client[3] if len(client) > 3 else None # noqa: PLR2004 |
| 242 |
if mac in output: |
| 243 |
output[mac]["curTx"] = cur_tx |
| 244 |
output[mac]["curRx"] = cur_rx |
| 245 |
output[mac]["wlConnectTime"] = wl_connect_time |
| 246 |
continue |
| 247 |
output[mac] = { |
| 248 |
"mac": mac, |
| 249 |
"curTx": cur_tx, |
| 250 |
"curRx": cur_rx, |
| 251 |
"wlConnectTime": wl_connect_time, |
| 252 |
} |
| 253 |
|
| 254 |
|
| 255 |
def read_legacy_wlan_list( |
| 256 |
output: dict[str, Any], data: dict[str, Any] |
| 257 |
) -> None: |
| 258 |
"""Read legacy wlan list to the output dict.""" |
| 259 |
|
| 260 |
for wlan, wid in LEGACY_WLAN.items(): |
| 261 |
wlan_list = data.get(f"wlList_{wlan}") |
| 262 |
if not wlan_list: |
| 263 |
continue |
| 264 |
|
| 265 |
for mac, client in wlan_list.items(): |
| 266 |
if not readable_mac(mac): |
| 267 |
continue |
| 268 |
rssi = client.get("rssi") |
| 269 |
if mac in output: |
| 270 |
output[mac]["isWL"] = wid |
| 271 |
output[mac]["rssi"] = rssi |
| 272 |
output[mac]["isOnline"] = 1 |
| 273 |
continue |
| 274 |
output[mac] = { |
| 275 |
"mac": mac, |
| 276 |
"isWL": wid, |
| 277 |
"rssi": rssi, |
| 278 |
"isOnline": 1, |
| 279 |
} |
| 280 |
|
| 281 |
|
| 282 |
def process(data: dict[str, Any]) -> dict[AsusData, Any]: |
| 283 |
"""Process the update clients data.""" |
| 284 |
|
| 285 |
state: dict[AsusData, Any] = {} |
| 286 |
|
| 287 |
# Clients from Networkmapd |
| 288 |
clients = { |
| 289 |
mac: description |
| 290 |
for mac, description in data.get("fromNetworkmapd", [{}])[0].items() |
| 291 |
if readable_mac(mac) |
| 292 |
} |
| 293 |
|
| 294 |
# Clients from nmpClient |
| 295 |
clients_historic = { |
| 296 |
mac: description |
| 297 |
for mac, description in data.get("nmpClient", [{}])[0].items() |
| 298 |
if readable_mac(mac) |
| 299 |
} |
| 300 |
|
| 301 |
# Merge states |
| 302 |
clients = merge_dicts(clients, clients_historic) |
| 303 |
# Clean the clients |
| 304 |
clean_dict(clients) |
| 305 |
# Clean the clients from the `from` field |
| 306 |
clients = clean_dict_key(clients, "from") |
| 307 |
|
| 308 |
state[AsusData.CLIENTS] = clients |
| 309 |
|
| 310 |
return state |