Skip to content

Commit

Permalink
Fix deprecations and warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
Xyaren committed Feb 21, 2025
1 parent 846b826 commit 01ff22e
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 53 deletions.
1 change: 1 addition & 0 deletions custom_components/magentatv/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
For more details about this integration, please refer to
https://github.com/xyaren/magentatv
"""

from __future__ import annotations

from asyncio import Lock
Expand Down
8 changes: 4 additions & 4 deletions custom_components/magentatv/api/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
PairingTimeoutException,
)
from .notify_server import NotifyServer
from .utils import magneta_hash
from .utils import magenta_hash

PAIRING_EVENT_TIMEOUT = 5
PAIRING_ATTEMPTS = 3
Expand All @@ -44,9 +44,9 @@ def __init__(

self._notify_server = notify_server

self._terminal_id = magneta_hash(instance_id)
self._terminal_id = magenta_hash(instance_id)

self._user_id = magneta_hash(user_id)
self._user_id = magenta_hash(user_id)
self._requester = AiohttpRequester(http_headers={"User-Agent": "Homeassistant MagentaTV Integration"})

self._verification_code = None
Expand Down Expand Up @@ -76,7 +76,7 @@ async def _on_event(self, changes):
body = changes.get("messageBody")
if "X-pairingCheck:" in body:
pairing_code = changes.get("messageBody").removeprefix("X-pairingCheck:")
self._verification_code = magneta_hash(pairing_code + self._terminal_id + self._user_id)
self._verification_code = magenta_hash(pairing_code + self._terminal_id + self._user_id)
self._pairing_event.set()

async def _register_for_events(self):
Expand Down
83 changes: 47 additions & 36 deletions custom_components/magentatv/api/notify_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ async def _async_subscribe_to_service(self, target, service: str, callback: Call
self._subscription_registry[sid] = (target, service, callback)

for changes in self._buffer.pop(sid, []):
callback(changes)
await callback(changes)

return sid

Expand Down Expand Up @@ -136,54 +136,65 @@ async def _async_subscribe(self, target, service) -> str:
if adv_port is None:
adv_port = self._listen_ip_port[1]

response = await self._requester.async_http_request(
http_request=HttpRequest(
method="SUBSCRIBE",
url=url,
headers={
"NT": "upnp:event",
"TIMEOUT": f"Second-{self._subscription_timeout}",
"HOST": f"{target[0]}:{target[1]}",
"CALLBACK": f"<http://{adv_host}:{adv_port}/eventSub>",
},
body=None,
try:
response = await self._requester.async_http_request(
http_request=HttpRequest(
method="SUBSCRIBE",
url=url,
headers={
"NT": "upnp:event",
"TIMEOUT": f"Second-{self._subscription_timeout}",
"HOST": f"{target[0]}:{target[1]}",
"CALLBACK": f"<http://{adv_host}:{adv_port}/eventSub>",
},
body=None,
)
)
)
except UpnpConnectionTimeoutError as ex:
LOGGER.error("Failed to subscribe %s on %s at %s", service, target, url, exc_info=ex)
raise ex
assert response.status_code == 200
sid = response.headers["SID"]
LOGGER.debug("Subscribed %s on %s at %s", sid, service, target)
return sid

@wrap_exceptions
async def _async_resubscribe(self, target, service, sid) -> str:
response = await self._requester.async_http_request(
http_request=HttpRequest(
method="SUBSCRIBE",
url=f"http://{target[0]}:{target[1]}/upnp/service/{service}/Event",
headers={
"SID": sid,
"TIMEOUT": f"Second-{self._subscription_timeout}",
},
body=None,
try:
response = await self._requester.async_http_request(
http_request=HttpRequest(
method="SUBSCRIBE",
url=f"http://{target[0]}:{target[1]}/upnp/service/{service}/Event",
headers={
"SID": sid,
"TIMEOUT": f"Second-{self._subscription_timeout}",
},
body=None,
)
)
)
assert response.status_code == 200
return response.headers["SID"]
assert response.status_code == 200
return response.headers["SID"]
except UpnpConnectionTimeoutError as ex:
LOGGER.error("Failed to resubscribe %s on %s at %s", sid, service, target, exc_info=ex)
raise ex

@wrap_exceptions
async def _async_unsubscribe(self, target, service, sid) -> str:
response = await self._requester.async_http_request(
http_request=HttpRequest(
method="UNSUBSCRIBE",
url=f"http://{target[0]}:{target[1]}/upnp/service/{service}/Event",
headers={
"SID": sid,
},
body=None,
try:
response = await self._requester.async_http_request(
http_request=HttpRequest(
method="UNSUBSCRIBE",
url=f"http://{target[0]}:{target[1]}/upnp/service/{service}/Event",
headers={
"SID": sid,
},
body=None,
)
)
)
assert response.status_code in [200, 412]
LOGGER.debug("Unsubscribed %s on %s at %s", sid, service, target)
assert response.status_code in [200, 412]
LOGGER.debug("Unsubscribed %s on %s at %s", sid, service, target)
except UpnpConnectionTimeoutError as ex:
LOGGER.warning("Failed to unsubscribe %s on %s at %s", sid, service, target, exc_info=ex)

async def _async_has_subscriptions(self) -> bool:
async with self.subscription_lock:
Expand Down
2 changes: 1 addition & 1 deletion custom_components/magentatv/api/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import hashlib


def magneta_hash(data: str) -> str:
def magenta_hash(data: str) -> str:
return hashlib.md5(data.encode("UTF-8")).hexdigest().upper()
28 changes: 18 additions & 10 deletions custom_components/magentatv/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import instance_id
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.service_info.ssdp import (
ATTR_UPNP_FRIENDLY_NAME,
ATTR_UPNP_MANUFACTURER,
ATTR_UPNP_MODEL_NAME,
ATTR_UPNP_MODEL_NUMBER,
ATTR_UPNP_UDN,
SsdpServiceInfo,
)

from custom_components.magentatv import async_get_notification_server
from custom_components.magentatv.api.exceptions import PairingTimeoutException
Expand Down Expand Up @@ -70,7 +78,7 @@ class MagentaTvFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):

def __init__(self) -> None:
"""Initialize the flow."""
self._discoveries: dict[str, ssdp.SsdpServiceInfo] = {}
self._discoveries: dict[str, SsdpServiceInfo] = {}

self.friendly_name: str | None = None
self.model_name: str | None = None
Expand Down Expand Up @@ -111,7 +119,7 @@ async def async_step_user(self, user_input: FlowInput = None) -> FlowResult:
return await self.async_step_manual()

self._discoveries = {
discovery.upnp.get(ssdp.ATTR_UPNP_FRIENDLY_NAME)
discovery.upnp.get(ATTR_UPNP_FRIENDLY_NAME)
or cast(str, urlparse(discovery.ssdp_location).hostname): discovery
for discovery in discoveries
}
Expand All @@ -120,7 +128,7 @@ async def async_step_user(self, user_input: FlowInput = None) -> FlowResult:

return self.async_show_form(step_id="user", data_schema=data_schema, last_step=False)

async def _async_get_discoveries(self) -> list[ssdp.SsdpServiceInfo]:
async def _async_get_discoveries(self) -> list[SsdpServiceInfo]:
"""Get list of unconfigured DLNA devices discovered by SSDP."""

# Get all compatible devices from ssdp's cache
Expand Down Expand Up @@ -206,11 +214,11 @@ async def async_step_unignore(self, user_input: Mapping[str, Any]) -> FlowResult
return self.async_abort(reason="discovery_error")

def _set_from_upnp(self, device_info: Mapping[str, Any]):
self._udn = device_info.get(ssdp.ATTR_UPNP_UDN)
self.friendly_name = device_info.get(ssdp.ATTR_UPNP_FRIENDLY_NAME)
self.model_name = device_info.get(ssdp.ATTR_UPNP_MODEL_NAME)
self.model_number = device_info.get(ssdp.ATTR_UPNP_MODEL_NUMBER)
self.manufacturer = device_info.get(ssdp.ATTR_UPNP_MANUFACTURER)
self._udn = device_info.get(ATTR_UPNP_UDN)
self.friendly_name = device_info.get(ATTR_UPNP_FRIENDLY_NAME)
self.model_name = device_info.get(ATTR_UPNP_MODEL_NAME)
self.model_number = device_info.get(ATTR_UPNP_MODEL_NUMBER)
self.manufacturer = device_info.get(ATTR_UPNP_MANUFACTURER)

assert self._udn is not None
assert self.friendly_name is not None
Expand All @@ -220,7 +228,7 @@ def _set_from_upnp(self, device_info: Mapping[str, Any]):

async def _async_set_info_from_discovery(
self,
discovery_info: ssdp.SsdpServiceInfo,
discovery_info: SsdpServiceInfo,
raise_on_progress: bool = True,
abort_if_configured: bool = True,
) -> None:
Expand Down Expand Up @@ -256,7 +264,7 @@ async def _async_set_info_from_discovery(

return await self.async_step_enter_user_id()

async def async_step_ssdp(self, discovery_info: ssdp.SsdpServiceInfo) -> FlowResult:
async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult:
"""Handle ssdp discovery flow."""

LOGGER.debug("async_step_ssdp %s", discovery_info)
Expand Down
4 changes: 2 additions & 2 deletions tests/api/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from custom_components.magentatv.api.utils import magneta_hash
from custom_components.magentatv.api.utils import magenta_hash


def test_hash_function():
assert magneta_hash("Test") == "0CBC6611F5540BD0809A388DC95A615B"
assert magenta_hash("Test") == "0CBC6611F5540BD0809A388DC95A615B"

0 comments on commit 01ff22e

Please sign in to comment.