Debian Codegraph @

ekey_bionyxpy/models.py

raw symbols SCIP
1 """Module for interacting with the objects returned by the API."""
2
3 from enum import Enum
4 from typing import Any
5 from typing import Literal
6 from typing import NotRequired
7 from typing import TypedDict
8
9 from .auth import AbstractAuth
10
11
12 class FunctionQuotas(TypedDict):
13 free: int
14 used: int
15
16
17 class SystemResponse(TypedDict):
18 systemName: str
19 systemId: str
20 ownSystem: bool
21 functionWebhookQuotas: FunctionQuotas
22
23
24 class WebhookResponse(TypedDict):
25 functionWebhookId: str
26 integrationName: str
27 locationName: str
28 functionName: str
29 expiresAt: str
30 modificationState: str | None
31
32
33 class WebhookDefinitionMethods(Enum):
34 GET = "Get"
35 POST = "Post"
36 PUT = "Put"
37 DELETE = "Delete"
38 PATCH = "Patch"
39 HEAD = "Head"
40
41
42 class WebhookDefinitionSecurityLevel(Enum):
43 TLSWITHCACHECK = "TlsWithCACheck"
44 TLSALLOWSELFFIGNED = "TlsAllowSelfSigned"
45 ALLOWHTTP = "AllowHttp"
46 TLSPINNEDCERTIFICATE = "TlsPinnedCertificate"
47
48
49 class WebhookDefinitionBody(TypedDict):
50 contentType: NotRequired[str]
51 content: str | dict
52
53
54 class WebhookDefinitionAuthenticationType(Enum):
55 NONE = "None"
56 OAUTH2ACCESSTOKEN = "OAuth2IssuedAccessToken"
57 OAUTH2REFRESHTOKEN = "OAuth2IssuedRefreshToken"
58
59
60 class WebhookDefinitionAuthentication(TypedDict):
61 apiAuthenticationType: (
62 WebhookDefinitionAuthenticationType | Literal["None", "OAuth2IssuedAccessToken", "OAuth2IssuedRefreshToken"]
63 )
64 expiresIn: NotRequired[int]
65 clientId: NotRequired[str]
66 accessToken: NotRequired[str]
67 refreshToken: NotRequired[str]
68 tokenEndoint: NotRequired[str]
69 scope: NotRequired[str]
70 authorizationEndpoint: NotRequired[str]
71
72
73 class WebhookDefinition(TypedDict):
74 method: WebhookDefinitionMethods | Literal["Get", "Post", "Put", "Delete", "Patch", "Head"]
75 url: str
76 body: NotRequired[WebhookDefinitionBody]
77 securityLevel: (
78 WebhookDefinitionSecurityLevel
79 | Literal["AllowHttp", "TlsWithCACheck", "TlsAllowSelfSigned", "TlsPinnedCertificate"]
80 )
81 pinnedCertificate: NotRequired[str]
82 timeout: NotRequired[int]
83 additionalHttpHeaders: NotRequired[Any]
84 authentication: WebhookDefinitionAuthentication
85
86
87 class WebhookData(TypedDict):
88 functionWebhookId: NotRequired[str]
89 integrationName: str
90 locationName: NotRequired[str]
91 functionName: NotRequired[str]
92 expiresAt: NotRequired[str]
93 modificationState: NotRequired[str]
94 definition: WebhookDefinition
95
96
97 class WebhookRename(TypedDict):
98 locationName: NotRequired[str]
99 functionName: NotRequired[str]
100
101
102 class Webhook:
103 """Class for interacting with webhooks."""
104
105 def __init__(self, raw_data: WebhookResponse, system_id: str, auth: AbstractAuth) -> None:
106 self._system_id = system_id
107 self._auth = auth
108 self._update_values(raw_data)
109
110 def _update_values(self, data: WebhookResponse) -> None:
111 self._webhook_id = data["functionWebhookId"]
112 self._webhook_function_name = data["functionName"]
113 self._webhook_location_name = data["locationName"]
114 self._expires_at = data["expiresAt"]
115 self._modification_state = data["modificationState"]
116
117 @property
118 def webhook_id(self) -> str:
119 return self._webhook_id
120
121 @property
122 def webhook_function_name(self) -> str:
123 return self._webhook_function_name
124
125 @property
126 def webhook_location_name(self) -> str:
127 return self._webhook_location_name
128
129 @property
130 def expires_at(self) -> str:
131 return self._expires_at
132
133 @property
134 def modification_state(self) -> str:
135 return self._modification_state
136
137 async def get_update(self) -> None:
138 """Gets the current version of the webhook as stored in the ekey system."""
139 resp = await self._auth.request("GET", f"systems/{self._system_id}/function-webhooks/{self._webhook_id}")
140 resp.raise_for_status()
141 json_data = await resp.json()
142 self._update_values(json_data)
143
144 async def delete(self) -> None:
145 """Requests deletion of the webhook. User needs to confirm."""
146 resp = await self._auth.request("DELETE", f"systems/{self._system_id}/function-webhooks/{self._webhook_id}")
147 resp.raise_for_status()
148 self._modification_state = "DeleteRequested"
149
150 async def update(self, webhook_data: WebhookData) -> None:
151 """Updates the definition of the webhook. User needs to confirm.
152
153 Args:
154 webhook_data (WebhookData): The new data for the webhook.
155 """
156 resp = await self._auth.request(
157 "PUT", f"systems/{self._system_id}/function-webhooks/{self._webhook_id}", json=webhook_data
158 )
159 resp.raise_for_status()
160 self._modification_state = "UpdateRequested"
161
162 async def update_name(self, webhook_data: WebhookRename) -> None:
163 """Renames the webhook. User does not need to confirm.
164
165 Args:
166 webhook_data (WebhookRename): The new name and location
167 """
168 resp = await self._auth.request(
169 "PATCH", f"systems/{self._system_id}/function-webhooks/{self._webhook_id}/name", json=webhook_data
170 )
171 resp.raise_for_status()
172
173
174 class System:
175 """Class for interacting with a single system."""
176
177 def __init__(self, raw_data: SystemResponse, auth: AbstractAuth):
178 self._system_id = raw_data["systemId"]
179 self._system_name = raw_data["systemName"]
180 self._own_system = raw_data["ownSystem"]
181 self._function_webhook_quotas = raw_data["functionWebhookQuotas"]
182 self._auth = auth
183
184 @property
185 def system_id(self) -> str:
186 return self._system_id
187
188 @property
189 def system_name(self) -> str:
190 return self._system_name
191
192 @property
193 def own_system(self) -> bool:
194 return self._own_system
195
196 @property
197 def function_webhook_quotas(self) -> FunctionQuotas:
198 return self._function_webhook_quotas
199
200 async def get_webhooks(self) -> list[Webhook]:
201 """Getting all the webhooks in the system that were set by this client_id.
202
203 Returns:
204 list[Webhook]: registered Webhooks
205 """
206 resp = await self._auth.request("GET", f"systems/{self._system_id}/function-webhooks")
207 resp.raise_for_status()
208 return [Webhook(wh_data, self._system_id, self._auth) for wh_data in await resp.json()]
209
210 async def get_webhook(self, webhook_id: str) -> Webhook:
211 """Gets the webhook with the provided id.
212
213 Args:
214 webhook_id (str): ID of the webhook
215
216 Returns:
217 Webhook: registerd Webhook
218
219 Raises:
220 aiohttp.ClientResponseError: If `Unauthorized - Authorization failed`
221 or `Forbidden - Invalid or expired authentication token` or `Not Found`
222 """
223 resp = await self._auth.request("GET", f"systems/{self._system_id}/function-webhooks/{webhook_id}")
224 resp.raise_for_status()
225 return Webhook(await resp.json(), self._system_id, self._auth)
226
227 async def add_webhook(self, webhook_data: WebhookData) -> Webhook:
228 """Adds a new webhook with the provided data.
229
230 Args:
231 webhook_data (WebhookData): Data of the Webhook
232
233 Returns:
234 Webhook: registerd webhook
235 """
236 resp = await self._auth.request("POST", f"systems/{self._system_id}/function-webhooks", json=webhook_data)
237 resp.raise_for_status()
238 return Webhook(await resp.json(), self._system_id, self._auth)
239
240
241 class BionyxAPI:
242 """Base class for interacting with the API and get all systems attached to the user."""
243
244 def __init__(self, auth: AbstractAuth) -> None:
245 """Initialize the API with an Auth object.
246
247 Args:
248 auth (AbstractAuth): Auth object that provides the base URL
249 """
250 self._auth = auth
251
252 async def get_systems(self) -> list[System]:
253 """Gets all the Systems attached to the currently logged in user.
254
255 Returns:
256 list[System]: List of Systems the user has access to
257 """
258 resp = await self._auth.request("GET", "systems")
259 resp.raise_for_status()
260 return [System(system_data, self._auth) for system_data in await resp.json()]