Debian Codegraph @

ansible_collections/community/dns/plugins/module_utils/_adguardhome/api.py

raw
1 # Copyright (c) 2025 Markus Bergholz
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import json
11 import typing as t
12 from urllib.error import HTTPError
13
14 from ansible.module_utils.common.text.converters import to_native
15 from ansible.module_utils.urls import Request
16
17 from ansible_collections.community.dns.plugins.module_utils._argspec import ArgumentSpec
18
19 if t.TYPE_CHECKING:
20 _P = t.ParamSpec("_P") # pragma: no cover
21
22 FailJson = t.Callable[_P, t.NoReturn] # pragma: no cover
23
24
25 def create_adguardhome_argument_spec() -> ArgumentSpec:
26 return ArgumentSpec(
27 {
28 "username": {"type": "str", "required": True},
29 "password": {"type": "str", "required": True, "no_log": True},
30 "host": {"type": "str", "required": True},
31 "validate_certs": {"type": "bool", "default": True},
32 }
33 )
34
35
36 class AdGuardHomeAPIHandler:
37 def __init__(self, params: dict[str, t.Any], fail_json: FailJson) -> None:
38 host: str = params["host"] # type: ignore
39 self.url = f"{host}/control/rewrite"
40
41 self.validate_certs: bool = params["validate_certs"] # type: ignore
42 self.fail_json = fail_json
43 self.r = Request(
44 validate_certs=self.validate_certs,
45 url_username=params["username"],
46 url_password=params["password"],
47 force_basic_auth=True,
48 headers={"Content-Type": "application/json"},
49 )
50
51 def list(self) -> list[dict[str, t.Any]]:
52 try:
53 response = self.r.open("GET", f"{self.url}/list")
54
55 return json.loads(response.read().decode("utf-8"))
56
57 except HTTPError as e:
58 self.fail_json(msg=to_native(e.read()))
59
60 def add_or_delete(
61 self,
62 domain: str,
63 answer: str,
64 method: t.Literal["add", "delete"],
65 target: dict[str, t.Any],
66 ) -> t.Literal[True]:
67 """
68 the delete api requires the matching answer value.
69 but because we make the answer value optional, it's
70 taken from previous `find_and_compare` function.
71 """
72 if method == "add": # noqa: SIM108
73 answer_value = answer
74 else:
75 answer_value = target["answer"] if answer is None else answer
76
77 data = json.dumps({"domain": domain, "answer": answer_value}).encode("utf-8")
78 try:
79 self.r.open(
80 "POST",
81 f"{self.url}/{method}",
82 data=data,
83 )
84 return True
85
86 except HTTPError as e:
87 self.fail_json(msg=to_native(e.read()))
88
89 def update(
90 self, domain: str, answer: str, target: dict[str, t.Any]
91 ) -> t.Literal[True]:
92 data = json.dumps(
93 {"target": target, "update": {"domain": domain, "answer": answer}}
94 ).encode("utf-8")
95 try:
96 self.r.open(
97 "PUT",
98 f"{self.url}/update",
99 data=data,
100 )
101 return True
102
103 except HTTPError as e:
104 self.fail_json(msg=to_native(e.read()))