| 1 |
"""async_upnp_client.event_handler module.""" |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import logging |
| 5 |
import weakref |
| 6 |
from abc import ABC |
| 7 |
from datetime import timedelta |
| 8 |
from http import HTTPStatus |
| 9 |
from ipaddress import ip_address |
| 10 |
from typing import Callable, Type |
| 11 |
from urllib.parse import urlparse |
| 12 |
|
| 13 |
import defusedxml.ElementTree as DET |
| 14 |
|
| 15 |
from async_upnp_client.client import UpnpDevice, UpnpRequester, UpnpService |
| 16 |
from async_upnp_client.const import NS, HttpRequest, IPvXAddress, ServiceId |
| 17 |
from async_upnp_client.exceptions import ( |
| 18 |
UpnpConnectionError, |
| 19 |
UpnpError, |
| 20 |
UpnpResponseError, |
| 21 |
UpnpSIDError, |
| 22 |
) |
| 23 |
from async_upnp_client.utils import get_local_ip |
| 24 |
|
| 25 |
_LOGGER = logging.getLogger(__name__) |
| 26 |
|
| 27 |
|
| 28 |
def default_on_pre_notify(request: HttpRequest) -> HttpRequest: |
| 29 |
"""Pre-notify hook.""" |
| 30 |
|
| 31 |
fixed_body = (request.body or "").rstrip(" \t\r\n\0") |
| 32 |
return HttpRequest(request.method, request.url, request.headers, fixed_body) |
| 33 |
|
| 34 |
|
| 35 |
class UpnpNotifyServer(ABC): |
| 36 |
""" |
| 37 |
Base Notify Server, which binds to a UpnpEventHandler. |
| 38 |
|
| 39 |
A single UpnpNotifyServer/UpnpEventHandler can be shared with multiple UpnpDevices. |
| 40 |
""" |
| 41 |
|
| 42 |
@property |
| 43 |
def callback_url(self) -> str: |
| 44 |
"""Return callback URL on which we are callable.""" |
| 45 |
raise NotImplementedError() |
| 46 |
|
| 47 |
async def async_start_server(self) -> None: |
| 48 |
"""Start the server.""" |
| 49 |
raise NotImplementedError() |
| 50 |
|
| 51 |
async def async_stop_server(self) -> None: |
| 52 |
"""Stop the server.""" |
| 53 |
raise NotImplementedError() |
| 54 |
|
| 55 |
|
| 56 |
class UpnpEventHandler: |
| 57 |
""" |
| 58 |
Handles UPnP eventing. |
| 59 |
|
| 60 |
An incoming NOTIFY request should be pass to handle_notify(). |
| 61 |
subscribe/resubscribe/unsubscribe handle subscriptions. |
| 62 |
|
| 63 |
When using a reverse proxy in combination with a event handler, you should use |
| 64 |
the option to override the callback url. |
| 65 |
|
| 66 |
A single UpnpNotifyServer/UpnpEventHandler can be shared with multiple UpnpDevices. |
| 67 |
""" |
| 68 |
|
| 69 |
def __init__( |
| 70 |
self, |
| 71 |
notify_server: UpnpNotifyServer, |
| 72 |
requester: UpnpRequester, |
| 73 |
on_pre_notify: Callable[[HttpRequest], HttpRequest] = default_on_pre_notify, |
| 74 |
) -> None: |
| 75 |
""" |
| 76 |
Initialize. |
| 77 |
|
| 78 |
notify_server is the notify server which is actually listening on a socket. |
| 79 |
""" |
| 80 |
self._notify_server = notify_server |
| 81 |
self._requester = requester |
| 82 |
self.on_pre_notify = on_pre_notify |
| 83 |
|
| 84 |
self._subscriptions: weakref.WeakValueDictionary[ServiceId, UpnpService] = weakref.WeakValueDictionary() |
| 85 |
self._backlog: dict[ServiceId, HttpRequest] = {} |
| 86 |
|
| 87 |
@property |
| 88 |
def callback_url(self) -> str: |
| 89 |
"""Return callback URL on which we are callable.""" |
| 90 |
return self._notify_server.callback_url |
| 91 |
|
| 92 |
def sid_for_service(self, service: UpnpService) -> ServiceId | None: |
| 93 |
"""Get the service connected to SID.""" |
| 94 |
for sid, subscribed_service in self._subscriptions.items(): |
| 95 |
if subscribed_service == service: |
| 96 |
return sid |
| 97 |
|
| 98 |
return None |
| 99 |
|
| 100 |
def service_for_sid(self, sid: ServiceId) -> UpnpService | None: |
| 101 |
"""Get a UpnpService for SID.""" |
| 102 |
return self._subscriptions.get(sid) |
| 103 |
|
| 104 |
def _sid_and_service(self, service_or_sid: UpnpService | ServiceId) -> tuple[ServiceId, UpnpService]: |
| 105 |
""" |
| 106 |
Resolve a SID or service to both SID and service. |
| 107 |
|
| 108 |
:raise KeyError: Cannot determine SID from UpnpService, or vice versa. |
| 109 |
""" |
| 110 |
sid: ServiceId | None |
| 111 |
service: UpnpService | None |
| 112 |
|
| 113 |
if isinstance(service_or_sid, UpnpService): |
| 114 |
service = service_or_sid |
| 115 |
sid = self.sid_for_service(service) |
| 116 |
if not sid: |
| 117 |
raise KeyError(f"Unknown UpnpService {service}") |
| 118 |
else: |
| 119 |
sid = service_or_sid |
| 120 |
service = self.service_for_sid(sid) |
| 121 |
if not service: |
| 122 |
raise KeyError(f"Unknown SID {sid}") |
| 123 |
|
| 124 |
return sid, service |
| 125 |
|
| 126 |
async def handle_notify(self, http_request: HttpRequest) -> HTTPStatus: |
| 127 |
"""Handle a NOTIFY request.""" |
| 128 |
http_request = self.on_pre_notify(http_request) |
| 129 |
|
| 130 |
|
| 131 |
if "NT" not in http_request.headers or "NTS" not in http_request.headers: |
| 132 |
return HTTPStatus.BAD_REQUEST |
| 133 |
|
| 134 |
if ( |
| 135 |
http_request.headers["NT"] != "upnp:event" |
| 136 |
or http_request.headers["NTS"] != "upnp:propchange" |
| 137 |
or "SID" not in http_request.headers |
| 138 |
): |
| 139 |
return HTTPStatus.PRECONDITION_FAILED |
| 140 |
|
| 141 |
sid: ServiceId = http_request.headers["SID"] |
| 142 |
service = self.service_for_sid(sid) |
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
if not service: |
| 147 |
_LOGGER.debug("Storing NOTIFY in backlog for SID: %s", sid) |
| 148 |
self._backlog[sid] = http_request |
| 149 |
|
| 150 |
return HTTPStatus.OK |
| 151 |
|
| 152 |
|
| 153 |
changes = {} |
| 154 |
el_root = DET.fromstring(http_request.body) |
| 155 |
for el_property in el_root.findall("./event:property", NS): |
| 156 |
for el_state_var in el_property: |
| 157 |
name = el_state_var.tag |
| 158 |
value = el_state_var.text or "" |
| 159 |
changes[name] = value |
| 160 |
|
| 161 |
|
| 162 |
service.notify_changed_state_variables(changes) |
| 163 |
|
| 164 |
return HTTPStatus.OK |
| 165 |
|
| 166 |
async def async_subscribe( |
| 167 |
self, |
| 168 |
service: UpnpService, |
| 169 |
timeout: timedelta = timedelta(seconds=1800), |
| 170 |
) -> tuple[ServiceId, timedelta]: |
| 171 |
""" |
| 172 |
Subscription to a UpnpService. |
| 173 |
|
| 174 |
Be sure to re-subscribe before the subscription timeout passes. |
| 175 |
|
| 176 |
:param service: UpnpService to subscribe to self |
| 177 |
:param timeout: Timeout of subscription |
| 178 |
:return: SID (subscription ID), renewal timeout (may be different to |
| 179 |
supplied timeout) |
| 180 |
:raise UpnpResponseError: Error in response to subscription request |
| 181 |
:raise UpnpSIDError: No SID received for subscription |
| 182 |
:raise UpnpConnectionError: Device might be offline. |
| 183 |
:raise UpnpCommunicationError (or subclass): Error while performing |
| 184 |
subscription request. |
| 185 |
""" |
| 186 |
_LOGGER.debug("Subscribing to: %s, callback URL: %s", service, self.callback_url) |
| 187 |
|
| 188 |
|
| 189 |
headers = { |
| 190 |
"NT": "upnp:event", |
| 191 |
"TIMEOUT": "Second-" + str(timeout.seconds), |
| 192 |
"HOST": urlparse(service.event_sub_url).netloc, |
| 193 |
"CALLBACK": f"<{self.callback_url}>", |
| 194 |
} |
| 195 |
backlog_request = HttpRequest("SUBSCRIBE", service.event_sub_url, headers, None) |
| 196 |
response = await self._requester.async_http_request(backlog_request) |
| 197 |
|
| 198 |
|
| 199 |
if response.status_code != 200: |
| 200 |
_LOGGER.debug("Did not receive 200, but %s", response.status_code) |
| 201 |
raise UpnpResponseError(status=response.status_code, headers=response.headers) |
| 202 |
|
| 203 |
if "sid" not in response.headers: |
| 204 |
_LOGGER.debug("No SID received, aborting subscribe") |
| 205 |
raise UpnpSIDError |
| 206 |
|
| 207 |
|
| 208 |
if ( |
| 209 |
"timeout" in response.headers |
| 210 |
and response.headers["timeout"] != "Second-infinite" |
| 211 |
and "Second-" in response.headers["timeout"] |
| 212 |
): |
| 213 |
response_timeout = response.headers["timeout"] |
| 214 |
timeout_seconds = int(response_timeout[7:]) |
| 215 |
timeout = timedelta(seconds=timeout_seconds) |
| 216 |
|
| 217 |
sid: ServiceId = response.headers["sid"] |
| 218 |
self._subscriptions[sid] = service |
| 219 |
_LOGGER.debug("Subscribed, service: %s, SID: %s, timeout: %s", service, sid, timeout) |
| 220 |
|
| 221 |
|
| 222 |
if sid in self._backlog: |
| 223 |
_LOGGER.debug("Re-playing backlogged NOTIFY for SID: %s", sid) |
| 224 |
backlog_request = self._backlog[sid] |
| 225 |
await self.handle_notify(backlog_request) |
| 226 |
del self._backlog[sid] |
| 227 |
|
| 228 |
return sid, timeout |
| 229 |
|
| 230 |
async def _async_do_resubscribe( |
| 231 |
self, |
| 232 |
service: UpnpService, |
| 233 |
sid: ServiceId, |
| 234 |
timeout: timedelta = timedelta(seconds=1800), |
| 235 |
) -> tuple[ServiceId, timedelta]: |
| 236 |
"""Perform only a resubscribe, caller can retry subscribe if this fails.""" |
| 237 |
|
| 238 |
headers = { |
| 239 |
"HOST": urlparse(service.event_sub_url).netloc, |
| 240 |
"SID": sid, |
| 241 |
"TIMEOUT": "Second-" + str(timeout.total_seconds()), |
| 242 |
} |
| 243 |
request = HttpRequest("SUBSCRIBE", service.event_sub_url, headers, None) |
| 244 |
response = await self._requester.async_http_request(request) |
| 245 |
|
| 246 |
|
| 247 |
if response.status_code != 200: |
| 248 |
_LOGGER.debug("Did not receive 200, but %s", response.status_code) |
| 249 |
raise UpnpResponseError(status=response.status_code, headers=response.headers) |
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
if "sid" in response.headers and response.headers["sid"]: |
| 254 |
new_sid: ServiceId = response.headers["sid"] |
| 255 |
if new_sid != sid: |
| 256 |
del self._subscriptions[sid] |
| 257 |
sid = new_sid |
| 258 |
|
| 259 |
|
| 260 |
if ( |
| 261 |
"timeout" in response.headers |
| 262 |
and response.headers["timeout"] != "Second-infinite" |
| 263 |
and "Second-" in response.headers["timeout"] |
| 264 |
): |
| 265 |
response_timeout = response.headers["timeout"] |
| 266 |
timeout_seconds = int(response_timeout[7:]) |
| 267 |
timeout = timedelta(seconds=timeout_seconds) |
| 268 |
|
| 269 |
self._subscriptions[sid] = service |
| 270 |
_LOGGER.debug("Resubscribed, service: %s, SID: %s, timeout: %s", service, sid, timeout) |
| 271 |
|
| 272 |
return sid, timeout |
| 273 |
|
| 274 |
async def async_resubscribe( |
| 275 |
self, |
| 276 |
service_or_sid: UpnpService | ServiceId, |
| 277 |
timeout: timedelta = timedelta(seconds=1800), |
| 278 |
) -> tuple[ServiceId, timedelta]: |
| 279 |
""" |
| 280 |
Renew subscription to a UpnpService. |
| 281 |
|
| 282 |
:param service_or_sid: UpnpService or existing SID to resubscribe |
| 283 |
:param timeout: Timeout of subscription |
| 284 |
:return: SID (subscription ID), renewal timeout (may be different to |
| 285 |
supplied timeout) |
| 286 |
:raise KeyError: Supplied service_or_sid is not known. |
| 287 |
:raise UpnpResponseError: Error in response to subscription request |
| 288 |
:raise UpnpSIDError: No SID received for subscription |
| 289 |
:raise UpnpConnectionError: Device might be offline. |
| 290 |
:raise UpnpCommunicationError (or subclass): Error while performing |
| 291 |
subscription request. |
| 292 |
""" |
| 293 |
_LOGGER.debug("Resubscribing to: %s", service_or_sid) |
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
sid, service = self._sid_and_service(service_or_sid) |
| 299 |
try: |
| 300 |
return await self._async_do_resubscribe(service, sid, timeout) |
| 301 |
except UpnpConnectionError as err: |
| 302 |
_LOGGER.debug( |
| 303 |
"Resubscribe for %s failed: %s. Device offline, not retrying.", |
| 304 |
service_or_sid, |
| 305 |
err, |
| 306 |
) |
| 307 |
del self._subscriptions[sid] |
| 308 |
raise |
| 309 |
except UpnpError as err: |
| 310 |
_LOGGER.debug( |
| 311 |
"Resubscribe for %s failed: %s. Trying full subscribe.", |
| 312 |
service_or_sid, |
| 313 |
err, |
| 314 |
) |
| 315 |
del self._subscriptions[sid] |
| 316 |
return await self.async_subscribe(service, timeout) |
| 317 |
|
| 318 |
async def async_resubscribe_all(self) -> None: |
| 319 |
"""Renew all current subscription.""" |
| 320 |
await asyncio.gather(*(self.async_resubscribe(sid) for sid in self._subscriptions)) |
| 321 |
|
| 322 |
async def async_unsubscribe( |
| 323 |
self, |
| 324 |
service_or_sid: UpnpService | ServiceId, |
| 325 |
) -> ServiceId: |
| 326 |
"""Unsubscribe from a UpnpService.""" |
| 327 |
sid, service = self._sid_and_service(service_or_sid) |
| 328 |
|
| 329 |
_LOGGER.debug( |
| 330 |
"Unsubscribing from SID: %s, service: %s device: %s", |
| 331 |
sid, |
| 332 |
service, |
| 333 |
service.device, |
| 334 |
) |
| 335 |
|
| 336 |
|
| 337 |
del self._subscriptions[sid] |
| 338 |
|
| 339 |
|
| 340 |
headers = { |
| 341 |
"HOST": urlparse(service.event_sub_url).netloc, |
| 342 |
"SID": sid, |
| 343 |
} |
| 344 |
request = HttpRequest("UNSUBSCRIBE", service.event_sub_url, headers, None) |
| 345 |
response = await self._requester.async_http_request(request) |
| 346 |
|
| 347 |
|
| 348 |
if response.status_code != 200: |
| 349 |
_LOGGER.debug("Did not receive 200, but %s", response.status_code) |
| 350 |
raise UpnpResponseError(status=response.status_code, headers=response.headers) |
| 351 |
|
| 352 |
return sid |
| 353 |
|
| 354 |
async def async_unsubscribe_all(self) -> None: |
| 355 |
"""Unsubscribe all subscriptions.""" |
| 356 |
sids = list(self._subscriptions) |
| 357 |
await asyncio.gather( |
| 358 |
*(self.async_unsubscribe(sid) for sid in sids), |
| 359 |
return_exceptions=True, |
| 360 |
) |
| 361 |
|
| 362 |
async def async_stop(self) -> None: |
| 363 |
"""Stop event the UpnpNotifyServer.""" |
| 364 |
|
| 365 |
await self._notify_server.async_stop_server() |
| 366 |
|
| 367 |
|
| 368 |
class UpnpEventHandlerRegister: |
| 369 |
"""Event handler register to handle multiple interfaces.""" |
| 370 |
|
| 371 |
def __init__(self, requester: UpnpRequester, notify_server_type: Type) -> None: |
| 372 |
"""Initialize.""" |
| 373 |
self.requester = requester |
| 374 |
self.notify_server_type = notify_server_type |
| 375 |
self._event_handlers: dict[IPvXAddress, tuple[UpnpEventHandler, set[UpnpDevice]]] = {} |
| 376 |
|
| 377 |
def _get_event_handler_for_device(self, device: UpnpDevice) -> UpnpEventHandler | None: |
| 378 |
"""Get the event handler for the device, if known.""" |
| 379 |
local_ip_str = get_local_ip(device.device_url) |
| 380 |
local_ip = ip_address(local_ip_str) |
| 381 |
if local_ip not in self._event_handlers: |
| 382 |
return None |
| 383 |
|
| 384 |
event_handler, devices = self._event_handlers[local_ip] |
| 385 |
if device in devices: |
| 386 |
return event_handler |
| 387 |
|
| 388 |
return None |
| 389 |
|
| 390 |
def has_event_handler_for_device(self, device: UpnpDevice) -> bool: |
| 391 |
"""Check if an event handler for a device is already available.""" |
| 392 |
return self._get_event_handler_for_device(device) is not None |
| 393 |
|
| 394 |
async def async_add_device(self, device: UpnpDevice) -> UpnpEventHandler: |
| 395 |
"""Add a new device, creates or gets the event handler for this device.""" |
| 396 |
local_ip_str = get_local_ip(device.device_url) |
| 397 |
local_ip = ip_address(local_ip_str) |
| 398 |
if local_ip not in self._event_handlers: |
| 399 |
event_handler = await self._create_event_handler_for_device(device) |
| 400 |
self._event_handlers[local_ip] = (event_handler, set([device])) |
| 401 |
return event_handler |
| 402 |
|
| 403 |
event_handler, devices = self._event_handlers[local_ip] |
| 404 |
devices.add(device) |
| 405 |
|
| 406 |
return event_handler |
| 407 |
|
| 408 |
async def _create_event_handler_for_device(self, device: UpnpDevice) -> UpnpEventHandler: |
| 409 |
"""Create a new event handler for a device.""" |
| 410 |
local_ip_str = get_local_ip(device.device_url) |
| 411 |
source_addr = (local_ip_str, 0) |
| 412 |
notify_server: UpnpNotifyServer = self.notify_server_type(requester=self.requester, source=source_addr) |
| 413 |
await notify_server.async_start_server() |
| 414 |
return UpnpEventHandler(notify_server, self.requester) |
| 415 |
|
| 416 |
async def async_remove_device(self, device: UpnpDevice) -> UpnpEventHandler | None: |
| 417 |
"""Remove an existing device, destroys the event handler and returns it, if needed.""" |
| 418 |
local_ip_str = get_local_ip(device.device_url) |
| 419 |
local_ip = ip_address(local_ip_str) |
| 420 |
assert local_ip in self._event_handlers |
| 421 |
|
| 422 |
event_handler, devices = self._event_handlers[local_ip] |
| 423 |
assert device in devices |
| 424 |
devices.remove(device) |
| 425 |
|
| 426 |
if not devices: |
| 427 |
await event_handler.async_stop() |
| 428 |
del self._event_handlers[local_ip] |
| 429 |
return event_handler |
| 430 |
|
| 431 |
return None |