Debian Codegraph @

src/adguardhome/adguardhome.py

raw
1 """Asynchronous Python client for the AdGuard Home API."""
2
3 from __future__ import annotations
4
5 import asyncio
6 import json
7 import socket
8 from typing import Any, Mapping, Self
9
10 import aiohttp
11 from yarl import URL
12
13 from .exceptions import AdGuardHomeConnectionError, AdGuardHomeError
14 from .filtering import AdGuardHomeFiltering
15 from .parental import AdGuardHomeParental
16 from .querylog import AdGuardHomeQueryLog
17 from .safebrowsing import AdGuardHomeSafeBrowsing
18 from .safesearch import AdGuardHomeSafeSearch
19 from .stats import AdGuardHomeStats
20
21
22 # pylint: disable=too-many-instance-attributes
23 class AdGuardHome:
24 """Main class for handling connections with AdGuard Home."""
25
26 # pylint: disable-next=too-many-arguments
27 def __init__( # noqa: PLR0913
28 self,
29 host: str,
30 *,
31 base_path: str = "/control",
32 password: str | None = None,
33 port: int = 3000,
34 request_timeout: int = 10,
35 session: aiohttp.client.ClientSession | None = None,
36 tls: bool = False,
37 username: str | None = None,
38 verify_ssl: bool = True,
39 ) -> None:
40 """Initialize connection with AdGuard Home.
41
42 Class constructor for setting up an AdGuard Home object to
43 communicate with an AdGuard Home instance.
44
45 Args:
46 ----
47 host: Hostname or IP address of the AdGuard Home instance.
48 base_path: Base path of the API, usually `/control`, which is the default.
49 password: Password for HTTP auth, if enabled.
50 port: Port on which the API runs, usually 3000.
51 request_timeout: Max timeout to wait for a response from the API.
52 session: Optional, shared, aiohttp client session.
53 tls: True, when TLS/SSL should be used.
54 username: Username for HTTP auth, if enabled.
55 verify_ssl: Can be set to false, when TLS with self-signed cert is used.
56
57 """
58 self._session = session
59 self._close_session = False
60
61 self.base_path = base_path
62 self.host = host
63 self.password = password
64 self.port = port
65 self.request_timeout = request_timeout
66 self.tls = tls
67 self.username = username
68 self.verify_ssl = verify_ssl
69
70 if self.base_path[-1] != "/":
71 self.base_path += "/"
72
73 self.filtering = AdGuardHomeFiltering(self)
74 self.parental = AdGuardHomeParental(self)
75 self.querylog = AdGuardHomeQueryLog(self)
76 self.safebrowsing = AdGuardHomeSafeBrowsing(self)
77 self.safesearch = AdGuardHomeSafeSearch(self)
78 self.stats = AdGuardHomeStats(self)
79
80 # pylint: disable-next=too-many-arguments, too-many-locals
81 async def request( # noqa: PLR0913
82 self,
83 uri: str,
84 method: str = "GET",
85 data: Any | None = None,
86 json_data: dict[str, Any] | None = None,
87 params: Mapping[str, str] | None = None,
88 ) -> dict[str, Any]:
89 """Handle a request to the AdGuard Home instance.
90
91 Make a request against the AdGuard Home API and handles the response.
92
93 Args:
94 ----
95 uri: The request URI on the AdGuard Home API to call.
96 method: HTTP method to use for the request; e.g., GET, POST.
97 data: RAW HTTP request data to send with the request.
98 json_data: Dictionary of data to send as JSON with the request.
99 params: Mapping of request parameters to send with the request.
100
101 Returns:
102 -------
103 The response from the API. In case the response is a JSON response,
104 the method will return a decoded JSON response as a Python
105 dictionary. In other cases, it will return the RAW text response.
106
107 Raises:
108 ------
109 AdGuardHomeConnectionError: An error occurred while communicating
110 with the AdGuard Home instance (connection issues).
111 AdGuardHomeError: An error occurred while processing the
112 response from the AdGuard Home instance (invalid data).
113
114 """
115 scheme = "https" if self.tls else "http"
116 url = URL.build(
117 scheme=scheme, host=self.host, port=self.port, path=self.base_path
118 ).join(URL(uri))
119
120 auth = None
121 if self.username and self.password:
122 auth = aiohttp.BasicAuth(self.username, self.password)
123
124 headers = {
125 "Accept": "application/json, text/plain, */*",
126 }
127
128 if self._session is None:
129 self._session = aiohttp.ClientSession()
130 self._close_session = True
131
132 skip_auto_headers = None
133 if data is None and json_data is None:
134 skip_auto_headers = {"Content-Type"}
135
136 try:
137 async with asyncio.timeout(self.request_timeout):
138 response = await self._session.request(
139 method,
140 url,
141 auth=auth,
142 data=data,
143 json=json_data,
144 params=params,
145 headers=headers,
146 ssl=self.verify_ssl,
147 skip_auto_headers=skip_auto_headers,
148 )
149 except asyncio.TimeoutError as exception:
150 msg = "Timeout occurred while connecting to AdGuard Home instance."
151 raise AdGuardHomeConnectionError(msg) from exception
152 except (aiohttp.ClientError, socket.gaierror) as exception:
153 msg = "Error occurred while communicating with AdGuard Home."
154 raise AdGuardHomeConnectionError(msg) from exception
155
156 content_type = response.headers.get("Content-Type", "")
157 if response.status // 100 in [4, 5]:
158 contents = await response.read()
159 response.close()
160
161 if content_type == "application/json":
162 raise AdGuardHomeError(
163 response.status, json.loads(contents.decode("utf8"))
164 )
165 raise AdGuardHomeError(
166 response.status, {"message": contents.decode("utf8")}
167 )
168
169 if "application/json" in content_type:
170 return await response.json()
171
172 text = await response.text()
173 return {"message": text}
174
175 async def protection_enabled(self) -> bool:
176 """Return if AdGuard Home protection is enabled or not.
177
178 Returns
179 -------
180 The status of the protection of the AdGuard Home instance.
181
182 """
183 response = await self.request("status")
184 return response["protection_enabled"]
185
186 async def enable_protection(self) -> None:
187 """Enable AdGuard Home protection.
188
189 Raises
190 ------
191 AdGuardHomeError: Failed enabling AdGuard Home protection.
192
193 """
194 try:
195 await self.request(
196 "dns_config",
197 method="POST",
198 json_data={"protection_enabled": True},
199 )
200 except AdGuardHomeError as exception:
201 msg = "Failed enabling AdGuard Home protection"
202 raise AdGuardHomeError(msg) from exception
203
204 async def disable_protection(self) -> None:
205 """Disable AdGuard Home protection.
206
207 Raises
208 ------
209 AdGuardHomeError: Failed disabling the AdGuard Home protection.
210
211 """
212 try:
213 await self.request(
214 "dns_config",
215 method="POST",
216 json_data={"protection_enabled": False},
217 )
218 except AdGuardHomeError as exception:
219 msg = "Failed disabling AdGuard Home protection"
220 raise AdGuardHomeError(msg) from exception
221
222 async def version(self) -> str:
223 """Return the current version of the AdGuard Home instance.
224
225 Returns
226 -------
227 The version number of the connected AdGuard Home instance.
228
229 """
230 response = await self.request("status")
231 return response["version"]
232
233 async def close(self) -> None:
234 """Close open client session."""
235 if self._session and self._close_session:
236 await self._session.close()
237
238 async def __aenter__(self) -> Self:
239 """Async enter.
240
241 Returns
242 -------
243 The AdGuard Home object.
244
245 """
246 return self
247
248 async def __aexit__(self, *_exc_info: object) -> None:
249 """Async exit.
250
251 Args:
252 ----
253 _exc_info: Exec type.
254
255 """
256 await self.close()