Python-Unifi-Client 1.2.6__py3-none-any.whl → 1.2.8__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.
- python_unifi_client/client.py +609 -229
- {python_unifi_client-1.2.6.dist-info → python_unifi_client-1.2.8.dist-info}/METADATA +1 -1
- python_unifi_client-1.2.8.dist-info/RECORD +6 -0
- python_unifi_client-1.2.6.dist-info/RECORD +0 -6
- {python_unifi_client-1.2.6.dist-info → python_unifi_client-1.2.8.dist-info}/WHEEL +0 -0
- {python_unifi_client-1.2.6.dist-info → python_unifi_client-1.2.8.dist-info}/top_level.txt +0 -0
python_unifi_client/client.py
CHANGED
|
@@ -10,8 +10,6 @@ import http.client as http_client
|
|
|
10
10
|
import logging
|
|
11
11
|
import base64
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
15
13
|
# Custom exceptions mirroring PHP equivalents
|
|
16
14
|
class CurlExtensionNotLoadedException(Exception):
|
|
17
15
|
def __init__(self):
|
|
@@ -79,7 +77,7 @@ class Client:
|
|
|
79
77
|
CURL_METHODS_ALLOWED = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']
|
|
80
78
|
DEFAULT_CURL_METHOD = 'GET'
|
|
81
79
|
|
|
82
|
-
def __init__(self, user, password, baseurl='https://
|
|
80
|
+
def __init__(self, user, password, baseurl='https://127.0.0.1', site='default', version='8.0.28', ssl_verify=False, unificookie_name='unificookie', debug=False):
|
|
83
81
|
# Initial setup mirrors PHP constructor
|
|
84
82
|
self._check_curl()
|
|
85
83
|
self._check_base_url(baseurl)
|
|
@@ -108,6 +106,29 @@ class Client:
|
|
|
108
106
|
self._cookies_created_at = 0
|
|
109
107
|
self._exec_retries = 0
|
|
110
108
|
self.debug = debug
|
|
109
|
+
self._firmware_version = None # None = unknown, 'v1' or 'v2' (auto-detected)
|
|
110
|
+
|
|
111
|
+
self.default_site_stats_attribs = [
|
|
112
|
+
'bytes',
|
|
113
|
+
'wan-tx_bytes',
|
|
114
|
+
'wan-rx_bytes',
|
|
115
|
+
'wlan_bytes',
|
|
116
|
+
'num_sta',
|
|
117
|
+
'lan-num_sta',
|
|
118
|
+
'wlan-num_sta',
|
|
119
|
+
'time',
|
|
120
|
+
]
|
|
121
|
+
|
|
122
|
+
self.default_ap_stats_attribs = [
|
|
123
|
+
'bytes',
|
|
124
|
+
'wan-tx_bytes',
|
|
125
|
+
'wan-rx_bytes',
|
|
126
|
+
'wlan_bytes',
|
|
127
|
+
'num_sta',
|
|
128
|
+
'lan-num_sta',
|
|
129
|
+
'wlan-num_sta',
|
|
130
|
+
'time',
|
|
131
|
+
]
|
|
111
132
|
|
|
112
133
|
if self.debug:
|
|
113
134
|
logging.basicConfig(level=logging.DEBUG)
|
|
@@ -146,7 +167,7 @@ class Client:
|
|
|
146
167
|
return True
|
|
147
168
|
return False
|
|
148
169
|
|
|
149
|
-
def login(self) -> bool:
|
|
170
|
+
def login(self, return_token:bool=False) -> bool:
|
|
150
171
|
# Skip if already logged in via valid cookie
|
|
151
172
|
self._verify_ssl_cert = False
|
|
152
173
|
|
|
@@ -216,6 +237,8 @@ class Client:
|
|
|
216
237
|
self._session.headers.update({'x-csrf-token': token,
|
|
217
238
|
'Referer': f"{self._baseurl}/login"})
|
|
218
239
|
self._is_loggedin = True
|
|
240
|
+
if return_token:
|
|
241
|
+
return True, token
|
|
219
242
|
return True
|
|
220
243
|
|
|
221
244
|
raise LoginFailedException(f"HTTP response: {resp2.status_code}")
|
|
@@ -260,19 +283,19 @@ class Client:
|
|
|
260
283
|
# The following methods are directly converted from the PHP class to Python, preserving functionality and parameters.
|
|
261
284
|
|
|
262
285
|
def get_site_stats(self):
|
|
263
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/sysinfo")
|
|
286
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/sysinfo", proxy_type='network')
|
|
264
287
|
|
|
265
288
|
def get_clients(self):
|
|
266
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/sta",
|
|
289
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/sta", proxy_type='network')
|
|
267
290
|
|
|
268
291
|
def block_client(self, mac):
|
|
269
|
-
return self.
|
|
292
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/stamgr", method='POST', payload={'cmd': 'block-sta', 'mac': mac})
|
|
270
293
|
|
|
271
294
|
def unblock_client(self, mac):
|
|
272
|
-
return self.
|
|
295
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/stamgr", method='POST', payload={'cmd': 'unblock-sta', 'mac': mac})
|
|
273
296
|
|
|
274
297
|
def reconnect_client(self, mac):
|
|
275
|
-
return self.
|
|
298
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/stamgr", method='POST', payload={'cmd': 'kick-sta', 'mac': mac})
|
|
276
299
|
|
|
277
300
|
def authorize_guest(self, mac, minutes, up=None, down=None, megabytes=None, ap_mac=None):
|
|
278
301
|
payload = {
|
|
@@ -284,7 +307,7 @@ class Client:
|
|
|
284
307
|
if down is not None: payload['down'] = down
|
|
285
308
|
if megabytes is not None: payload['bytes'] = megabytes
|
|
286
309
|
if ap_mac is not None: payload['ap_mac'] = ap_mac.lower()
|
|
287
|
-
return self.
|
|
310
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/stamgr", payload=payload)
|
|
288
311
|
|
|
289
312
|
"""
|
|
290
313
|
Unauthorize a client device.
|
|
@@ -294,37 +317,32 @@ class Client:
|
|
|
294
317
|
throws Exception
|
|
295
318
|
"""
|
|
296
319
|
def unauthorize_guest(self, mac):
|
|
297
|
-
return self.
|
|
320
|
+
return self.fetch_results(
|
|
298
321
|
f"/api/s/{self._site}/cmd/stamgr",
|
|
299
|
-
method='POST',
|
|
300
322
|
payload={'cmd': 'unauthorize-guest', 'mac': mac}
|
|
301
323
|
)
|
|
302
324
|
|
|
303
325
|
def reconnect_sta(self, mac):
|
|
304
|
-
return self.
|
|
326
|
+
return self.fetch_results(
|
|
305
327
|
f"/api/s/{self._site}/cmd/stamgr",
|
|
306
|
-
method='POST',
|
|
307
328
|
payload={'cmd': 'kick-sta', 'mac': mac.lower()}
|
|
308
329
|
)
|
|
309
330
|
|
|
310
331
|
def block_sta(self, mac):
|
|
311
|
-
return self.
|
|
332
|
+
return self.fetch_results(
|
|
312
333
|
f"/api/s/{self._site}/cmd/stamgr",
|
|
313
|
-
method='POST',
|
|
314
334
|
payload={'cmd': 'block-sta', 'mac': mac.lower()}
|
|
315
335
|
)
|
|
316
336
|
|
|
317
337
|
def unblock_sta(self, mac):
|
|
318
|
-
return self.
|
|
338
|
+
return self.fetch_results(
|
|
319
339
|
f"/api/s/{self._site}/cmd/stamgr",
|
|
320
|
-
method='POST',
|
|
321
340
|
payload={'cmd': 'unblock-sta', 'mac': mac.lower()}
|
|
322
341
|
)
|
|
323
342
|
|
|
324
343
|
def forget_sta(self, mac):
|
|
325
|
-
return self.
|
|
344
|
+
return self.fetch_results(
|
|
326
345
|
f"/api/s/{self._site}/cmd/stamgr",
|
|
327
|
-
method='POST',
|
|
328
346
|
payload={'cmd': 'forget-sta', 'mac': mac}
|
|
329
347
|
)
|
|
330
348
|
|
|
@@ -368,14 +386,15 @@ class Client:
|
|
|
368
386
|
|
|
369
387
|
return self.fetch_results(
|
|
370
388
|
f"/api/s/{self._site}/rest/user",
|
|
371
|
-
payload=payload
|
|
389
|
+
payload=payload,
|
|
390
|
+
proxy_type='network'
|
|
372
391
|
)
|
|
373
392
|
|
|
374
393
|
def delete_user(self, user_id: str):
|
|
375
394
|
"""
|
|
376
395
|
Remove a user by ID
|
|
377
396
|
"""
|
|
378
|
-
return self.
|
|
397
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/user/{user_id}", proxy_type='network')
|
|
379
398
|
|
|
380
399
|
def get_user(self, user_id: str):
|
|
381
400
|
"""
|
|
@@ -384,7 +403,7 @@ class Client:
|
|
|
384
403
|
return self.fetch_results(f"/api/s/{self._site}/rest/user/{user_id}")
|
|
385
404
|
|
|
386
405
|
def get_client_by_mac(self, mac: str):
|
|
387
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/user/{mac}",
|
|
406
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/user/{mac}", proxy_type='network')
|
|
388
407
|
|
|
389
408
|
def update_user(self, user_id: str, name: str = None, note: str = None, is_guest: bool = None, is_wired: bool = None):
|
|
390
409
|
"""
|
|
@@ -403,16 +422,16 @@ class Client:
|
|
|
403
422
|
|
|
404
423
|
return self.fetch_results(
|
|
405
424
|
f"/api/s/{self._site}/rest/user/{user_id}",
|
|
406
|
-
payload=payload
|
|
425
|
+
payload=payload,
|
|
426
|
+
proxy_type='network'
|
|
407
427
|
)
|
|
408
428
|
|
|
409
429
|
def forget_user(self, mac: str):
|
|
410
430
|
"""
|
|
411
431
|
Forget (remove) any record of a client's MAC from the site.
|
|
412
432
|
"""
|
|
413
|
-
return self.
|
|
433
|
+
return self.fetch_results(
|
|
414
434
|
f"/api/s/{self._site}/cmd/sitemgr",
|
|
415
|
-
method='POST',
|
|
416
435
|
payload={'cmd': 'forget-sta', 'mac': mac}
|
|
417
436
|
)
|
|
418
437
|
|
|
@@ -420,13 +439,13 @@ class Client:
|
|
|
420
439
|
|
|
421
440
|
## ------------- Make sure these are included in the PHP files ------
|
|
422
441
|
def get_clients_summary(self):
|
|
423
|
-
return self.
|
|
442
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/summary/client")
|
|
424
443
|
|
|
425
444
|
def get_user_groups(self):
|
|
426
|
-
return self.
|
|
445
|
+
return self.fetch_results(f"/api/s/{self._site}/list/usergroup")
|
|
427
446
|
|
|
428
447
|
def get_user_group(self, group_id):
|
|
429
|
-
return self.
|
|
448
|
+
return self.fetch_results(f"/api/s/{self._site}/list/usergroup/{group_id}")
|
|
430
449
|
|
|
431
450
|
def create_user_group(self, group_name: str, group_dn: int = -1, group_up: int = -1):
|
|
432
451
|
"""
|
|
@@ -457,27 +476,25 @@ class Client:
|
|
|
457
476
|
'qos_rate_max_up': group_up,
|
|
458
477
|
'site_id': site_id,
|
|
459
478
|
}
|
|
460
|
-
return self.
|
|
479
|
+
return self.fetch_results(
|
|
461
480
|
f"/api/s/{self._site}/rest/usergroup",
|
|
462
|
-
method='PUT',
|
|
463
481
|
payload=payload
|
|
464
482
|
)
|
|
465
483
|
|
|
466
484
|
def delete_user_group(self, group_id):
|
|
467
|
-
return self.
|
|
485
|
+
return self.fetch_results(
|
|
468
486
|
f"/api/s/{self._site}/cmd/usergroup/{group_id}",
|
|
469
|
-
method='DELETE'
|
|
470
487
|
)
|
|
471
488
|
|
|
472
489
|
|
|
473
490
|
def list_sites(self):
|
|
474
|
-
return self.fetch_results("/api/self/sites")
|
|
491
|
+
return self.fetch_results("/api/self/sites", proxy_type='network')
|
|
475
492
|
|
|
476
493
|
def list_apgroups(self):
|
|
477
494
|
"""
|
|
478
495
|
Fetch AP groups for the current site.
|
|
479
496
|
"""
|
|
480
|
-
return self.
|
|
497
|
+
return self.fetch_results(f"/v2/api/site/{self._site}/apgroups")
|
|
481
498
|
|
|
482
499
|
def create_apgroup(self, name: str, description: str = None) -> dict:
|
|
483
500
|
"""Create a new AP group with optional description."""
|
|
@@ -508,11 +525,11 @@ class Client:
|
|
|
508
525
|
def list_dashboard(self, five_minutes: bool = False):
|
|
509
526
|
"""Fetch dashboard metrics, 5-minute scale if requested."""
|
|
510
527
|
suffix = '?scale=5minutes' if five_minutes else ''
|
|
511
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/dashboard{suffix}")
|
|
528
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/dashboard{suffix}", proxy_type='network')
|
|
512
529
|
|
|
513
530
|
def list_users(self):
|
|
514
531
|
"""Fetch known client devices."""
|
|
515
|
-
return self.fetch_results(f"/api/s/{self._site}/list/user",
|
|
532
|
+
return self.fetch_results(f"/api/s/{self._site}/list/user", proxy_type='network')
|
|
516
533
|
|
|
517
534
|
def list_tags(self):
|
|
518
535
|
"""Fetch all device tags (REST)."""
|
|
@@ -542,7 +559,7 @@ class Client:
|
|
|
542
559
|
return self.fetch_results(f"/api/s/{self._site}/rest/rogueknown")
|
|
543
560
|
|
|
544
561
|
def get_site(self, site_id) -> str:
|
|
545
|
-
return self.
|
|
562
|
+
return self.fetch_results(f"/api/s/{site_id}/self", proxy_type='network')
|
|
546
563
|
|
|
547
564
|
def create_site(self, description: str):
|
|
548
565
|
"""
|
|
@@ -571,9 +588,8 @@ class Client:
|
|
|
571
588
|
self._curl_method = "GET"
|
|
572
589
|
|
|
573
590
|
def delete_site(self, site_id):
|
|
574
|
-
return self.
|
|
591
|
+
return self.fetch_results(
|
|
575
592
|
f"/api/s/{site_id}",
|
|
576
|
-
method='DELETE',
|
|
577
593
|
payload={'site': site_id, 'cmd': 'delete-site'}
|
|
578
594
|
)
|
|
579
595
|
|
|
@@ -637,12 +653,12 @@ class Client:
|
|
|
637
653
|
def get_admins(self):
|
|
638
654
|
"""Fetch administrators for current site"""
|
|
639
655
|
payload = {'cmd': 'get-admins'}
|
|
640
|
-
return self.fetch_results(f"/api/s/{self._site}/cmd/sitemgr", payload=payload,
|
|
656
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/sitemgr", payload=payload, proxy_type='network')
|
|
641
657
|
|
|
642
658
|
def list_all_admins(self):
|
|
643
659
|
"""Fetch all administrators"""
|
|
644
660
|
payload = {'cmd': 'get-all-admins'}
|
|
645
|
-
return self.fetch_results(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
661
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/sitemgr", payload=payload, proxy_type='network')
|
|
646
662
|
|
|
647
663
|
def invite_admin(self, name: str, email: str, enable_sso: bool = True, readonly: bool = False,
|
|
648
664
|
device_adopt: bool = False, device_restart: bool = False) -> bool:
|
|
@@ -662,7 +678,7 @@ class Client:
|
|
|
662
678
|
payload['permissions'].append('API_DEVICE_ADOPT')
|
|
663
679
|
if device_restart:
|
|
664
680
|
payload['permissions'].append('API_DEVICE_RESTART')
|
|
665
|
-
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
681
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload, proxy_type='network')
|
|
666
682
|
|
|
667
683
|
def assign_existing_admin(self, admin_id: str, readonly: bool = False,
|
|
668
684
|
device_adopt: bool = False, device_restart: bool = False) -> bool:
|
|
@@ -694,12 +710,12 @@ class Client:
|
|
|
694
710
|
def revoke_admin(self, admin_id: str) -> bool:
|
|
695
711
|
"""Revoke an admin's access to this site"""
|
|
696
712
|
payload = {'cmd': 'revoke-admin', 'admin': admin_id.strip()}
|
|
697
|
-
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
713
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload, proxy_type='network')
|
|
698
714
|
|
|
699
715
|
def delete_admin(self, admin_id: str) -> bool:
|
|
700
716
|
"""Delete an admin user"""
|
|
701
717
|
payload = {'cmd': 'delete-admin', 'admin': admin_id.strip()}
|
|
702
|
-
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload)
|
|
718
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/cmd/sitemgr", payload=payload,proxy_type='network')
|
|
703
719
|
|
|
704
720
|
def list_wlan_groups(self):
|
|
705
721
|
"""Fetch WLAN groups"""
|
|
@@ -714,7 +730,8 @@ class Client:
|
|
|
714
730
|
return self.fetch_results_boolean(
|
|
715
731
|
'/status',
|
|
716
732
|
payload=None,
|
|
717
|
-
login_required=self._unifi_os
|
|
733
|
+
login_required=self._unifi_os,
|
|
734
|
+
proxy_type='network'
|
|
718
735
|
)
|
|
719
736
|
|
|
720
737
|
def stat_full_status(self):
|
|
@@ -723,7 +740,8 @@ class Client:
|
|
|
723
740
|
self.fetch_results_boolean(
|
|
724
741
|
'/status',
|
|
725
742
|
payload=None,
|
|
726
|
-
login_required=self._unifi_os
|
|
743
|
+
login_required=self._unifi_os,
|
|
744
|
+
proxy_type='network'
|
|
727
745
|
)
|
|
728
746
|
# Decode and return the last raw JSON results
|
|
729
747
|
raw = self.get_last_results_raw(return_json=False)
|
|
@@ -752,22 +770,233 @@ class Client:
|
|
|
752
770
|
return self.fetch_results('/api/self')
|
|
753
771
|
|
|
754
772
|
def get_devices(self):
|
|
755
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/device", login_required=True,
|
|
773
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/device", login_required=True, proxy_type='network')
|
|
756
774
|
|
|
757
775
|
def get_device(self, device_id):
|
|
758
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/device/{device_id}",
|
|
776
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/device/{device_id}", proxy_type='network')
|
|
777
|
+
|
|
778
|
+
# === Health & Status Methods ===
|
|
779
|
+
|
|
780
|
+
def list_health(self):
|
|
781
|
+
"""Get site health status including WAN, LAN, WLAN subsystems.
|
|
782
|
+
|
|
783
|
+
Returns:
|
|
784
|
+
list: Health data for each subsystem with status and details
|
|
785
|
+
"""
|
|
786
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/health", proxy_type='network')
|
|
759
787
|
|
|
788
|
+
def get_device_history(self, mac: str, is_client:bool, limit: int = 50):
|
|
789
|
+
"""Fetch device activity/event history from system logs.
|
|
790
|
+
|
|
791
|
+
Args:
|
|
792
|
+
mac: Device MAC address
|
|
793
|
+
is_client: Determines the scope, 'CLIENTS or DEVICE'
|
|
794
|
+
limit: Maximum number of entries to return
|
|
795
|
+
|
|
796
|
+
Returns:
|
|
797
|
+
list: Activity log entries for the device
|
|
798
|
+
"""
|
|
799
|
+
scope = 'CLIENTS' if is_client else 'DEVICE'
|
|
800
|
+
|
|
801
|
+
self._curl_method = 'GET'
|
|
802
|
+
return self.fetch_results(
|
|
803
|
+
f"/v2/api/site/default/system-log/device/{mac}?mac={mac}&scope={scope}&limit={limit}",
|
|
804
|
+
proxy_type='network'
|
|
805
|
+
)
|
|
806
|
+
|
|
807
|
+
# === Firewall Methods ===
|
|
808
|
+
|
|
809
|
+
def list_firewall_rules(self):
|
|
810
|
+
"""List all firewall rules for the site.
|
|
811
|
+
|
|
812
|
+
Returns:
|
|
813
|
+
list: Firewall rule configurations
|
|
814
|
+
"""
|
|
815
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/firewallrule", proxy_type='network')
|
|
816
|
+
|
|
817
|
+
def create_firewall_rule(self, payload: dict):
|
|
818
|
+
"""Create a new firewall rule.
|
|
819
|
+
|
|
820
|
+
Args:
|
|
821
|
+
payload: Firewall rule configuration dict
|
|
822
|
+
|
|
823
|
+
Returns:
|
|
824
|
+
list: Created firewall rule data
|
|
825
|
+
"""
|
|
826
|
+
self._curl_method = 'POST'
|
|
827
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/firewallrule", payload=payload, proxy_type='network')
|
|
828
|
+
|
|
829
|
+
def delete_firewall_rule(self, rule_id: str):
|
|
830
|
+
"""Delete a firewall rule by ID.
|
|
831
|
+
|
|
832
|
+
Args:
|
|
833
|
+
rule_id: The _id of the firewall rule to delete
|
|
834
|
+
|
|
835
|
+
Returns:
|
|
836
|
+
bool: True if successful
|
|
837
|
+
"""
|
|
838
|
+
self._curl_method = 'DELETE'
|
|
839
|
+
return self.fetch_results_boolean(f"/api/s/{self._site}/rest/firewallrule/{rule_id}", proxy_type='network')
|
|
840
|
+
|
|
841
|
+
# === UniFi OS System Methods (no prefix_path - direct /api/ endpoints) ===
|
|
842
|
+
|
|
843
|
+
def get_system_config(self):
|
|
844
|
+
"""Get UniFi OS system configuration.
|
|
845
|
+
|
|
846
|
+
Returns:
|
|
847
|
+
list: System configuration including SSH, update settings
|
|
848
|
+
"""
|
|
849
|
+
return self.fetch_results("/api/system", proxy_type=None)
|
|
850
|
+
|
|
851
|
+
def set_system_config(self, payload: dict):
|
|
852
|
+
"""Update UniFi OS system configuration.
|
|
853
|
+
|
|
854
|
+
Args:
|
|
855
|
+
payload: System config updates (e.g., {'ssh': {'enabled': True}})
|
|
856
|
+
|
|
857
|
+
Returns:
|
|
858
|
+
list: Updated system configuration
|
|
859
|
+
"""
|
|
860
|
+
self._curl_method = 'PATCH'
|
|
861
|
+
return self.fetch_results("/api/system", payload=payload, proxy_type=None)
|
|
862
|
+
|
|
863
|
+
def set_ssh_password(self, password: str):
|
|
864
|
+
"""Set the SSH password for UniFi OS.
|
|
865
|
+
|
|
866
|
+
Args:
|
|
867
|
+
password: New SSH password
|
|
868
|
+
|
|
869
|
+
Returns:
|
|
870
|
+
list: Response from password set operation
|
|
871
|
+
"""
|
|
872
|
+
self._curl_method = 'POST'
|
|
873
|
+
return self.fetch_results("/api/system/ssh/setpassword", payload={'password': password}, proxy_type=None)
|
|
874
|
+
|
|
875
|
+
def get_notification_settings(self):
|
|
876
|
+
"""Get UniFi OS notification settings.
|
|
877
|
+
|
|
878
|
+
Returns:
|
|
879
|
+
list: Notification configuration
|
|
880
|
+
"""
|
|
881
|
+
return self.fetch_results("/api/notifications/settings", proxy_type=None)
|
|
882
|
+
|
|
883
|
+
def set_notification_settings(self, payload: dict):
|
|
884
|
+
"""Update UniFi OS notification settings.
|
|
885
|
+
|
|
886
|
+
Args:
|
|
887
|
+
payload: Notification settings to update
|
|
888
|
+
|
|
889
|
+
Returns:
|
|
890
|
+
list: Updated notification settings
|
|
891
|
+
"""
|
|
892
|
+
self._curl_method = 'PUT'
|
|
893
|
+
return self.fetch_results("/api/notifications/settings", payload=payload, proxy_type=None)
|
|
894
|
+
|
|
895
|
+
def download_backup(self, filename: str = None):
|
|
896
|
+
"""Download UniFi OS system backup.
|
|
897
|
+
|
|
898
|
+
Args:
|
|
899
|
+
filename: Optional filename filter
|
|
900
|
+
|
|
901
|
+
Returns:
|
|
902
|
+
bytes: Backup file content (requires special handling for binary data)
|
|
903
|
+
"""
|
|
904
|
+
params = {}
|
|
905
|
+
if filename:
|
|
906
|
+
params['filename'] = filename
|
|
907
|
+
self._curl_method = 'GET'
|
|
908
|
+
# Note: This returns raw bytes, not JSON - may need special handling
|
|
909
|
+
return self.exec_curl("/api/backup/download", payload=params if params else None, proxy_type=None)
|
|
910
|
+
|
|
911
|
+
# === User Management Methods (always /proxy/users/ - no v1/v2 distinction) ===
|
|
912
|
+
|
|
913
|
+
def list_site_users(self):
|
|
914
|
+
"""Get all users/admins for the site.
|
|
915
|
+
|
|
916
|
+
Returns:
|
|
917
|
+
list: User accounts with roles and permissions
|
|
918
|
+
"""
|
|
919
|
+
return self.fetch_results("/api/v2/users", proxy_type='users')
|
|
920
|
+
|
|
921
|
+
def invite_user(self, email: str, role: str = 'admin', permissions: dict = None):
|
|
922
|
+
"""Invite a user to the UniFi site.
|
|
923
|
+
|
|
924
|
+
Args:
|
|
925
|
+
email: User's email address
|
|
926
|
+
role: User role (e.g., 'admin', 'viewer')
|
|
927
|
+
permissions: Optional permission overrides
|
|
928
|
+
|
|
929
|
+
Returns:
|
|
930
|
+
list: Invitation result
|
|
931
|
+
"""
|
|
932
|
+
payload = {
|
|
933
|
+
'email': email,
|
|
934
|
+
'role': role
|
|
935
|
+
}
|
|
936
|
+
if permissions:
|
|
937
|
+
payload['permissions'] = permissions
|
|
938
|
+
self._curl_method = 'POST'
|
|
939
|
+
return self.fetch_results("/api/v2/users/invite_add", payload=payload, proxy_type='users')
|
|
940
|
+
|
|
941
|
+
def deactivate_user(self, user_id: str):
|
|
942
|
+
"""Deactivate a user account.
|
|
943
|
+
|
|
944
|
+
Args:
|
|
945
|
+
user_id: User's unique identifier
|
|
946
|
+
|
|
947
|
+
Returns:
|
|
948
|
+
list: Deactivation result
|
|
949
|
+
"""
|
|
950
|
+
self._curl_method = 'PUT'
|
|
951
|
+
return self.fetch_results(f"/api/v2/user/{user_id}/deactivate?isULP=1", proxy_type='users')
|
|
952
|
+
|
|
953
|
+
def activate_user(self, user_id: str):
|
|
954
|
+
"""Activate a deactivated user account.
|
|
955
|
+
|
|
956
|
+
Args:
|
|
957
|
+
user_id: User's unique identifier
|
|
958
|
+
|
|
959
|
+
Returns:
|
|
960
|
+
list: Activation result
|
|
961
|
+
"""
|
|
962
|
+
self._curl_method = 'PUT'
|
|
963
|
+
return self.fetch_results(f"/api/v2/user/{user_id}/active?isULP=1", proxy_type='users')
|
|
964
|
+
|
|
965
|
+
def remove_user(self, user_id: str):
|
|
966
|
+
"""Permanently remove a user account.
|
|
967
|
+
|
|
968
|
+
Args:
|
|
969
|
+
user_id: User's unique identifier
|
|
970
|
+
|
|
971
|
+
Returns:
|
|
972
|
+
list: Removal result
|
|
973
|
+
"""
|
|
974
|
+
self._curl_method = 'DELETE'
|
|
975
|
+
return self.fetch_results(f"/api/v2/user/{user_id}", proxy_type='users')
|
|
976
|
+
|
|
977
|
+
def create_custom_role(self, payload: dict):
|
|
978
|
+
"""Create a custom permission role.
|
|
979
|
+
|
|
980
|
+
Args:
|
|
981
|
+
payload: Role configuration with permissions
|
|
982
|
+
|
|
983
|
+
Returns:
|
|
984
|
+
list: Created role data
|
|
985
|
+
"""
|
|
986
|
+
self._curl_method = 'POST'
|
|
987
|
+
return self.fetch_results("/api/v2/custom_role", payload=payload, proxy_type='users')
|
|
988
|
+
|
|
760
989
|
def get_wlan(self, wlan_id: str):
|
|
761
990
|
"""
|
|
762
991
|
Retrieve WLAN configuration by ID
|
|
763
992
|
"""
|
|
764
|
-
return self.
|
|
993
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/wlanconf/{wlan_id}")
|
|
765
994
|
|
|
766
995
|
def list_wlanconf(self):
|
|
767
996
|
"""
|
|
768
997
|
List all WLAN configurations on the site.
|
|
769
998
|
"""
|
|
770
|
-
return self.
|
|
999
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/wlanconf")
|
|
771
1000
|
|
|
772
1001
|
def create_wlan(
|
|
773
1002
|
self,
|
|
@@ -816,9 +1045,8 @@ class Client:
|
|
|
816
1045
|
data['ap_group_ids'] = ap_group_ids
|
|
817
1046
|
|
|
818
1047
|
# Perform the request and return True on HTTP 200
|
|
819
|
-
self.
|
|
1048
|
+
self.fetch_results(
|
|
820
1049
|
f"/api/s/{self._site}/add/wlanconf",
|
|
821
|
-
method='POST',
|
|
822
1050
|
payload=data
|
|
823
1051
|
)
|
|
824
1052
|
return self._last_response_code == 200
|
|
@@ -861,9 +1089,8 @@ class Client:
|
|
|
861
1089
|
data['x_passphrase'] = x_passphrase.strip()
|
|
862
1090
|
if name is not None:
|
|
863
1091
|
data['name'] = name.strip()
|
|
864
|
-
return self.
|
|
1092
|
+
return self.fetch_results(
|
|
865
1093
|
f"/api/s/{self._site}/rest/wlanconf/{wlan_id}",
|
|
866
|
-
method='PUT',
|
|
867
1094
|
payload=data
|
|
868
1095
|
)
|
|
869
1096
|
|
|
@@ -871,7 +1098,7 @@ class Client:
|
|
|
871
1098
|
"""
|
|
872
1099
|
Delete a WLAN configuration by ID
|
|
873
1100
|
"""
|
|
874
|
-
return self.
|
|
1101
|
+
return self.fetch_results(
|
|
875
1102
|
f"/api/s/{self._site}/rest/wlanconf/{wlan_id.strip()}"
|
|
876
1103
|
)
|
|
877
1104
|
|
|
@@ -924,7 +1151,7 @@ class Client:
|
|
|
924
1151
|
def list_clients(self, mac: str = None):
|
|
925
1152
|
"""Fetch online client devices, or single device if MAC provided."""
|
|
926
1153
|
path_mac = mac.lower().strip() if isinstance(mac, str) else ''
|
|
927
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/sta/{path_mac}",
|
|
1154
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/sta/{path_mac}", proxy_type='network')
|
|
928
1155
|
|
|
929
1156
|
def list_active_clients(self, include_traffic_usage: bool = True, include_unifi_devices: bool = True):
|
|
930
1157
|
"""Fetch active client devices, with optional traffic and UniFi device inclusion."""
|
|
@@ -932,7 +1159,7 @@ class Client:
|
|
|
932
1159
|
'include_traffic_usage': include_traffic_usage,
|
|
933
1160
|
'include_unifi_devices': include_unifi_devices,
|
|
934
1161
|
})
|
|
935
|
-
return self.fetch_results(f"/v2/api/site/{self._site}/clients/active?{query}",
|
|
1162
|
+
return self.fetch_results(f"/v2/api/site/{self._site}/clients/active?{query}", proxy_type='network')
|
|
936
1163
|
|
|
937
1164
|
def list_clients_history(self, only_non_blocked: bool = True, include_unifi_devices: bool = True, within_hours: int = 0):
|
|
938
1165
|
"""Fetch offline client device history."""
|
|
@@ -947,9 +1174,8 @@ class Client:
|
|
|
947
1174
|
"""
|
|
948
1175
|
Expire (unauthorize) a guest session immedietely
|
|
949
1176
|
"""
|
|
950
|
-
return self.
|
|
1177
|
+
return self.fetch_results(
|
|
951
1178
|
f"/api/s/{self._site}/cmd/stamgr",
|
|
952
|
-
method='POST',
|
|
953
1179
|
payload={'cmd': 'unauthorize-guest', 'mac': mac}
|
|
954
1180
|
)
|
|
955
1181
|
|
|
@@ -957,7 +1183,7 @@ class Client:
|
|
|
957
1183
|
"""
|
|
958
1184
|
List all hotspot vouchers on the site.
|
|
959
1185
|
"""
|
|
960
|
-
return self.
|
|
1186
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/voucher")
|
|
961
1187
|
|
|
962
1188
|
def create_voucher(
|
|
963
1189
|
self,
|
|
@@ -995,9 +1221,8 @@ class Client:
|
|
|
995
1221
|
if megabytes is not None:
|
|
996
1222
|
payload['bytes'] = megabytes
|
|
997
1223
|
|
|
998
|
-
return self.
|
|
1224
|
+
return self.fetch_results(
|
|
999
1225
|
f"/api/s/{self._site}/cmd/hotspot",
|
|
1000
|
-
method='POST',
|
|
1001
1226
|
payload=payload
|
|
1002
1227
|
)
|
|
1003
1228
|
|
|
@@ -1009,9 +1234,8 @@ class Client:
|
|
|
1009
1234
|
"""
|
|
1010
1235
|
payload = {'_id': voucher_id, 'cmd': 'delete-voucher'}
|
|
1011
1236
|
|
|
1012
|
-
return self.
|
|
1237
|
+
return self.fetch_results(
|
|
1013
1238
|
f"/api/s/{self._site}/cmd/hotspot",
|
|
1014
|
-
method='POST',
|
|
1015
1239
|
payload=payload
|
|
1016
1240
|
)
|
|
1017
1241
|
|
|
@@ -1019,7 +1243,7 @@ class Client:
|
|
|
1019
1243
|
"""
|
|
1020
1244
|
List all client sessions (stat/session) for the site
|
|
1021
1245
|
"""
|
|
1022
|
-
return self.
|
|
1246
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/session", proxy_type='network')
|
|
1023
1247
|
|
|
1024
1248
|
def stat_hourly_site(self, start: int = None, end: int = None, attribs: list = None):
|
|
1025
1249
|
"""
|
|
@@ -1040,9 +1264,8 @@ class Client:
|
|
|
1040
1264
|
'end': end
|
|
1041
1265
|
}
|
|
1042
1266
|
|
|
1043
|
-
return self.
|
|
1267
|
+
return self.fetch_results(
|
|
1044
1268
|
f"/api/s/{self._site}/stat/report/hourly.site",
|
|
1045
|
-
method='GET',
|
|
1046
1269
|
payload=payload
|
|
1047
1270
|
)
|
|
1048
1271
|
|
|
@@ -1052,7 +1275,7 @@ class Client:
|
|
|
1052
1275
|
start = start or end - 12 * 3600 * 1000
|
|
1053
1276
|
attrs = attribs or self.default_site_stats_attribs
|
|
1054
1277
|
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1055
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.site", payload=payload)
|
|
1278
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.site", payload=payload, proxy_type='network')
|
|
1056
1279
|
|
|
1057
1280
|
def stat_5minutes_aps(self, start: int = None, end: int = None, mac: str = None, attribs: list = None):
|
|
1058
1281
|
"""Fetch 5-minute AP stats (defaults to past 12 hours)."""
|
|
@@ -1062,7 +1285,7 @@ class Client:
|
|
|
1062
1285
|
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1063
1286
|
if mac:
|
|
1064
1287
|
payload['mac'] = mac.lower()
|
|
1065
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.ap", payload=payload)
|
|
1288
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.ap", payload=payload, proxy_type='network')
|
|
1066
1289
|
|
|
1067
1290
|
def stat_hourly_aps(self, start: int = None, end: int = None, mac: str = None, attribs: list = None):
|
|
1068
1291
|
"""Fetch hourly AP stats (defaults to past 7 days)."""
|
|
@@ -1143,7 +1366,7 @@ class Client:
|
|
|
1143
1366
|
start = start or end - 12 * 3600 * 1000
|
|
1144
1367
|
attrs = attribs or ['time', 'mem', 'cpu', 'loadavg_5']
|
|
1145
1368
|
payload = {'attrs': ['time'] + attrs, 'start': start, 'end': end}
|
|
1146
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.gw", payload=payload)
|
|
1369
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/5minutes.gw", payload=payload, proxy_type='network')
|
|
1147
1370
|
|
|
1148
1371
|
def stat_hourly_gateway(self, start: int = None, end: int = None, attribs: list = None):
|
|
1149
1372
|
"""Fetch hourly gateway stats (defaults to past 7 days)."""
|
|
@@ -1172,29 +1395,28 @@ class Client:
|
|
|
1172
1395
|
return self.fetch_results(f"/api/s/{self._site}/stat/report/monthly.gw", payload=payload)
|
|
1173
1396
|
|
|
1174
1397
|
def list_network(self, network_id: str = ''):
|
|
1175
|
-
return self.
|
|
1398
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/networkconf{network_id.strip()}")
|
|
1176
1399
|
|
|
1177
1400
|
def list_networkconf(self, network_id: str = ''):
|
|
1178
|
-
return self.
|
|
1401
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/networkconf{network_id.strip()}")
|
|
1179
1402
|
|
|
1180
1403
|
def list_backups(self):
|
|
1181
1404
|
payload = {'cmd': 'list-backups'}
|
|
1182
1405
|
|
|
1183
|
-
return self.fetch_results(f"/api/s/{self._site}/cmd/backup", payload=payload,
|
|
1406
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/backup", payload=payload, proxy_type='network')
|
|
1184
1407
|
|
|
1185
1408
|
def get_network(self, network_id: str):
|
|
1186
1409
|
"""
|
|
1187
1410
|
Get a specific network configuration by ID
|
|
1188
1411
|
"""
|
|
1189
|
-
return self.
|
|
1412
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/networkconf/{network_id}")
|
|
1190
1413
|
|
|
1191
1414
|
def create_network(self, payload: dict):
|
|
1192
1415
|
"""
|
|
1193
1416
|
Create a new network configuration
|
|
1194
1417
|
"""
|
|
1195
|
-
return self.
|
|
1418
|
+
return self.fetch_results(
|
|
1196
1419
|
f"/api/s/{self._site}/rest/networkconf",
|
|
1197
|
-
method='POST',
|
|
1198
1420
|
payload=payload
|
|
1199
1421
|
)
|
|
1200
1422
|
|
|
@@ -1202,9 +1424,8 @@ class Client:
|
|
|
1202
1424
|
"""
|
|
1203
1425
|
Update an existing network configuration
|
|
1204
1426
|
"""
|
|
1205
|
-
return self.
|
|
1427
|
+
return self.fetch_results(
|
|
1206
1428
|
f"/api/s/{self._site}/rest/networkconf/{network_id}",
|
|
1207
|
-
method='PUT',
|
|
1208
1429
|
payload=update_fields
|
|
1209
1430
|
)
|
|
1210
1431
|
|
|
@@ -1212,30 +1433,28 @@ class Client:
|
|
|
1212
1433
|
"""
|
|
1213
1434
|
Delete a network configuration by ID
|
|
1214
1435
|
"""
|
|
1215
|
-
return self.
|
|
1436
|
+
return self.fetch_results(
|
|
1216
1437
|
f"/api/s/{self._site}/rest/networkconf{network_id.strip()}",
|
|
1217
|
-
method='DELETE'
|
|
1218
1438
|
)
|
|
1219
1439
|
|
|
1220
1440
|
def list_portconf(self):
|
|
1221
1441
|
"""
|
|
1222
1442
|
List all port configurations on the site.
|
|
1223
1443
|
"""
|
|
1224
|
-
return self.fetch_results(f"/api/s/{self._site}/list/portconf",
|
|
1444
|
+
return self.fetch_results(f"/api/s/{self._site}/list/portconf", proxy_type='network')
|
|
1225
1445
|
|
|
1226
1446
|
def get_portconf(self, portconf_id: str):
|
|
1227
1447
|
"""
|
|
1228
1448
|
Retrieve port configuration by ID
|
|
1229
1449
|
"""
|
|
1230
|
-
return self.
|
|
1450
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/portconf/{portconf_id}")
|
|
1231
1451
|
|
|
1232
1452
|
def create_portconf(self, config: dict):
|
|
1233
1453
|
"""
|
|
1234
1454
|
Create a new port configuration.
|
|
1235
1455
|
"""
|
|
1236
|
-
return self.
|
|
1456
|
+
return self.fetch_results(
|
|
1237
1457
|
f"/api/s/{self._site}/rest/portconf",
|
|
1238
|
-
method='POST',
|
|
1239
1458
|
payload=config
|
|
1240
1459
|
)
|
|
1241
1460
|
|
|
@@ -1243,9 +1462,8 @@ class Client:
|
|
|
1243
1462
|
"""
|
|
1244
1463
|
Update an existing port configuration.
|
|
1245
1464
|
"""
|
|
1246
|
-
return self.
|
|
1465
|
+
return self.fetch_results(
|
|
1247
1466
|
f"/api/s/{self._site}/rest/portconf/{portconf_id}",
|
|
1248
|
-
method='PUT',
|
|
1249
1467
|
payload=config
|
|
1250
1468
|
)
|
|
1251
1469
|
|
|
@@ -1253,9 +1471,8 @@ class Client:
|
|
|
1253
1471
|
"""
|
|
1254
1472
|
Delete a port configuration by ID.
|
|
1255
1473
|
"""
|
|
1256
|
-
return self.
|
|
1474
|
+
return self.fetch_results(
|
|
1257
1475
|
f"/api/s/{self._site}/rest/portconf/{portconf_id}",
|
|
1258
|
-
method='DELETE'
|
|
1259
1476
|
)
|
|
1260
1477
|
|
|
1261
1478
|
def stat_ips_events(self, start: int = None, end: int = None, limit: int = None):
|
|
@@ -1273,7 +1490,7 @@ class Client:
|
|
|
1273
1490
|
end = end if end is not None else int(time.time() * 1000)
|
|
1274
1491
|
start = start if start is not None else end - (7 * 24 * 3600 * 1000)
|
|
1275
1492
|
payload = {'mac': mac, 'start': start, 'end': end}
|
|
1276
|
-
return self.
|
|
1493
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/session", payload=payload)
|
|
1277
1494
|
|
|
1278
1495
|
def stat_sta_sessions_latest(self, mac: str, limit: int = None):
|
|
1279
1496
|
"""Fetch latest 'n' login sessions for a client (defaults to 5)."""
|
|
@@ -1288,7 +1505,7 @@ class Client:
|
|
|
1288
1505
|
end = end if end is not None else int(time.time() * 1000)
|
|
1289
1506
|
start = start if start is not None else end - (7 * 24 * 3600 * 1000)
|
|
1290
1507
|
payload = {'mac': mac, 'start': start, 'end': end}
|
|
1291
|
-
return self.
|
|
1508
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/", payload=payload, proxy_type='network')
|
|
1292
1509
|
|
|
1293
1510
|
def stat_all_user(self, start: int = None, end: int = None):
|
|
1294
1511
|
"""
|
|
@@ -1297,7 +1514,7 @@ class Client:
|
|
|
1297
1514
|
end = end if end is not None else int(time.time() * 1000)
|
|
1298
1515
|
start = start if start is not None else end - (7 * 24 * 3600 * 1000)
|
|
1299
1516
|
payload = {'start': start, 'end': end}
|
|
1300
|
-
return self.
|
|
1517
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/alluser", payload=payload)
|
|
1301
1518
|
|
|
1302
1519
|
def stat_allusers(self, historyhours: int = 8760):
|
|
1303
1520
|
"""Fetch clients seen within the past N hours (all-time totals)."""
|
|
@@ -1312,7 +1529,7 @@ class Client:
|
|
|
1312
1529
|
start = start if start is not None else end - (7 * 24 * 3600 * 1000)
|
|
1313
1530
|
attribs = ['time'] + attribs if attribs else ['time'] + self.default_site_stats_attribs
|
|
1314
1531
|
payload = {'attrs': attribs, 'start': start, 'end': end}
|
|
1315
|
-
return self.
|
|
1532
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/daily.site", payload=payload)
|
|
1316
1533
|
|
|
1317
1534
|
def stat_monthly_site(self, start: int = None, end: int = None, attribs: list = None):
|
|
1318
1535
|
"""
|
|
@@ -1322,33 +1539,33 @@ class Client:
|
|
|
1322
1539
|
start = start if start is not None else end - (30 * 24 * 3600 * 1000)
|
|
1323
1540
|
attribs = ['time'] + attribs if attribs else ['time'] + self.default_site_stats_attribs
|
|
1324
1541
|
payload = {'attrs': attribs, 'start': start, 'end': end}
|
|
1325
|
-
return self.
|
|
1542
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/monthly.site", payload=payload)
|
|
1326
1543
|
|
|
1327
1544
|
def stat_current_user(self):
|
|
1328
1545
|
"""
|
|
1329
1546
|
Get stats for currently connected users.
|
|
1330
1547
|
"""
|
|
1331
|
-
return self.
|
|
1548
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/sta")
|
|
1332
1549
|
|
|
1333
1550
|
def stat_all_users(self):
|
|
1334
1551
|
"""
|
|
1335
1552
|
Get usage stats for all known users.
|
|
1336
1553
|
"""
|
|
1337
|
-
return self.
|
|
1554
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/alluser")
|
|
1338
1555
|
|
|
1339
1556
|
def stat_voucher(self, create_time: int = None):
|
|
1340
1557
|
"""
|
|
1341
1558
|
Fetch statistics about vouchers, optionally filtering by creation time
|
|
1342
1559
|
"""
|
|
1343
1560
|
payload = {'create_time': create_time} if create_time is not None else {}
|
|
1344
|
-
return self.
|
|
1561
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/voucher", payload=payload)
|
|
1345
1562
|
|
|
1346
1563
|
def stat_payment(self, within: int=None):
|
|
1347
1564
|
"""
|
|
1348
1565
|
Fetch statistics about payments, optionally filtering by time window
|
|
1349
1566
|
"""
|
|
1350
1567
|
path_suffix = f"?within={within}" if within is not None else ""
|
|
1351
|
-
return self.
|
|
1568
|
+
return self.fetch_results(f"api/s/{self._site}/stat/payment{path_suffix}")
|
|
1352
1569
|
|
|
1353
1570
|
def create_hotspotop(self, name: str, x_password: str, note: str = '') -> bool:
|
|
1354
1571
|
"""Create hotspot operator user"""
|
|
@@ -1370,7 +1587,7 @@ class Client:
|
|
|
1370
1587
|
end = end if end is not None else int(time.time())
|
|
1371
1588
|
start = start if start is not None else end - (7 * 24 * 3600)
|
|
1372
1589
|
payload = {'start': start, 'end': end}
|
|
1373
|
-
return self.
|
|
1590
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/authorization", payload=payload)
|
|
1374
1591
|
|
|
1375
1592
|
def stat_sessions(self, start: int = None, end: int = None, mac: str = None, type: str = 'all'):
|
|
1376
1593
|
"""
|
|
@@ -1386,7 +1603,7 @@ class Client:
|
|
|
1386
1603
|
if mac:
|
|
1387
1604
|
payload['mac'] = mac.lower()
|
|
1388
1605
|
|
|
1389
|
-
return self.
|
|
1606
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/session", payload=payload)
|
|
1390
1607
|
|
|
1391
1608
|
def stat_client(self, mac: str):
|
|
1392
1609
|
"""Fetch details for a single client device."""
|
|
@@ -1459,26 +1676,26 @@ class Client:
|
|
|
1459
1676
|
Retrieve list of alarms with optional filtering payload
|
|
1460
1677
|
"""
|
|
1461
1678
|
payload = payload or {}
|
|
1462
|
-
return self.
|
|
1679
|
+
return self.fetch_results(f"/api/s/{self._site}/list/alarm", payload=payload)
|
|
1463
1680
|
|
|
1464
1681
|
def list_events(self, historyhours: int = 720, start: int = 0, limit: int = 3000):
|
|
1465
1682
|
payload = {
|
|
1466
1683
|
'_sort': '-time',
|
|
1467
1684
|
'within': historyhours,
|
|
1468
|
-
'type':
|
|
1685
|
+
'type': None,
|
|
1469
1686
|
'_start': start,
|
|
1470
1687
|
'_limit': limit
|
|
1471
1688
|
}
|
|
1472
|
-
return self.
|
|
1689
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/event", payload=payload)
|
|
1473
1690
|
|
|
1474
1691
|
def list_tags(self):
|
|
1475
|
-
return self.
|
|
1692
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/tag")
|
|
1476
1693
|
|
|
1477
1694
|
def list_dpi_stats(self):
|
|
1478
1695
|
"""
|
|
1479
1696
|
List DPI stats.
|
|
1480
1697
|
"""
|
|
1481
|
-
return self.
|
|
1698
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/dpi", proxy_type='network')
|
|
1482
1699
|
|
|
1483
1700
|
def list_dpi_stats_filtered(self, type: str = 'by_cat', cat_filter: list = None):
|
|
1484
1701
|
"""
|
|
@@ -1492,11 +1709,11 @@ class Client:
|
|
|
1492
1709
|
if isinstance(cat_filter, list) and type == 'by_app':
|
|
1493
1710
|
payload['cats'] = cat_filter
|
|
1494
1711
|
|
|
1495
|
-
return self.
|
|
1712
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/sitedpi", payload=payload)
|
|
1496
1713
|
|
|
1497
1714
|
def list_dpi_app_categories(self):
|
|
1498
1715
|
"""Fetch DPI application categories."""
|
|
1499
|
-
return self.fetch_results(f"/api/s/{self._site}/list/dpi/application/categories")
|
|
1716
|
+
return self.fetch_results(f"/api/s/{self._site}/list/dpi/application/categories", proxy_type='network')
|
|
1500
1717
|
|
|
1501
1718
|
def list_dpi_app(self):
|
|
1502
1719
|
"""Fetch DPI applications."""
|
|
@@ -1513,7 +1730,7 @@ class Client:
|
|
|
1513
1730
|
return self.fetch_results(f"/api/s/{self._site}/stat/ccode")
|
|
1514
1731
|
|
|
1515
1732
|
def list_radius_accounts(self):
|
|
1516
|
-
return self.
|
|
1733
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/account")
|
|
1517
1734
|
|
|
1518
1735
|
def list_radius_profiles(self):
|
|
1519
1736
|
"""Fetch RADIUS profiles"""
|
|
@@ -1585,7 +1802,7 @@ class Client:
|
|
|
1585
1802
|
|
|
1586
1803
|
path = f"/v2/api/site/{self._site}/system-log/{class_}"
|
|
1587
1804
|
|
|
1588
|
-
return self.fetch_results(path, payload=payload,
|
|
1805
|
+
return self.fetch_results(path, payload=payload, proxy_type='network')
|
|
1589
1806
|
|
|
1590
1807
|
def delete_radius_account(self, account_id: str) -> bool:
|
|
1591
1808
|
"""Delete a Radius user account"""
|
|
@@ -1595,17 +1812,17 @@ class Client:
|
|
|
1595
1812
|
return result
|
|
1596
1813
|
|
|
1597
1814
|
def list_readius_profiles(self):
|
|
1598
|
-
return self.
|
|
1815
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/radiusprofile")
|
|
1599
1816
|
|
|
1600
1817
|
def list_hotspot_operators(self):
|
|
1601
|
-
return self.
|
|
1818
|
+
return self.fetch_results(f"api/s/{self._site}/rest/hotspotop")
|
|
1602
1819
|
|
|
1603
1820
|
def count_alarms(self, archived: bool = None):
|
|
1604
1821
|
"""
|
|
1605
1822
|
Count alarms; if archived=False counts only non-archived
|
|
1606
1823
|
"""
|
|
1607
1824
|
suffix = '?archived=false' if archived is False else ''
|
|
1608
|
-
return self.
|
|
1825
|
+
return self.fetch_results(f"/api/s/{self._site}/cnt/alarm{suffix}")
|
|
1609
1826
|
|
|
1610
1827
|
def archive_alarm(self, alarm_id: str = '') -> bool:
|
|
1611
1828
|
"""
|
|
@@ -1615,7 +1832,7 @@ class Client:
|
|
|
1615
1832
|
payload = {'_id': alarm_id, 'cmd': 'archive-alarm'}
|
|
1616
1833
|
else:
|
|
1617
1834
|
payload = {'cmd': 'archive-all-alarms'}
|
|
1618
|
-
self.
|
|
1835
|
+
self.fetch_results(f"/api/s/{self._site}/cmd/evtmgr", payload=payload)
|
|
1619
1836
|
return self._last_response_code == 200
|
|
1620
1837
|
|
|
1621
1838
|
def stat_speedtest_results(self, start: int = None, end: int = None):
|
|
@@ -1629,38 +1846,35 @@ class Client:
|
|
|
1629
1846
|
'start': start,
|
|
1630
1847
|
'end': end
|
|
1631
1848
|
}
|
|
1632
|
-
return self.
|
|
1633
|
-
|
|
1634
|
-
def list_health(self):
|
|
1635
|
-
return self._request(f"/api/s/{self._site}/stat/heatlh")
|
|
1849
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/report/archive.speedtest", payload=payload)
|
|
1636
1850
|
|
|
1637
1851
|
def stat_user_devices(self):
|
|
1638
1852
|
"""
|
|
1639
1853
|
Retrieve statistics on user devices.
|
|
1640
1854
|
"""
|
|
1641
|
-
return self.
|
|
1855
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/user/devices", proxy_type='network')
|
|
1642
1856
|
|
|
1643
1857
|
def stat_sites(self):
|
|
1644
1858
|
"""
|
|
1645
1859
|
Retrieve statistics for all available sites.
|
|
1646
1860
|
"""
|
|
1647
|
-
return self.
|
|
1861
|
+
return self.fetch_results("/api/stat/sites")
|
|
1648
1862
|
|
|
1649
1863
|
def list_devices(self, macs: list[str] = []):
|
|
1650
1864
|
"""
|
|
1651
1865
|
Fetch UniFi devices, optionally filtered by MAC addresses.
|
|
1652
1866
|
"""
|
|
1653
1867
|
payload = {'macs': [mac.lower() for mac in macs]}
|
|
1654
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/device", payload=payload,
|
|
1868
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/device", payload=payload, proxy_type='network')
|
|
1655
1869
|
|
|
1656
1870
|
def list_devices_basic(self):
|
|
1657
|
-
return self.fetch_results(f"/api/s/{self._site}/stat/device-basic",
|
|
1871
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/device-basic", proxy_type='network')
|
|
1658
1872
|
|
|
1659
1873
|
def check_controller_update(self):
|
|
1660
1874
|
"""
|
|
1661
1875
|
Fetch latest known controller version info
|
|
1662
1876
|
"""
|
|
1663
|
-
return self.
|
|
1877
|
+
return self.fetch_results(f"/api/s/{self._site}/stat/fwupdate/latest-version")
|
|
1664
1878
|
|
|
1665
1879
|
def get_update_os_console(self):
|
|
1666
1880
|
"""
|
|
@@ -1668,7 +1882,7 @@ class Client:
|
|
|
1668
1882
|
"""
|
|
1669
1883
|
if not self._unifi_os:
|
|
1670
1884
|
raise NotAUnifiOsConsoleException()
|
|
1671
|
-
return self.
|
|
1885
|
+
return self.fetch_results('/api/firmware/update')
|
|
1672
1886
|
|
|
1673
1887
|
def update_os_console(self) -> bool:
|
|
1674
1888
|
"""
|
|
@@ -1677,8 +1891,8 @@ class Client:
|
|
|
1677
1891
|
if not self._unifi_os:
|
|
1678
1892
|
raise NotAUnifiOsConsoleException()
|
|
1679
1893
|
payload = {'persistFullData': True}
|
|
1680
|
-
self.
|
|
1681
|
-
return
|
|
1894
|
+
results = self.fetch_results(f"/api/s/{self._site}/cmd/firmware/update", payload=payload, proxy_type='network')
|
|
1895
|
+
return results
|
|
1682
1896
|
|
|
1683
1897
|
|
|
1684
1898
|
## ---------- Deprecated Methods ---------
|
|
@@ -1772,6 +1986,24 @@ class Client:
|
|
|
1772
1986
|
self._unifi_os = is_unifi_os
|
|
1773
1987
|
return True
|
|
1774
1988
|
|
|
1989
|
+
def get_firmware_version(self) -> str:
|
|
1990
|
+
"""Return detected firmware version ('v1', 'v2', or None if unknown)"""
|
|
1991
|
+
return self._firmware_version
|
|
1992
|
+
|
|
1993
|
+
def set_firmware_version(self, version: str) -> bool:
|
|
1994
|
+
"""Manually set firmware version (e.g., from cached Odoo record)
|
|
1995
|
+
|
|
1996
|
+
Args:
|
|
1997
|
+
version: 'v1' for legacy controllers, 'v2' for UniFi OS, or None to reset
|
|
1998
|
+
|
|
1999
|
+
Returns:
|
|
2000
|
+
True if version was set successfully, False if invalid version
|
|
2001
|
+
"""
|
|
2002
|
+
if version in ('v1', 'v2', None):
|
|
2003
|
+
self._firmware_version = version
|
|
2004
|
+
return True
|
|
2005
|
+
return False
|
|
2006
|
+
|
|
1775
2007
|
def set_connection_timeout(self, timeout: int) -> bool:
|
|
1776
2008
|
"""Set connection timeout in seconds"""
|
|
1777
2009
|
self._connection_timeout = timeout
|
|
@@ -1801,8 +2033,8 @@ class Client:
|
|
|
1801
2033
|
|
|
1802
2034
|
# ----- Protected Helper Methods -----
|
|
1803
2035
|
|
|
1804
|
-
def fetch_results_boolean(self, path: str, payload=None, login_required: bool = True, prefix_path: bool = True) -> bool:
|
|
1805
|
-
return self.fetch_results(path, payload, boolean=True, login_required=login_required, prefix_path=prefix_path)
|
|
2036
|
+
def fetch_results_boolean(self, path: str, payload=None, login_required: bool = True, prefix_path: bool = True, auto_fallback: bool = True) -> bool:
|
|
2037
|
+
return self.fetch_results(path, payload, boolean=True, login_required=login_required, prefix_path=prefix_path, auto_fallback=auto_fallback)
|
|
1806
2038
|
|
|
1807
2039
|
def _get_json_last_error(self) -> bool:
|
|
1808
2040
|
try:
|
|
@@ -1837,7 +2069,7 @@ class Client:
|
|
|
1837
2069
|
def generate_backup(self, days: int = -1):
|
|
1838
2070
|
"""Generate a controller backup for the past N days."""
|
|
1839
2071
|
payload = {'cmd': 'backup', 'days': days}
|
|
1840
|
-
result = self.fetch_results(f"/
|
|
2072
|
+
result = self.fetch_results(f"/api/s/{self._site}/cmd/backup", payload=payload, proxy_type='network', boolean=False)
|
|
1841
2073
|
print(f"RAW RESULT FROM FETCH_RESULTS(): {result}") if self.debug else None
|
|
1842
2074
|
return result
|
|
1843
2075
|
|
|
@@ -1855,7 +2087,7 @@ class Client:
|
|
|
1855
2087
|
'cmd': 'restore-backup',
|
|
1856
2088
|
'file': filename
|
|
1857
2089
|
}
|
|
1858
|
-
return self.fetch_results(f"/api/s/{self._site}/cmd/backup", payload=payload,
|
|
2090
|
+
return self.fetch_results(f"/api/s/{self._site}/cmd/backup", payload=payload, proxy_type='network')
|
|
1859
2091
|
|
|
1860
2092
|
def generate_backup_site(self):
|
|
1861
2093
|
"""Generate a site export backup."""
|
|
@@ -2050,54 +2282,9 @@ class Client:
|
|
|
2050
2282
|
|
|
2051
2283
|
def get_cookies_created_at(self) -> int:
|
|
2052
2284
|
return self._cookies_created_at
|
|
2053
|
-
|
|
2054
|
-
def __construct(
|
|
2055
|
-
self,
|
|
2056
|
-
user: str,
|
|
2057
|
-
password: str,
|
|
2058
|
-
baseurl: str = 'https://127.0.0.1:8443',
|
|
2059
|
-
site: str = 'default',
|
|
2060
|
-
version: str = '8.0.28',
|
|
2061
|
-
ssl_verify: bool = False,
|
|
2062
|
-
unificookie_name: str = 'unificookie'
|
|
2063
|
-
):
|
|
2064
|
-
"""
|
|
2065
|
-
PHP constructor conversion: checks and initial assignments.
|
|
2066
|
-
"""
|
|
2067
|
-
# Ensure HTTP client available
|
|
2068
|
-
self._check_curl()
|
|
2069
|
-
# Validate base URL and site
|
|
2070
|
-
self._check_base_url(baseurl)
|
|
2071
|
-
self._check_site(site)
|
|
2072
|
-
|
|
2073
|
-
# Assign core properties
|
|
2074
|
-
self._baseurl = baseurl.strip()
|
|
2075
|
-
self._site = site.strip().lower()
|
|
2076
|
-
self._user = user.strip()
|
|
2077
|
-
self._password = password.strip()
|
|
2078
|
-
self._version = version.strip()
|
|
2079
|
-
self._unificookie_name = unificookie_name.strip()
|
|
2080
|
-
|
|
2081
|
-
# SSL verification settings
|
|
2082
|
-
self._verify_ssl_cert = ssl_verify
|
|
2083
|
-
|
|
2084
|
-
def __destruct(self):
|
|
2085
|
-
"""
|
|
2086
|
-
PHP destructor: if the unificookie is set in session, skip logout; otherwise logout if logged in.
|
|
2087
|
-
"""
|
|
2088
|
-
# If the unificookie is present in session cookies, skip logout
|
|
2089
|
-
if self._unificookie_name in self._session.cookies.get_dict():
|
|
2090
|
-
return
|
|
2091
|
-
|
|
2092
|
-
# Logout if still logged in
|
|
2093
|
-
if getattr(self, '_is_loggedin', False):
|
|
2094
|
-
try:
|
|
2095
|
-
self.logout()
|
|
2096
|
-
except Exception:
|
|
2097
|
-
pass
|
|
2098
2285
|
|
|
2099
2286
|
def list_firewallgroups(self, group_id: str = ''):
|
|
2100
|
-
return self.fetch_results(f"/api/s/{self._site}/rest/firewallgroup/{group_id.strip()}")
|
|
2287
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/firewallgroup/{group_id.strip()}", proxy_type='network')
|
|
2101
2288
|
|
|
2102
2289
|
def create_firewallgroup(self, group_name: str, group_type: str, group_members: list = []) -> bool:
|
|
2103
2290
|
"""Create a new firewall group"""
|
|
@@ -2109,11 +2296,7 @@ class Client:
|
|
|
2109
2296
|
'group_type': group_type,
|
|
2110
2297
|
'group_members': group_members
|
|
2111
2298
|
}
|
|
2112
|
-
return self.
|
|
2113
|
-
f"/api/s/{self._site}/rest/firewallgroup",
|
|
2114
|
-
method='POST',
|
|
2115
|
-
payload=payload
|
|
2116
|
-
)
|
|
2299
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/firewallgroup", payload=payload, proxy_type='network')
|
|
2117
2300
|
|
|
2118
2301
|
def edit_firewallgroup(self, group_id: str, site_id: str, group_name: str, group_type: str, group_members: list = []) -> bool:
|
|
2119
2302
|
"""Edit an existing firewall group"""
|
|
@@ -2128,10 +2311,11 @@ class Client:
|
|
|
2128
2311
|
'group_members': group_members,
|
|
2129
2312
|
'site_id': site_id
|
|
2130
2313
|
}
|
|
2131
|
-
|
|
2314
|
+
self._curl_method = 'PUT'
|
|
2315
|
+
return self.fetch_results(
|
|
2132
2316
|
f"/api/s/{self._site}/rest/firewallgroup/{group_id.strip()}",
|
|
2133
|
-
|
|
2134
|
-
|
|
2317
|
+
payload=payload,
|
|
2318
|
+
proxy_type='network'
|
|
2135
2319
|
)
|
|
2136
2320
|
|
|
2137
2321
|
def delete_firewallgroup(self, group_id: str) -> bool:
|
|
@@ -2140,7 +2324,7 @@ class Client:
|
|
|
2140
2324
|
self._curl_method = "GET"
|
|
2141
2325
|
|
|
2142
2326
|
def list_firewallrules(self):
|
|
2143
|
-
return self.
|
|
2327
|
+
return self.fetch_results(f"/api/s/{self._site}/rest/firewallrule", proxy_type='network')
|
|
2144
2328
|
|
|
2145
2329
|
def list_routing(self, route_id: str = ''):
|
|
2146
2330
|
return self.fetch_results(f"/api/s/{self._site}/rest/routing/{route_id.strip()}")
|
|
@@ -2323,62 +2507,122 @@ class Client:
|
|
|
2323
2507
|
payload = None,
|
|
2324
2508
|
boolean: bool = False,
|
|
2325
2509
|
login_required: bool = False,
|
|
2326
|
-
|
|
2510
|
+
proxy_type: str = 'network',
|
|
2511
|
+
auto_fallback: bool = True
|
|
2327
2512
|
):
|
|
2513
|
+
"""Fetch results from UniFi API with automatic v1/v2 firmware detection.
|
|
2514
|
+
|
|
2515
|
+
Args:
|
|
2516
|
+
path: API endpoint path
|
|
2517
|
+
payload: Request payload (optional)
|
|
2518
|
+
boolean: If True, return boolean instead of data
|
|
2519
|
+
login_required: If True, raise if not logged in
|
|
2520
|
+
proxy_type: Proxy category for UniFi OS devices:
|
|
2521
|
+
- 'network': /proxy/network prefix (v1/v2 fallback supported)
|
|
2522
|
+
- 'users': /proxy/users prefix (v2 only)
|
|
2523
|
+
- 'protect': /proxy/protect prefix (v2 only)
|
|
2524
|
+
- None: No prefix, direct /api/ path (v2 only)
|
|
2525
|
+
auto_fallback: If True, automatically fallback from v2 to v1 on JSON decode error
|
|
2526
|
+
(only applies when proxy_type='network')
|
|
2527
|
+
|
|
2528
|
+
Returns:
|
|
2529
|
+
API response data, or boolean if boolean=True
|
|
2530
|
+
"""
|
|
2328
2531
|
if login_required and not self._is_loggedin:
|
|
2329
2532
|
raise LoginRequiredException()
|
|
2330
2533
|
|
|
2331
|
-
|
|
2332
|
-
|
|
2534
|
+
# Use cached firmware version if known (only affects network endpoints)
|
|
2535
|
+
if proxy_type == 'network':
|
|
2536
|
+
if self._firmware_version == 'v1':
|
|
2537
|
+
proxy_type = None # v1 doesn't use /proxy/network prefix
|
|
2538
|
+
# v2 keeps proxy_type='network'
|
|
2539
|
+
|
|
2540
|
+
# Track the proxy_type we're using for caching
|
|
2541
|
+
used_proxy_type = proxy_type
|
|
2333
2542
|
|
|
2334
|
-
|
|
2335
|
-
|
|
2543
|
+
try:
|
|
2544
|
+
self._last_results_raw = self.exec_curl(path, payload, proxy_type)
|
|
2545
|
+
self._last_results_raw = self._last_results_raw.decode()
|
|
2546
|
+
|
|
2547
|
+
if isinstance(self._last_results_raw, str):
|
|
2336
2548
|
response = json.loads(self._last_results_raw)
|
|
2337
2549
|
print("Fetched response:", response) if self.debug else None
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2550
|
+
|
|
2551
|
+
# Cache successful firmware version (only if not already cached)
|
|
2552
|
+
# If any proxy path works, we're on v2 (UniFi OS)
|
|
2553
|
+
if self._firmware_version is None and used_proxy_type is not None:
|
|
2554
|
+
self._firmware_version = 'v2'
|
|
2555
|
+
if self.debug:
|
|
2556
|
+
print(f"Detected firmware version: {self._firmware_version}")
|
|
2557
|
+
|
|
2558
|
+
if isinstance(response, dict) and 'meta' in response:
|
|
2559
|
+
if response['meta'].get('rc') == 'ok':
|
|
2560
|
+
self._last_error_message = ''
|
|
2561
|
+
if 'data' in response:
|
|
2562
|
+
if isinstance(response['data'], list):
|
|
2563
|
+
print("Response inside fetch_results():", response) if self.debug else None
|
|
2564
|
+
print("Data:", response.get("data")) if self.debug else None
|
|
2565
|
+
return response['data'] if not boolean else True
|
|
2566
|
+
return [response['data']] if not boolean else True
|
|
2567
|
+
return True
|
|
2568
|
+
elif response['meta'].get('rc') == 'error':
|
|
2569
|
+
self._last_error_message = 'An unknown error was returned by the controller'
|
|
2570
|
+
raise Exception(f"Error message: {self._last_error_message} - {response}")
|
|
2571
|
+
|
|
2572
|
+
if path.startswith('/v2/api/'):
|
|
2573
|
+
if 'errorCode' in response:
|
|
2574
|
+
self._last_error_message = 'An unknown error was returned by an API v2 endpoint'
|
|
2575
|
+
raise Exception(f"Error code: {response['errorCode']}, message: {self._last_error_message}")
|
|
2576
|
+
return response
|
|
2577
|
+
|
|
2578
|
+
# Proxy API response (users, protect, etc.)
|
|
2579
|
+
# These have code: 1 (positive) for success, negative codes for errors
|
|
2580
|
+
if used_proxy_type is not None:
|
|
2581
|
+
if 'code' in response:
|
|
2582
|
+
if response['code'] < 0:
|
|
2583
|
+
# Negative code is an error
|
|
2584
|
+
self._last_error_message = response.get('msg', response.get('message', 'API error'))
|
|
2585
|
+
raise Exception(f"Error code: {response['code']}, message: {self._last_error_message}")
|
|
2586
|
+
# Positive code (1) means success - return data
|
|
2587
|
+
if 'data' in response:
|
|
2349
2588
|
return response['data'] if not boolean else True
|
|
2350
|
-
return
|
|
2589
|
+
return response if not boolean else True
|
|
2590
|
+
return response if not boolean else True
|
|
2591
|
+
|
|
2592
|
+
# UniFi OS system response (paths like /api/system, /api/backup, etc.)
|
|
2593
|
+
if path.startswith('/api/') and used_proxy_type is None:
|
|
2594
|
+
if 'code' in response:
|
|
2595
|
+
self._last_error_message = response.get('message', 'An unknown error was returned by a UniFi OS endpoint.')
|
|
2596
|
+
raise Exception(f"Error code: {response['code']}, message: {self._last_error_message}")
|
|
2597
|
+
if not boolean:
|
|
2598
|
+
return [response]
|
|
2351
2599
|
return True
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
raise Exception(f"Error code: {response['code']}, message: {self._last_error_message}")
|
|
2368
|
-
if not boolean:
|
|
2369
|
-
return [response]
|
|
2370
|
-
return True
|
|
2371
|
-
return False
|
|
2600
|
+
return False
|
|
2601
|
+
|
|
2602
|
+
except json.JSONDecodeError as e:
|
|
2603
|
+
# If proxy path failed with JSON decode error and auto_fallback enabled, try without proxy prefix
|
|
2604
|
+
if auto_fallback and used_proxy_type is not None and self._firmware_version is None:
|
|
2605
|
+
if self.debug:
|
|
2606
|
+
print(f"JSON decode error on v2 path, attempting v1 fallback...")
|
|
2607
|
+
self._firmware_version = 'v1' # Cache for future calls
|
|
2608
|
+
return self.fetch_results(
|
|
2609
|
+
path, payload, boolean, login_required,
|
|
2610
|
+
proxy_type=None, # v1 uses no proxy prefix
|
|
2611
|
+
auto_fallback=False # Don't recurse again
|
|
2612
|
+
)
|
|
2613
|
+
# Re-raise if fallback not applicable or already tried
|
|
2614
|
+
raise JsonDecodeException(f"Invalid JSON response from controller: {e}")
|
|
2372
2615
|
|
|
2373
2616
|
def fetch_results_boolean(
|
|
2374
2617
|
self,
|
|
2375
2618
|
path: str,
|
|
2376
2619
|
payload=None,
|
|
2377
2620
|
login_required: bool = True,
|
|
2378
|
-
|
|
2621
|
+
proxy_type: str = 'network',
|
|
2622
|
+
auto_fallback: bool = True
|
|
2379
2623
|
) -> bool:
|
|
2380
2624
|
"""Call fetch_results and always return a boolean"""
|
|
2381
|
-
return self.fetch_results(path, payload, True, login_required,
|
|
2625
|
+
return self.fetch_results(path, payload, True, login_required, proxy_type, auto_fallback)
|
|
2382
2626
|
|
|
2383
2627
|
def get_json_last_error(self) -> bool:
|
|
2384
2628
|
"""Raise exception with message matching last JSON decoding error."""
|
|
@@ -2408,15 +2652,26 @@ class Client:
|
|
|
2408
2652
|
|
|
2409
2653
|
return True
|
|
2410
2654
|
|
|
2411
|
-
def exec_curl(self, path: str, payload=None,
|
|
2655
|
+
def exec_curl(self, path: str, payload=None, proxy_type: str = None):
|
|
2656
|
+
"""Execute HTTP request to UniFi controller.
|
|
2657
|
+
|
|
2658
|
+
Args:
|
|
2659
|
+
path: API endpoint path (e.g., /api/s/{site}/stat/health)
|
|
2660
|
+
payload: Request payload (optional)
|
|
2661
|
+
proxy_type: Proxy category for UniFi OS devices:
|
|
2662
|
+
- 'network': /proxy/network prefix (for network management APIs)
|
|
2663
|
+
- 'users': /proxy/users prefix (for user management APIs)
|
|
2664
|
+
- 'protect': /proxy/protect prefix (for UniFi Protect APIs)
|
|
2665
|
+
- None: No prefix, direct /api/ path (for UniFi OS system APIs)
|
|
2666
|
+
"""
|
|
2412
2667
|
# 1) method sanity check
|
|
2413
2668
|
if self._curl_method not in self.CURL_METHODS_ALLOWED:
|
|
2414
2669
|
raise InvalidCurlMethodException()
|
|
2415
2670
|
|
|
2416
2671
|
# 2) build URL
|
|
2417
2672
|
url = f"{self._baseurl}{path}"
|
|
2418
|
-
if self._unifi_os and
|
|
2419
|
-
url = f"{self._baseurl}/proxy/
|
|
2673
|
+
if self._unifi_os and proxy_type:
|
|
2674
|
+
url = f"{self._baseurl}/proxy/{proxy_type}{path}"
|
|
2420
2675
|
|
|
2421
2676
|
# 3) build curl_options dict
|
|
2422
2677
|
"""
|
|
@@ -2493,7 +2748,7 @@ class Client:
|
|
|
2493
2748
|
if self.login():
|
|
2494
2749
|
if self.debug:
|
|
2495
2750
|
print("exec_curl: re-login succeeded, retrying exec_curl")
|
|
2496
|
-
return self.exec_curl(path, payload,
|
|
2751
|
+
return self.exec_curl(path, payload, proxy_type)
|
|
2497
2752
|
raise LoginFailedException('Cookie/Token expired and re-login failed.')
|
|
2498
2753
|
raise LoginFailedException('Login failed, check credentials.')
|
|
2499
2754
|
|
|
@@ -2505,6 +2760,7 @@ class Client:
|
|
|
2505
2760
|
print("Payload:", json_payload or '<empty>')
|
|
2506
2761
|
print("Response Code:", http_code)
|
|
2507
2762
|
print("Response Body:", resp.text)
|
|
2763
|
+
print(self._curl_method)
|
|
2508
2764
|
print("-----------------------------\n")
|
|
2509
2765
|
|
|
2510
2766
|
# 11) reset method and retry count
|
|
@@ -2607,7 +2863,131 @@ class Client:
|
|
|
2607
2863
|
for header in self.curl_headers:
|
|
2608
2864
|
if header.lower().find('x-csrf-token:') == -1:
|
|
2609
2865
|
filtered.append(header)
|
|
2610
|
-
self.
|
|
2866
|
+
self._curl_headers = filtered
|
|
2611
2867
|
|
|
2612
2868
|
# 8) Append the new header, using only ASCII
|
|
2613
|
-
self.
|
|
2869
|
+
self._curl_headers.append('x-csrf-token: %s' % csrf_token)
|
|
2870
|
+
|
|
2871
|
+
# =========================================================================
|
|
2872
|
+
# SSH Management Methods
|
|
2873
|
+
# =========================================================================
|
|
2874
|
+
|
|
2875
|
+
def set_ssh_password(self, password: str):
|
|
2876
|
+
"""Set the SSH password for UniFi OS.
|
|
2877
|
+
|
|
2878
|
+
Args:
|
|
2879
|
+
password: The SSH password to set.
|
|
2880
|
+
|
|
2881
|
+
Returns:
|
|
2882
|
+
True on success (200/204), False on failure.
|
|
2883
|
+
"""
|
|
2884
|
+
payload = {'password': password}
|
|
2885
|
+
try:
|
|
2886
|
+
self.fetch_results("/api/system/ssh/setpassword", payload=payload, proxy_type=None)
|
|
2887
|
+
return True
|
|
2888
|
+
except JsonDecodeException:
|
|
2889
|
+
# 204 No Content returns empty body - that's success
|
|
2890
|
+
return True
|
|
2891
|
+
except Exception:
|
|
2892
|
+
return False
|
|
2893
|
+
|
|
2894
|
+
def turn_on_ssh(self, password: str):
|
|
2895
|
+
"""Enable SSH on the UniFi controller.
|
|
2896
|
+
|
|
2897
|
+
Args:
|
|
2898
|
+
password: SSH password to set before enabling.
|
|
2899
|
+
|
|
2900
|
+
Returns:
|
|
2901
|
+
API response on success, error string on failure.
|
|
2902
|
+
"""
|
|
2903
|
+
result = self.set_ssh_password(password)
|
|
2904
|
+
if not result:
|
|
2905
|
+
return 'Failed to set password, try again later.'
|
|
2906
|
+
|
|
2907
|
+
self._curl_method = 'PATCH'
|
|
2908
|
+
return self.fetch_results("/api/system", payload={'ssh': {'enabled': True}}, proxy_type=None)
|
|
2909
|
+
|
|
2910
|
+
def turn_off_ssh(self):
|
|
2911
|
+
"""Disable SSH on the UniFi controller.
|
|
2912
|
+
|
|
2913
|
+
Returns:
|
|
2914
|
+
API response data.
|
|
2915
|
+
"""
|
|
2916
|
+
self._curl_method = 'PATCH'
|
|
2917
|
+
return self.fetch_results("/api/system", payload={'ssh': {'enabled': False}}, proxy_type=None)
|
|
2918
|
+
|
|
2919
|
+
# =========================================================================
|
|
2920
|
+
# Utility Methods
|
|
2921
|
+
# =========================================================================
|
|
2922
|
+
|
|
2923
|
+
def get_protect_devices(self):
|
|
2924
|
+
"""Get UniFi Protect device stats.
|
|
2925
|
+
|
|
2926
|
+
Returns:
|
|
2927
|
+
List of protect device stats, or empty list if Protect not installed.
|
|
2928
|
+
"""
|
|
2929
|
+
try:
|
|
2930
|
+
return self.fetch_results("/api/devices/stat/", proxy_type='protect')
|
|
2931
|
+
except JsonDecodeException:
|
|
2932
|
+
# UniFi Protect not installed returns empty/invalid response
|
|
2933
|
+
return []
|
|
2934
|
+
|
|
2935
|
+
def validate_email(self, email: str) -> bool:
|
|
2936
|
+
"""Validate email address format.
|
|
2937
|
+
|
|
2938
|
+
Args:
|
|
2939
|
+
email: Email address to validate.
|
|
2940
|
+
|
|
2941
|
+
Returns:
|
|
2942
|
+
True if valid, False otherwise.
|
|
2943
|
+
"""
|
|
2944
|
+
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
|
|
2945
|
+
return bool(re.match(pattern, email))
|
|
2946
|
+
|
|
2947
|
+
# =========================================================================
|
|
2948
|
+
# Additional User Management Helpers
|
|
2949
|
+
# =========================================================================
|
|
2950
|
+
|
|
2951
|
+
def get_custom_role(self, network_permission: str, user_permission: str):
|
|
2952
|
+
"""Create a custom role for admin user creation.
|
|
2953
|
+
|
|
2954
|
+
This is a convenience method that builds the role payload from permission strings.
|
|
2955
|
+
Use create_custom_role() if you need to pass a raw payload.
|
|
2956
|
+
|
|
2957
|
+
Args:
|
|
2958
|
+
network_permission: One of 'admin', 'hotspotoperator', 'readonly', 'none'
|
|
2959
|
+
user_permission: One of 'admin', 'readonly', 'none'
|
|
2960
|
+
|
|
2961
|
+
Returns:
|
|
2962
|
+
API response with role data including unique_id.
|
|
2963
|
+
"""
|
|
2964
|
+
import random
|
|
2965
|
+
payload = {
|
|
2966
|
+
'is_private': True,
|
|
2967
|
+
'name': f'role_private_{random.randint(10000000, 99999999)}',
|
|
2968
|
+
'permission_resources': [],
|
|
2969
|
+
'permissions': []
|
|
2970
|
+
}
|
|
2971
|
+
if network_permission != 'none':
|
|
2972
|
+
payload['permissions'].append({'manifest_unique_key': 'network.management', 'formulas': [network_permission]})
|
|
2973
|
+
if user_permission != 'none':
|
|
2974
|
+
payload['permissions'].append({'manifest_unique_key': 'system.management.user', 'formulas': [user_permission]})
|
|
2975
|
+
|
|
2976
|
+
self._curl_method = 'POST'
|
|
2977
|
+
return self.fetch_results("/api/v2/custom_role", payload=payload, proxy_type='users')
|
|
2978
|
+
|
|
2979
|
+
def resend_invite(self, email: str):
|
|
2980
|
+
"""Resend invitation to a user.
|
|
2981
|
+
|
|
2982
|
+
Args:
|
|
2983
|
+
email: Email address to send invite to.
|
|
2984
|
+
|
|
2985
|
+
Returns:
|
|
2986
|
+
API response data, or error string iwf invalid email.
|
|
2987
|
+
"""
|
|
2988
|
+
if not self.validate_email(email):
|
|
2989
|
+
return "Please enter a valid email"
|
|
2990
|
+
|
|
2991
|
+
payload = {'email': email, 'is_resend': True}
|
|
2992
|
+
self._curl_method = 'POST'
|
|
2993
|
+
return self.fetch_results("/api/v2/users/invite_add", payload=payload, proxy_type='users')
|