unifi-controller-api 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,28 @@
1
+ class UnifiControllerError(Exception):
2
+ """Base exception for UnifiController errors."""
3
+
4
+ pass
5
+
6
+
7
+ class UnifiAuthenticationError(UnifiControllerError):
8
+ """Raised when authentication with the UniFi Controller fails."""
9
+
10
+ pass
11
+
12
+
13
+ class UnifiAPIError(UnifiControllerError):
14
+ """Raised when an API call to the UniFi Controller fails."""
15
+
16
+ pass
17
+
18
+
19
+ class UnifiDataError(UnifiControllerError):
20
+ """Raised when there is an error parsing data from the UniFi Controller."""
21
+
22
+ pass
23
+
24
+
25
+ class UnifiModelError(UnifiControllerError):
26
+ """Raised when there is an error loading or processing device models."""
27
+
28
+ pass
@@ -0,0 +1,141 @@
1
+ """
2
+ Functions for exporting UniFi device information to various formats.
3
+
4
+ This module provides simple export utilities for UniFi device data,
5
+ allowing export to CSV, JSON, and Python dictionaries without external dependencies.
6
+ """
7
+
8
+ import csv
9
+ import json
10
+ from typing import Any, Dict, List, Optional, TypeVar
11
+
12
+ from .models.device import UnifiDevice
13
+ from .models.site import UnifiSite
14
+ from .logging import get_logger
15
+
16
+ logger = get_logger(__name__)
17
+
18
+ T = TypeVar("T", UnifiDevice, UnifiSite)
19
+
20
+
21
+ class UnifiEncoder(json.JSONEncoder):
22
+ def default(self, obj):
23
+ if hasattr(obj, "to_dict") and callable(getattr(obj, "to_dict")):
24
+ return obj.to_dict()
25
+ try:
26
+ return super().default(obj)
27
+ except TypeError:
28
+ return str(obj)
29
+
30
+
31
+ def to_dict_list(items: List[T]) -> List[Dict[str, Any]]:
32
+ """
33
+ Convert a list of UniFi model objects to a list of dictionaries.
34
+
35
+ This is useful for further processing or serialization.
36
+
37
+ Args:
38
+ items: List of UniFi model objects (UnifiDevice or UnifiSite)
39
+
40
+ Returns:
41
+ List of dictionaries with standardized structure
42
+ """
43
+ result = []
44
+
45
+ for item in items:
46
+ if hasattr(item, "to_dict") and callable(getattr(item, "to_dict")):
47
+ result.append(item.to_dict())
48
+ elif isinstance(item, dict):
49
+ result.append(item)
50
+
51
+ return result
52
+
53
+
54
+ def _flatten_dict(
55
+ d: Dict[str, Any], parent_key: str = "", sep: str = "_"
56
+ ) -> Dict[str, Any]:
57
+ """
58
+ Flatten nested dictionaries using a separator.
59
+
60
+ Args:
61
+ d: Dictionary to flatten
62
+ parent_key: Key of the parent dictionary (used in recursion)
63
+ sep: Separator to use between keys (default: '_')
64
+
65
+ Returns:
66
+ Flattened dictionary with no nested structures
67
+ """
68
+ items = []
69
+ for k, v in d.items():
70
+ new_key = f"{parent_key}{sep}{k}" if parent_key else k
71
+ if isinstance(v, dict):
72
+ items.extend(_flatten_dict(v, new_key, sep=sep).items())
73
+ elif isinstance(v, list):
74
+ if v and all(isinstance(i, dict) for i in v):
75
+ for i, item in enumerate(v):
76
+ items.extend(_flatten_dict(item, f"{new_key}_{i}", sep=sep).items())
77
+ else:
78
+ items.append((new_key, ", ".join(str(i) for i in v)))
79
+ else:
80
+ items.append((new_key, v))
81
+
82
+ return dict(items)
83
+
84
+
85
+ def export_csv(
86
+ items: List[T],
87
+ path: str,
88
+ fields: Optional[List[str]] = None,
89
+ flatten_nested: bool = False,
90
+ ) -> None:
91
+ """
92
+ Export UniFi objects to a CSV file.
93
+
94
+ Args:
95
+ items: List of UniFi model objects (UnifiDevice or UnifiSite)
96
+ path: Path where the CSV file will be saved
97
+ fields: Optional list of specific fields to include in the export.
98
+ If not provided, all fields will be exported.
99
+ flatten_nested: Whether to flatten nested structures using dot notation (default: False)
100
+ For example, uplink.type becomes uplink_type
101
+ """
102
+ item_dicts = to_dict_list(items)
103
+
104
+ if not item_dicts:
105
+ with open(path, "w", newline="", encoding="utf-8") as csvfile:
106
+ csvfile.write("")
107
+ return
108
+
109
+ if flatten_nested:
110
+ item_dicts = [_flatten_dict(item) for item in item_dicts]
111
+ item_dicts = [d for d in item_dicts if d]
112
+ if not item_dicts:
113
+ with open(path, "w", newline="", encoding="utf-8") as csvfile:
114
+ csvfile.write("")
115
+ return
116
+
117
+ if fields:
118
+ final_fields = fields
119
+ else:
120
+ final_fields = list(item_dicts[0].keys())
121
+
122
+ with open(path, "w", newline="", encoding="utf-8") as csvfile:
123
+ writer = csv.DictWriter(csvfile, fieldnames=final_fields, extrasaction="ignore")
124
+ writer.writeheader()
125
+
126
+ writer.writerows(item_dicts)
127
+
128
+
129
+ def export_json(items: List[T], path: str, indent: int = 2) -> None:
130
+ """
131
+ Export UniFi objects to a JSON file.
132
+
133
+ Args:
134
+ items: List of UniFi model objects (UnifiDevice or UnifiSite)
135
+ path: Path where the JSON file will be saved
136
+ indent: Number of spaces for indentation in the JSON file (default: 2)
137
+ """
138
+ item_dicts = to_dict_list(items)
139
+
140
+ with open(path, "w", encoding="utf-8") as jsonfile:
141
+ json.dump(item_dicts, jsonfile, indent=indent, cls=UnifiEncoder)
@@ -0,0 +1,95 @@
1
+ import logging
2
+ import json
3
+ from typing import Any, Dict, Optional
4
+
5
+
6
+ def get_logger(name: Optional[str] = None) -> logging.Logger:
7
+ """
8
+ Get a logger with the appropriate name.
9
+
10
+ Args:
11
+ name: Optional specific logger name. If not provided, uses the module's __name__.
12
+
13
+ Returns:
14
+ A logger instance for the specified name
15
+ """
16
+ if name is None:
17
+ return logging.getLogger("unifi_controller_api")
18
+ elif name.startswith("unifi_controller_api"):
19
+ return logging.getLogger(name)
20
+ else:
21
+ return logging.getLogger(f"unifi_controller_api.{name}")
22
+
23
+
24
+ def log_extra_fields(
25
+ logger: logging.Logger,
26
+ obj_name: str,
27
+ obj_id: str,
28
+ extra_fields: Dict[str, Any],
29
+ max_length: int = 300,
30
+ ):
31
+ """
32
+ Log extra fields found in an object using the provided logger.
33
+
34
+ Args:
35
+ logger: Logger to use
36
+ obj_name: Name of the object type (e.g., 'Device', 'Site').
37
+ obj_id: Identifier for the specific object (e.g., MAC address, site name).
38
+ extra_fields: Dictionary of extra fields.
39
+ max_length: Maximum length for field values in the log. Default is 300.
40
+ """
41
+ if not extra_fields:
42
+ logger.debug(f"No extra fields for {obj_name} {obj_id}")
43
+ return
44
+
45
+ truncated_fields = {}
46
+ for key, value in extra_fields.items():
47
+ if isinstance(value, (dict, list)):
48
+ try:
49
+ value_str = json.dumps(value)
50
+ if len(value_str) > max_length:
51
+ value_str = value_str[:max_length] + "... [truncated]"
52
+ truncated_fields[key] = value_str
53
+ except (TypeError, ValueError):
54
+ truncated_fields[key] = f"<complex structure: {type(value).__name__}>"
55
+ elif isinstance(value, str) and len(value) > max_length:
56
+ truncated_fields[key] = value[:max_length] + "... [truncated]"
57
+ else:
58
+ truncated_fields[key] = value
59
+
60
+ logger.debug(
61
+ f"Extra fields for {obj_name} {obj_id}: {json.dumps(truncated_fields, indent=2)}"
62
+ )
63
+
64
+
65
+ def log_api_response(
66
+ logger: logging.Logger,
67
+ url: str,
68
+ response_data: Dict[str, Any],
69
+ status_code: int,
70
+ truncate: bool = True,
71
+ max_length: int = 500,
72
+ ):
73
+ """
74
+ Log API response data using the provided logger.
75
+
76
+ Args:
77
+ logger: Logger to use
78
+ url: The API URL that was called.
79
+ response_data: The response data as a dictionary.
80
+ status_code: HTTP status code.
81
+ truncate: Whether to truncate large response values. Default is True.
82
+ max_length: Maximum length for response in the log if truncated. Default is 500.
83
+ """
84
+ try:
85
+ response_str = json.dumps(response_data)
86
+ if truncate and len(response_str) > max_length:
87
+ response_str = response_str[:max_length] + "... [truncated]"
88
+
89
+ logger.debug(
90
+ f"API Response from {url} (Status: {status_code}):\n{response_str}"
91
+ )
92
+ except (TypeError, ValueError) as e:
93
+ logger.debug(
94
+ f"API Response from {url} (Status: {status_code}) - Error serializing: {e}"
95
+ )
@@ -0,0 +1,191 @@
1
+ """
2
+ Utility functions for the UniFi Controller API package.
3
+ """
4
+
5
+ import inspect
6
+ import json
7
+ import os
8
+ import dataclasses
9
+ from typing import Any, Dict, List, Type, Optional, Tuple
10
+
11
+ from .models.device import UnifiDevice
12
+ from .logging import get_logger
13
+ from .exceptions import UnifiModelError
14
+
15
+ logger = get_logger(__name__)
16
+
17
+
18
+ def get_api_field_mapping(model_class: Type) -> Dict[str, str]:
19
+ """
20
+ Create a mapping between API field names and model attribute names.
21
+
22
+ Examines dataclass fields with metadata to find mappings between
23
+ API field names (like 'user-num_sta') and Python attribute names (like 'user_num_sta').
24
+
25
+ Args:
26
+ model_class: The dataclass model to examine for field mappings
27
+
28
+ Returns:
29
+ Dictionary mapping UniFi API field names to Python model attribute names
30
+ """
31
+ if not dataclasses.is_dataclass(model_class):
32
+ return {}
33
+
34
+ field_mapping = {}
35
+
36
+ for field in dataclasses.fields(model_class):
37
+ if hasattr(field, "metadata") and "unifi_api_field" in field.metadata:
38
+ api_field_name = field.metadata["unifi_api_field"]
39
+ field_mapping[api_field_name] = field.name
40
+
41
+ return field_mapping
42
+
43
+
44
+ def filter_valid_fields(data: Dict[str, Any], model_class: Type) -> Dict[str, Any]:
45
+ """
46
+ Filter a dictionary to only include fields that are valid for the model class.
47
+
48
+ Args:
49
+ data: Input dictionary with potentially invalid fields
50
+ model_class: The model class to filter fields for
51
+
52
+ Returns:
53
+ Dictionary containing only fields that are valid parameters for the model class
54
+ """
55
+ signature = inspect.signature(model_class.__init__)
56
+ valid_params = set(signature.parameters.keys())
57
+
58
+ valid_params.discard("self")
59
+
60
+ field_map = get_api_field_mapping(model_class)
61
+
62
+ result = {}
63
+ for k, v in data.items():
64
+ if k in valid_params:
65
+ result[k] = v
66
+ elif k in field_map and field_map[k] in valid_params:
67
+ mapped_key = field_map[k]
68
+ result[mapped_key] = v
69
+
70
+ return result
71
+
72
+
73
+ def extract_extra_fields(data: Dict[str, Any], model_class: Type) -> Dict[str, Any]:
74
+ """
75
+ Extract fields from a dictionary that are not valid for the model class.
76
+
77
+ Args:
78
+ data: Input dictionary with potentially invalid fields
79
+ model_class: The model class to check fields against
80
+
81
+ Returns:
82
+ Dictionary containing only fields that are NOT valid parameters for the model class
83
+ """
84
+ signature = inspect.signature(model_class.__init__)
85
+ valid_params = set(signature.parameters.keys())
86
+
87
+ valid_params.discard("self")
88
+ field_map = get_api_field_mapping(model_class)
89
+ all_valid_keys = valid_params.union(field_map.keys())
90
+
91
+ return {k: v for k, v in data.items() if k not in all_valid_keys}
92
+
93
+
94
+ def map_api_data_to_model(
95
+ data: Dict[str, Any], model_class: Type
96
+ ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
97
+ """
98
+ Maps API data to model fields, handling special field names and separating model fields from extra fields.
99
+
100
+ This function handles:
101
+ - Direct field matches
102
+ - Fields with api_key metadata mapping
103
+ - Nested data structures
104
+ - Extra fields preservation
105
+
106
+ Args:
107
+ data: Input dictionary from API response
108
+ model_class: The dataclass model to map data to
109
+
110
+ Returns:
111
+ Tuple containing (model_fields, extra_fields) where:
112
+ - model_fields: Dictionary of fields that map to the model's attributes
113
+ - extra_fields: Dictionary of extra fields that don't directly map to the model
114
+ """
115
+ signature = inspect.signature(model_class.__init__)
116
+ valid_params = set(signature.parameters.keys())
117
+ valid_params.discard("self")
118
+
119
+ field_map = get_api_field_mapping(model_class)
120
+ reverse_field_map = {v: k for k, v in field_map.items()}
121
+
122
+ model_fields = {}
123
+ extra_fields = {}
124
+
125
+ for api_key, value in data.items():
126
+ mapped_key = None
127
+
128
+ if api_key in valid_params:
129
+ mapped_key = api_key
130
+
131
+ elif api_key in field_map and field_map[api_key] in valid_params:
132
+ mapped_key = field_map[api_key]
133
+ logger.debug(f"Mapped field {api_key} to {mapped_key}")
134
+
135
+ if mapped_key is not None:
136
+ model_fields[mapped_key] = value
137
+ else:
138
+ extra_fields[api_key] = value
139
+
140
+ return model_fields, extra_fields
141
+
142
+
143
+ def resolve_model_names(
144
+ devices: List[UnifiDevice], model_db_path: Optional[str] = None
145
+ ) -> None:
146
+ """
147
+ Centralized function to resolve model names for a list of UnifiDevice objects.
148
+
149
+ This function is used to populate the model_name field based on the device model code,
150
+ using the device-models.json database.
151
+
152
+ Args:
153
+ devices: List of UnifiDevice objects to resolve model names for
154
+ model_db_path: Path to the device model database JSON file. If None,
155
+ uses the built-in device-models.json file.
156
+
157
+ This function modifies the devices in-place, setting their model_name attribute.
158
+ It only sets model_name if it's not already set, preserving existing values.
159
+
160
+ Raises:
161
+ UnifiModelError: If the device model database cannot be loaded.
162
+ """
163
+ if not devices:
164
+ return
165
+
166
+ if model_db_path is None:
167
+ model_db_path = os.path.join(
168
+ os.path.dirname(os.path.dirname(__file__)),
169
+ "unifi_controller_api",
170
+ "device-models.json",
171
+ )
172
+
173
+ try:
174
+ with open(model_db_path, "r", encoding="utf-8") as file:
175
+ device_models = json.load(file)
176
+ except (json.JSONDecodeError, IOError, FileNotFoundError) as e:
177
+ error_msg = f"Failed to load device models from {model_db_path}: {e}"
178
+ logger.error(error_msg)
179
+ raise UnifiModelError(error_msg) from e
180
+
181
+ for device in devices:
182
+ if device.model_name is not None or not device.model:
183
+ continue
184
+
185
+ model_details = device_models.get(device.model, {})
186
+ model_name = model_details.get("names", {}).get("fullName", None)
187
+
188
+ if model_name:
189
+ device.model_name = model_name
190
+ else:
191
+ device.model_name = device.model
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: unifi-controller-api
3
+ Version: 0.1.0
4
+ Summary: A (read only) Python library for interacting with the Unifi Controller API
5
+ Author-email: Tyler Woods <tyler@tylermade.net>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/tnware/unifi-controller-api
8
+ Project-URL: Bug Tracker, https://github.com/tnware/unifi-controller-api/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: System :: Networking :: Monitoring
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Classifier: Topic :: Utilities
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: requests
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=6.0; extra == "dev"
21
+ Requires-Dist: pytest-cov>=2.12; extra == "dev"
22
+ Requires-Dist: pytest-mock>=3.10.0; extra == "dev"
23
+ Requires-Dist: python-dotenv>=1.0.0; extra == "dev"
24
+ Requires-Dist: ruff>=0.1.1; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # unifi-controller-api
@@ -0,0 +1,12 @@
1
+ unifi_controller_api/__init__.py,sha256=zgPF64otPUraXTgeAVFcFIKHJTJ7ahPo82PSV8w24vc,796
2
+ unifi_controller_api/api_client.py,sha256=FnD3B2stgATEEfncPdCQMwDXfaCQMz8K4lT9JGbzsMU,17387
3
+ unifi_controller_api/device-models.json,sha256=ozFF_ejBpQHWum1MP4XQtFj7jbTfDEYO2BTejAKc_N8,147559
4
+ unifi_controller_api/exceptions.py,sha256=kczlF_TAd0alrTHvrUso6Froiu1OA0bWdsWn3XrHQdQ,628
5
+ unifi_controller_api/export.py,sha256=7OfE08oGirK92RNqGHMp_r3RRh6jvRvPc-kKgEDHD8Q,4321
6
+ unifi_controller_api/logging.py,sha256=Xt7b8C-YaUSGTznIPqEbF8K29cDCw-0orkkt9fuHnfo,3108
7
+ unifi_controller_api/utils.py,sha256=-z_t02Cnp5N5dB4BLpl4OD1nIGU7ZQzaKdVw9bYk7DA,6137
8
+ unifi_controller_api-0.1.0.dist-info/licenses/LICENSE,sha256=Q5k_NmmPchmJVHS5eEefcJ9tCcVowUj-g8pJShsfE2s,1063
9
+ unifi_controller_api-0.1.0.dist-info/METADATA,sha256=ZZ7JDvj_mZMzWp-TiWrEut-8iZ2X_9kNWWkDTvmaqs0,1077
10
+ unifi_controller_api-0.1.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
11
+ unifi_controller_api-0.1.0.dist-info/top_level.txt,sha256=kjGsZ4fcC4PHasZsM0WwNPZAoO3HjzOmTdzXy5pKAVI,21
12
+ unifi_controller_api-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (78.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 tnware
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ unifi_controller_api