Debian Codegraph @

asusrouter/tools/writers.py

raw
1 """Writers module.
2
3 This module contains the writers for AsusRouter,
4 which prepare data to be sent to the router.
5 """
6
7 from __future__ import annotations
8
9 from collections.abc import Mapping
10 from typing import Any, Final
11 from urllib.parse import quote_plus
12
13 from asusrouter.config import (
14 CONFIG_DEFAULT_ALREADY_NOTIFIED,
15 ARConfigBase,
16 ARConfigKeyBase,
17 )
18 from asusrouter.const import RequestType
19 from asusrouter.tools.converters import clean_input
20 from asusrouter.tools.identifiers import MacAddress
21
22 REQUEST_DELIMITER: Final[dict[RequestType, str]] = {
23 RequestType.GET: "&",
24 RequestType.POST: ";",
25 }
26
27
28 @clean_input
29 def nvram(content: str | list[str] | None = None) -> str | None:
30 """NVRAM writer.
31
32 This function converts a list of strings (or a single string)
33 into a string request to the NVRAM read endpoint.
34 """
35
36 if isinstance(content, str):
37 return f"nvram_get({content});"
38
39 if isinstance(content, list):
40 return "".join([f"nvram_get({item});" for item in content])
41
42 return None
43
44
45 @clean_input
46 def dict_to_request(
47 data: Mapping[str, Any], request_type: RequestType = RequestType.POST
48 ) -> str:
49 """Convert a mapping to a request string.
50
51 - For RequestType.GET keys and values are URL-quoted (quote_plus) and
52 pairs are joined with '&'.
53 - For RequestType.POST keys and values are escaped for single-quotes and
54 pairs are joined with ';'.
55 """
56 if not data:
57 return ""
58
59 delimiter = REQUEST_DELIMITER.get(
60 request_type, REQUEST_DELIMITER[RequestType.GET]
61 )
62 parts: list[str] = []
63
64 for key, value in data.items():
65 # Normalize value (handle MacAddress specially)
66 if isinstance(value, MacAddress):
67 val_str = value.as_asus()
68 elif isinstance(value, bool):
69 # Device-friendly boolean representation
70 val_str = "1" if value else "0"
71 else:
72 val_str = "" if value is None else str(value)
73
74 if request_type == RequestType.GET:
75 k = quote_plus(str(key))
76 v = quote_plus(val_str)
77 parts.append(f"{k}={v}")
78 else: # POST
79 # Escape single quotes to avoid breaking the 'key':'value' syntax
80 esc_k = str(key).replace("'", "\\'")
81 esc_v = val_str.replace("'", "\\'")
82 parts.append(f"'{esc_k}':'{esc_v}'")
83
84 return delimiter.join(parts) if parts else ""
85
86
87 def ensure_notification_flag(
88 config: ARConfigBase,
89 key: ARConfigKeyBase,
90 ) -> None:
91 """Ensure notification flag exists in the configs."""
92
93 if key not in config:
94 config.register(key)
95 config.set(
96 key,
97 CONFIG_DEFAULT_ALREADY_NOTIFIED,
98 )