| 1 |
"""Library for accessing igloohome API""" |
| 2 |
from typing import Optional |
| 3 |
|
| 4 |
from dacite import from_dict, Config |
| 5 |
from datetime import datetime |
| 6 |
|
| 7 |
import aiohttp |
| 8 |
import jwt |
| 9 |
from dataclasses import dataclass |
| 10 |
|
| 11 |
_OAUTH2_HOST = "https://auth.igloohome.co" |
| 12 |
_OAUTH2_TOKEN_PATH = "/oauth2/token" |
| 13 |
_OAUTH2_SCOPE_EVERYTHING = OAUTH2_SCOPE = ("igloohomeapi/algopin-hourly igloohomeapi/algopin-daily " |
| 14 |
"igloohomeapi/algopin-permanent igloohomeapi/algopin-onetime " |
| 15 |
"igloohomeapi/create-pin-bridge-proxied-job " |
| 16 |
"igloohomeapi/delete-pin-bridge-proxied-job " |
| 17 |
"igloohomeapi/lock-bridge-proxied-job " |
| 18 |
"igloohomeapi/unlock-bridge-proxied-job igloohomeapi/get-devices " |
| 19 |
"igloohomeapi/get-job-status igloohomeapi/get-properties") |
| 20 |
|
| 21 |
_BASE_URL = "https://api.igloodeveloper.co" |
| 22 |
_BASE_PATH = "igloohome" |
| 23 |
_DEVICES_PATH_SEGMENT = "devices" |
| 24 |
|
| 25 |
|
| 26 |
def _parse_iso_datetime(val: str) -> datetime: |
| 27 |
if val.endswith("Z"): |
| 28 |
val = val[:-1] + "+00:00" |
| 29 |
return datetime.fromisoformat(val) |
| 30 |
|
| 31 |
|
| 32 |
_GLOBAL_CONFIG = config = Config(type_hooks={ |
| 33 |
datetime: _parse_iso_datetime |
| 34 |
}) |
| 35 |
|
| 36 |
|
| 37 |
@dataclass |
| 38 |
class LinkedDevice: |
| 39 |
type: str |
| 40 |
deviceId: str |
| 41 |
|
| 42 |
|
| 43 |
@dataclass |
| 44 |
class GetDeviceInfoResponse: |
| 45 |
id: str |
| 46 |
type: str |
| 47 |
deviceId: str |
| 48 |
deviceName: str |
| 49 |
pairedAt: str |
| 50 |
homeId: list[str] |
| 51 |
linkedDevices: list[LinkedDevice] |
| 52 |
batteryLevel: Optional[int] |
| 53 |
lastSync: datetime |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
@dataclass |
| 58 |
class GetDevicesResponse: |
| 59 |
nextCursor: str |
| 60 |
payload: list[GetDeviceInfoResponse] |
| 61 |
|
| 62 |
|
| 63 |
@dataclass |
| 64 |
class CreateBridgeProxiedJobResponse: |
| 65 |
jobId: str |
| 66 |
|
| 67 |
|
| 68 |
@dataclass |
| 69 |
class GetJobStatusResponse: |
| 70 |
jobId: str |
| 71 |
expiryDate: str |
| 72 |
completed: bool |
| 73 |
jobType: str |
| 74 |
jobResponse: dict |
| 75 |
|
| 76 |
|
| 77 |
BRIDGE_JOB_LOCK = 1 |
| 78 |
BRIDGE_JOB_UNLOCK = 2 |
| 79 |
BRIDGE_JOB_CREATE_CUSTOM_PIN = 4 |
| 80 |
BRIDGE_JOB_DELETE_CUSTOM_PIN = 5 |
| 81 |
BRIDGE_JOB_GET_BATTERY_LEVEL = 9 |
| 82 |
BRIDGE_JOB_GET_DEVICE_STATUS = 10 |
| 83 |
BRIDGE_JOB_GET_ACTIVITY_LOGS = 15 |
| 84 |
|
| 85 |
"""One of the possible GetDeviceInfoResponse.type values.""" |
| 86 |
DEVICE_TYPE_BRIDGE = "Bridge" |
| 87 |
"""One of the possible GetDeviceInfoResponse.type values.""" |
| 88 |
DEVICE_TYPE_LOCK = "Lock" |
| 89 |
"""One of the possible GetDeviceInfoResponse.type values.""" |
| 90 |
DEVICE_TYPE_KEYPAD = "Keypad" |
| 91 |
|
| 92 |
|
| 93 |
class Auth: |
| 94 |
def __init__( |
| 95 |
self, |
| 96 |
session: aiohttp.ClientSession, |
| 97 |
client_id: str, |
| 98 |
client_secret: str, |
| 99 |
host: str = _OAUTH2_HOST, |
| 100 |
scope: str = _OAUTH2_SCOPE_EVERYTHING, |
| 101 |
) -> None: |
| 102 |
self.access_token = None |
| 103 |
self.session = session |
| 104 |
self.client_id = client_id |
| 105 |
self.client_secret = client_secret |
| 106 |
self.host = host |
| 107 |
self.scope = scope |
| 108 |
|
| 109 |
async def async_get_access_token(self) -> str: |
| 110 |
form = aiohttp.FormData() |
| 111 |
form.add_field("grant_type", "client_credentials") |
| 112 |
form.add_field("scope", self.scope) |
| 113 |
response = await self.session.post( |
| 114 |
url=self.host + _OAUTH2_TOKEN_PATH, |
| 115 |
auth=aiohttp.BasicAuth( |
| 116 |
login=self.client_id, password=self.client_secret |
| 117 |
), |
| 118 |
data=form, |
| 119 |
) |
| 120 |
json = await response.json() |
| 121 |
if response.status == 200: |
| 122 |
self.access_token = json["access_token"] |
| 123 |
return self.access_token |
| 124 |
else: |
| 125 |
raise AuthException(f'Failed to get access token. responseCode=${response.status}') |
| 126 |
|
| 127 |
async def async_get_valid_access_token(self) -> str: |
| 128 |
"""Gets a valid access token.""" |
| 129 |
if self.access_token is None: |
| 130 |
access_token = await self.async_get_access_token() |
| 131 |
return access_token |
| 132 |
elif is_access_token_valid(self.access_token): |
| 133 |
return self.access_token |
| 134 |
else: |
| 135 |
return await self.async_get_access_token() |
| 136 |
|
| 137 |
async def request(self, method: str, url: str, **kwargs) -> aiohttp.ClientResponse: |
| 138 |
"""Make a request.""" |
| 139 |
headers = kwargs.get("headers") |
| 140 |
|
| 141 |
if headers is None: |
| 142 |
headers = {} |
| 143 |
else: |
| 144 |
headers = dict(headers) |
| 145 |
|
| 146 |
headers["Authorization"] = f"Bearer {await self.async_get_valid_access_token()}" |
| 147 |
headers["Accept"] = "application/json" |
| 148 |
|
| 149 |
return await self.session.request( |
| 150 |
method, url, **kwargs, headers=headers, |
| 151 |
) |
| 152 |
|
| 153 |
|
| 154 |
def is_access_token_valid(access_token: str) -> bool: |
| 155 |
"""Check if the access token is valid.""" |
| 156 |
try: |
| 157 |
|
| 158 |
|
| 159 |
claims = jwt.decode(access_token, options={"require": ["exp"]}) |
| 160 |
except Exception: |
| 161 |
return False |
| 162 |
|
| 163 |
|
| 164 |
class AuthException(Exception): |
| 165 |
pass |
| 166 |
|
| 167 |
|
| 168 |
class Api: |
| 169 |
def __init__( |
| 170 |
self, |
| 171 |
auth: Auth, |
| 172 |
host: str = _BASE_URL |
| 173 |
): |
| 174 |
self.auth = auth |
| 175 |
self.host = host |
| 176 |
|
| 177 |
async def get_devices(self) -> GetDevicesResponse: |
| 178 |
response = await self.auth.request( |
| 179 |
"get", |
| 180 |
f'{self.host}/{_BASE_PATH}/{_DEVICES_PATH_SEGMENT}', |
| 181 |
) |
| 182 |
if response.status == 200: |
| 183 |
return from_dict(GetDevicesResponse, await response.json(), config=_GLOBAL_CONFIG) |
| 184 |
else: |
| 185 |
raise ApiException("Response failure", response.status) |
| 186 |
|
| 187 |
async def get_device_info(self, deviceId: str) -> GetDeviceInfoResponse: |
| 188 |
response = await self.auth.request( |
| 189 |
"get", |
| 190 |
f'{self.host}/{_BASE_PATH}/{_DEVICES_PATH_SEGMENT}/{deviceId}', |
| 191 |
) |
| 192 |
if response.status == 200: |
| 193 |
return from_dict(GetDeviceInfoResponse, await response.json(), config=_GLOBAL_CONFIG) |
| 194 |
else: |
| 195 |
raise ApiException("Response failure", response.status) |
| 196 |
|
| 197 |
async def create_bridge_proxied_job( |
| 198 |
self, |
| 199 |
deviceId: str, |
| 200 |
bridgeId: str, |
| 201 |
jobType: int, |
| 202 |
jobData: dict = None |
| 203 |
) -> CreateBridgeProxiedJobResponse: |
| 204 |
response = await self.auth.request( |
| 205 |
"post", |
| 206 |
f'{self.host}/{_BASE_PATH}/{_DEVICES_PATH_SEGMENT}/{deviceId}/jobs/bridges/{bridgeId}', |
| 207 |
json={ |
| 208 |
"jobType": jobType, |
| 209 |
"jobData": jobData, |
| 210 |
} |
| 211 |
) |
| 212 |
if response.status == 200: |
| 213 |
return from_dict(CreateBridgeProxiedJobResponse, await response.json()) |
| 214 |
else: |
| 215 |
raise ApiException("Response failure", response.status) |
| 216 |
|
| 217 |
async def get_job_status(self, jobId: str) -> GetJobStatusResponse: |
| 218 |
response = await self.auth.request( |
| 219 |
"get", |
| 220 |
f'{self.host}/{_BASE_PATH}/jobs/{jobId}' |
| 221 |
) |
| 222 |
if response.status == 200: |
| 223 |
return from_dict(GetJobStatusResponse, await response.json()) |
| 224 |
else: |
| 225 |
raise ApiException("Response failure", response.status) |
| 226 |
|
| 227 |
|
| 228 |
class ApiException(Exception): |
| 229 |
def __init__(self, message: str, response_code: int): |
| 230 |
self.message = message |
| 231 |
self.response_code = response_code |
| 232 |
|
| 233 |
def __str__(self): |
| 234 |
return f'ApiException(message={self.message}, response_code={self.response_code})' |
| 235 |
|
| 236 |
|
| 237 |
async def _create_exception(response: aiohttp.ClientResponse) -> ApiException: |
| 238 |
return ApiException( |
| 239 |
message=f'Unsuccessful request. code={response.status}, message={await response.text()}', |
| 240 |
response_code=response.status |
| 241 |
) |