| 1 |
"""async_upnp_client.profiles.dlna module.""" |
| 2 |
|
| 3 |
# pylint: disable=too-many-lines |
| 4 |
|
| 5 |
import asyncio |
| 6 |
import logging |
| 7 |
from datetime import datetime, timedelta |
| 8 |
from enum import Enum, IntEnum, IntFlag |
| 9 |
from functools import lru_cache |
| 10 |
from http import HTTPStatus |
| 11 |
from mimetypes import guess_type |
| 12 |
from time import monotonic as monotonic_timer |
| 13 |
from typing import Any, Iterable, Mapping, MutableMapping, NamedTuple, Sequence |
| 14 |
from xml.etree.ElementTree import ParseError |
| 15 |
from xml.sax.handler import ContentHandler, ErrorHandler |
| 16 |
from xml.sax.xmlreader import AttributesImpl |
| 17 |
|
| 18 |
from defusedxml.common import DefusedXmlException |
| 19 |
from defusedxml.sax import parseString |
| 20 |
from didl_lite import didl_lite |
| 21 |
|
| 22 |
from async_upnp_client.client import UpnpService, UpnpStateVariable |
| 23 |
from async_upnp_client.const import MIME_TO_UPNP_CLASS_MAPPING, HttpRequest |
| 24 |
from async_upnp_client.exceptions import UpnpError |
| 25 |
from async_upnp_client.profiles.profile import UpnpProfileDevice |
| 26 |
from async_upnp_client.utils import absolute_url, str_to_time, time_to_str |
| 27 |
|
| 28 |
_LOGGER = logging.getLogger(__name__) |
| 29 |
|
| 30 |
|
| 31 |
DeviceState = Enum("DeviceState", "ON PLAYING PAUSED IDLE") |
| 32 |
|
| 33 |
|
| 34 |
class TransportState(str, Enum): |
| 35 |
"""Allowed values for DLNA AV Transport TransportState variable.""" |
| 36 |
|
| 37 |
STOPPED = "STOPPED" |
| 38 |
PLAYING = "PLAYING" |
| 39 |
TRANSITIONING = "TRANSITIONING" |
| 40 |
PAUSED_PLAYBACK = "PAUSED_PLAYBACK" |
| 41 |
PAUSED_RECORDING = "PAUSED_RECORDING" |
| 42 |
RECORDING = "RECORDING" |
| 43 |
NO_MEDIA_PRESENT = "NO_MEDIA_PRESENT" |
| 44 |
VENDOR_DEFINED = "VENDOR_DEFINED" |
| 45 |
|
| 46 |
|
| 47 |
class PlayMode(str, Enum): |
| 48 |
"""Allowed values for DLNA AV Transport CurrentPlayMode variable.""" |
| 49 |
|
| 50 |
NORMAL = "NORMAL" |
| 51 |
SHUFFLE = "SHUFFLE" |
| 52 |
REPEAT_ONE = "REPEAT_ONE" |
| 53 |
REPEAT_ALL = "REPEAT_ALL" |
| 54 |
RANDOM = "RANDOM" |
| 55 |
DIRECT_1 = "DIRECT_1" |
| 56 |
INTRO = "INTRO" |
| 57 |
VENDOR_DEFINED = "VENDOR_DEFINED" |
| 58 |
|
| 59 |
|
| 60 |
class DlnaOrgOp(Enum): |
| 61 |
"""DLNA.ORG_OP (Operations Parameter) flags.""" |
| 62 |
|
| 63 |
NONE = 0 |
| 64 |
RANGE = 0x01 |
| 65 |
TIMESEEK = 0x10 |
| 66 |
|
| 67 |
|
| 68 |
class DlnaOrgCi(Enum): |
| 69 |
"""DLNA.ORG_CI (Conversion Indicator) flags.""" |
| 70 |
|
| 71 |
NONE = 0 |
| 72 |
TRANSCODED = 1 |
| 73 |
|
| 74 |
|
| 75 |
class DlnaOrgPs(Enum): |
| 76 |
"""DLNA.ORG_PS (PlaySpeed) flags.""" |
| 77 |
|
| 78 |
INVALID = 0 |
| 79 |
NORMAL = 1 |
| 80 |
|
| 81 |
|
| 82 |
class DlnaOrgFlags(IntFlag): |
| 83 |
""" |
| 84 |
DLNA.ORG_FLAGS flags. |
| 85 |
|
| 86 |
padded with 24 trailing 0s |
| 87 |
80000000 31 sender paced |
| 88 |
40000000 30 lsop time based seek supported |
| 89 |
20000000 29 lsop byte based seek supported |
| 90 |
10000000 28 playcontainer supported |
| 91 |
8000000 27 s0 increasing supported |
| 92 |
4000000 26 sN increasing supported |
| 93 |
2000000 25 rtsp pause supported |
| 94 |
1000000 24 streaming transfer mode supported |
| 95 |
800000 23 interactive transfer mode supported |
| 96 |
400000 22 background transfer mode supported |
| 97 |
200000 21 connection stalling supported |
| 98 |
100000 20 dlna version15 supported |
| 99 |
""" |
| 100 |
|
| 101 |
SENDER_PACED = 1 << 31 |
| 102 |
TIME_BASED_SEEK = 1 << 30 |
| 103 |
BYTE_BASED_SEEK = 1 << 29 |
| 104 |
PLAY_CONTAINER = 1 << 28 |
| 105 |
S0_INCREASE = 1 << 27 |
| 106 |
SN_INCREASE = 1 << 26 |
| 107 |
RTSP_PAUSE = 1 << 25 |
| 108 |
STREAMING_TRANSFER_MODE = 1 << 24 |
| 109 |
INTERACTIVE_TRANSFERT_MODE = 1 << 23 |
| 110 |
BACKGROUND_TRANSFERT_MODE = 1 << 22 |
| 111 |
CONNECTION_STALL = 1 << 21 |
| 112 |
DLNA_V15 = 1 << 20 |
| 113 |
|
| 114 |
|
| 115 |
class DlnaDmrEventContentHandler(ContentHandler): |
| 116 |
"""Content Handler to parse DLNA DMR Event data.""" |
| 117 |
|
| 118 |
def __init__(self) -> None: |
| 119 |
"""Initialize.""" |
| 120 |
super().__init__() |
| 121 |
self.changes: MutableMapping[str, MutableMapping[str, Any]] = {} |
| 122 |
self._current_instance: str | None = None |
| 123 |
|
| 124 |
def startElement(self, name: str, attrs: AttributesImpl) -> None: |
| 125 |
"""Handle startElement.""" |
| 126 |
if "val" not in attrs: |
| 127 |
return |
| 128 |
|
| 129 |
if name == "InstanceID": |
| 130 |
self._current_instance = attrs.get("val", "0") |
| 131 |
else: |
| 132 |
current_instance = self._current_instance or "0" # safety |
| 133 |
|
| 134 |
if current_instance not in self.changes: |
| 135 |
self.changes[current_instance] = {} |
| 136 |
|
| 137 |
# If channel is given, we're only interested in the Master channel. |
| 138 |
if attrs.get("channel") not in (None, "Master"): |
| 139 |
return |
| 140 |
|
| 141 |
# Strip namespace prefix. |
| 142 |
if ":" in name: |
| 143 |
index = name.find(":") + 1 |
| 144 |
name = name[index:] |
| 145 |
|
| 146 |
self.changes[current_instance][name] = attrs.get("val") |
| 147 |
|
| 148 |
def endElement(self, name: str) -> None: |
| 149 |
"""Handle endElement.""" |
| 150 |
if name == "InstanceID": |
| 151 |
self._current_instance = None |
| 152 |
|
| 153 |
|
| 154 |
class DlnaDmrEventErrorHandler(ErrorHandler): |
| 155 |
"""Error handler which ignores errors.""" |
| 156 |
|
| 157 |
def error(self, exception: BaseException) -> None: # type: ignore |
| 158 |
"""Handle error.""" |
| 159 |
_LOGGER.debug("Error during parsing: %s", exception) |
| 160 |
|
| 161 |
def fatalError(self, exception: BaseException) -> None: # type: ignore |
| 162 |
"""Handle error.""" |
| 163 |
_LOGGER.debug("Fatal error during parsing: %s", exception) |
| 164 |
|
| 165 |
|
| 166 |
def _parse_last_change_event(text: str) -> Mapping[str, Mapping[str, str]]: |
| 167 |
""" |
| 168 |
Parse a LastChange event. |
| 169 |
|
| 170 |
:param text Text to parse. |
| 171 |
|
| 172 |
:return Dict per Instance, containing changed state variables with values. |
| 173 |
""" |
| 174 |
content_handler = DlnaDmrEventContentHandler() |
| 175 |
error_handler = DlnaDmrEventErrorHandler() |
| 176 |
parseString(text.encode(), content_handler, error_handler) |
| 177 |
return content_handler.changes |
| 178 |
|
| 179 |
|
| 180 |
def dlna_handle_notify_last_change(state_var: UpnpStateVariable) -> None: |
| 181 |
""" |
| 182 |
Handle changes to LastChange state variable. |
| 183 |
|
| 184 |
This expands all changed state variables in the LastChange state variable. |
| 185 |
Note that the callback is called twice: |
| 186 |
- for the original event; |
| 187 |
- for the expanded event, via this function. |
| 188 |
""" |
| 189 |
if state_var.name != "LastChange": |
| 190 |
raise UpnpError("Call this only on state variable LastChange") |
| 191 |
|
| 192 |
event_data: str | None = state_var.value |
| 193 |
if not event_data: |
| 194 |
_LOGGER.debug("No event data on state_variable") |
| 195 |
return |
| 196 |
|
| 197 |
changes = _parse_last_change_event(event_data) |
| 198 |
if "0" not in changes: |
| 199 |
_LOGGER.warning("Only InstanceID 0 is supported") |
| 200 |
return |
| 201 |
|
| 202 |
service = state_var.service |
| 203 |
changes_0 = changes["0"] |
| 204 |
service.notify_changed_state_variables(changes_0) |
| 205 |
|
| 206 |
|
| 207 |
@lru_cache(maxsize=128) |
| 208 |
def split_commas(input_: str) -> list[str]: |
| 209 |
""" |
| 210 |
Split a string into a list of comma separated values. |
| 211 |
|
| 212 |
Strip whitespace and omit the empty string. |
| 213 |
""" |
| 214 |
stripped = (item.strip() for item in input_.split(",")) |
| 215 |
return [item for item in stripped if item] |
| 216 |
|
| 217 |
|
| 218 |
@lru_cache(maxsize=128) |
| 219 |
def _lower_split_commas(input_: str) -> set[str]: |
| 220 |
"""Lowercase version of split_commas.""" |
| 221 |
return {a.lower() for a in split_commas(input_)} |
| 222 |
|
| 223 |
|
| 224 |
@lru_cache |
| 225 |
def _cached_from_xml_string( |
| 226 |
xml: str, |
| 227 |
) -> list[didl_lite.DidlObject | didl_lite.Descriptor]: |
| 228 |
try: |
| 229 |
return didl_lite.from_xml_string(xml, strict=False) |
| 230 |
except (ParseError, DefusedXmlException): |
| 231 |
# Invalid XML and XML rejected by the secure parser are unusable metadata. |
| 232 |
_LOGGER.debug("Unable to parse DIDL-Lite metadata") |
| 233 |
return [] |
| 234 |
|
| 235 |
|
| 236 |
class ConnectionManagerMixin(UpnpProfileDevice): |
| 237 |
"""Mix-in to support ConnectionManager actions and state variables.""" |
| 238 |
|
| 239 |
_SERVICE_TYPES = { |
| 240 |
"CM": { |
| 241 |
"urn:schemas-upnp-org:service:ConnectionManager:3", |
| 242 |
"urn:schemas-upnp-org:service:ConnectionManager:2", |
| 243 |
"urn:schemas-upnp-org:service:ConnectionManager:1", |
| 244 |
}, |
| 245 |
} |
| 246 |
|
| 247 |
__did_first_update: bool = False |
| 248 |
|
| 249 |
async def async_update(self) -> None: |
| 250 |
"""Retrieve latest data.""" |
| 251 |
if not self.__did_first_update: |
| 252 |
await self._async_poll_state_variables("CM", "GetProtocolInfo") |
| 253 |
self.__did_first_update = True |
| 254 |
|
| 255 |
# region CM |
| 256 |
@property |
| 257 |
def has_get_protocol_info(self) -> bool: |
| 258 |
"""Check if device can report its protocol info.""" |
| 259 |
return self._action("CM", "GetProtocolInfo") is not None |
| 260 |
|
| 261 |
async def async_get_protocol_info(self) -> Mapping[str, list[str]]: |
| 262 |
"""Get protocol info.""" |
| 263 |
action = self._action("CM", "GetProtocolInfo") |
| 264 |
if not action: |
| 265 |
return {"source": [], "sink": []} |
| 266 |
|
| 267 |
protocol_info = await action.async_call() |
| 268 |
return { |
| 269 |
"source": split_commas(protocol_info["Source"]), |
| 270 |
"sink": split_commas(protocol_info["Sink"]), |
| 271 |
} |
| 272 |
|
| 273 |
@property |
| 274 |
def source_protocol_info(self) -> list[str]: |
| 275 |
"""Supported source protocols.""" |
| 276 |
state_var = self._state_variable("CM", "SourceProtocolInfo") |
| 277 |
if state_var is None or not state_var.value: |
| 278 |
return [] |
| 279 |
|
| 280 |
return split_commas(state_var.value) |
| 281 |
|
| 282 |
@property |
| 283 |
def sink_protocol_info(self) -> list[str]: |
| 284 |
"""Supported sink protocols.""" |
| 285 |
state_var = self._state_variable("CM", "SinkProtocolInfo") |
| 286 |
if state_var is None or not state_var.value: |
| 287 |
return [] |
| 288 |
|
| 289 |
return split_commas(state_var.value) |
| 290 |
|
| 291 |
# endregion |
| 292 |
|
| 293 |
|
| 294 |
class DmrDevice(ConnectionManagerMixin, UpnpProfileDevice): |
| 295 |
"""Representation of a DLNA DMR device.""" |
| 296 |
|
| 297 |
# pylint: disable=too-many-public-methods |
| 298 |
|
| 299 |
DEVICE_TYPES = [ |
| 300 |
"urn:schemas-upnp-org:device:MediaRenderer:1", |
| 301 |
"urn:schemas-upnp-org:device:MediaRenderer:2", |
| 302 |
"urn:schemas-upnp-org:device:MediaRenderer:3", |
| 303 |
] |
| 304 |
|
| 305 |
SERVICE_IDS = frozenset( |
| 306 |
( |
| 307 |
"urn:upnp-org:serviceId:AVTransport", |
| 308 |
"urn:upnp-org:serviceId:ConnectionManager", |
| 309 |
"urn:upnp-org:serviceId:RenderingControl", |
| 310 |
) |
| 311 |
) |
| 312 |
|
| 313 |
_SERVICE_TYPES = { |
| 314 |
"RC": { |
| 315 |
"urn:schemas-upnp-org:service:RenderingControl:3", |
| 316 |
"urn:schemas-upnp-org:service:RenderingControl:2", |
| 317 |
"urn:schemas-upnp-org:service:RenderingControl:1", |
| 318 |
}, |
| 319 |
"AVT": { |
| 320 |
"urn:schemas-upnp-org:service:AVTransport:3", |
| 321 |
"urn:schemas-upnp-org:service:AVTransport:2", |
| 322 |
"urn:schemas-upnp-org:service:AVTransport:1", |
| 323 |
}, |
| 324 |
**ConnectionManagerMixin._SERVICE_TYPES, |
| 325 |
} |
| 326 |
|
| 327 |
_current_track_meta_data: didl_lite.DidlObject | None = None |
| 328 |
_av_transport_uri_meta_data: didl_lite.DidlObject | None = None |
| 329 |
__did_first_update: bool = False |
| 330 |
|
| 331 |
async def async_update(self, do_ping: bool = True) -> None: |
| 332 |
"""Retrieve the latest data. |
| 333 |
|
| 334 |
:param do_ping: Poll device to check if it is available (online). |
| 335 |
""" |
| 336 |
# pylint: disable=arguments-differ |
| 337 |
await super().async_update() |
| 338 |
|
| 339 |
# call GetTransportInfo/GetPositionInfo regularly |
| 340 |
avt_service = self._service("AVT") |
| 341 |
if avt_service: |
| 342 |
if not self.is_subscribed or do_ping: |
| 343 |
# CurrentTransportState is evented, so don't need to poll when subscribed |
| 344 |
await self._async_poll_state_variables("AVT", "GetTransportInfo", InstanceID=0) |
| 345 |
|
| 346 |
if self.transport_state in ( |
| 347 |
TransportState.PLAYING, |
| 348 |
TransportState.PAUSED_PLAYBACK, |
| 349 |
): |
| 350 |
# playing something, get position info |
| 351 |
# RelativeTimePosition is *never* evented, must always poll |
| 352 |
await self._async_poll_state_variables("AVT", "GetPositionInfo", InstanceID=0) |
| 353 |
if not self.is_subscribed or not self.__did_first_update: |
| 354 |
# Events won't be sent, so poll all state variables |
| 355 |
await self._async_poll_state_variables( |
| 356 |
"AVT", |
| 357 |
[ |
| 358 |
"GetMediaInfo", |
| 359 |
"GetDeviceCapabilities", |
| 360 |
"GetTransportSettings", |
| 361 |
"GetCurrentTransportActions", |
| 362 |
], |
| 363 |
InstanceID=0, |
| 364 |
) |
| 365 |
await self._async_poll_state_variables("RC", ["GetMute", "GetVolume"], InstanceID=0, Channel="Master") |
| 366 |
self.__did_first_update = True |
| 367 |
elif do_ping: |
| 368 |
await self.profile_device.async_ping() |
| 369 |
|
| 370 |
def _on_event(self, service: UpnpService, state_variables: Sequence[UpnpStateVariable]) -> None: |
| 371 |
"""State variable(s) changed, perform callback(s).""" |
| 372 |
# handle DLNA specific event |
| 373 |
for state_variable in state_variables: |
| 374 |
if state_variable.name == "LastChange": |
| 375 |
dlna_handle_notify_last_change(state_variable) |
| 376 |
|
| 377 |
if service.service_id == "urn:upnp-org:serviceId:AVTransport": |
| 378 |
for state_variable in state_variables: |
| 379 |
if state_variable.name == "CurrentTrackMetaData": |
| 380 |
self._update_current_track_meta_data(state_variable) |
| 381 |
if state_variable.name == "AVTransportURIMetaData": |
| 382 |
self._update_av_transport_uri_metadata(state_variable) |
| 383 |
|
| 384 |
if self.on_event: |
| 385 |
# pylint: disable=not-callable |
| 386 |
self.on_event(service, state_variables) |
| 387 |
|
| 388 |
@property |
| 389 |
def state(self) -> DeviceState: |
| 390 |
""" |
| 391 |
Get current state. |
| 392 |
|
| 393 |
This property is deprecated and will be removed in a future version! |
| 394 |
Please use `transport_state` instead. |
| 395 |
""" |
| 396 |
state_var = self._state_variable("AVT", "TransportState") |
| 397 |
if not state_var: |
| 398 |
return DeviceState.ON |
| 399 |
|
| 400 |
state_value = (state_var.value or "").strip().lower() |
| 401 |
if state_value == "playing": |
| 402 |
return DeviceState.PLAYING |
| 403 |
if state_value in ("paused", "paused_playback"): |
| 404 |
return DeviceState.PAUSED |
| 405 |
|
| 406 |
return DeviceState.IDLE |
| 407 |
|
| 408 |
@property |
| 409 |
def transport_state(self) -> TransportState | None: |
| 410 |
"""Get transport state.""" |
| 411 |
state_var = self._state_variable("AVT", "TransportState") |
| 412 |
if not state_var: |
| 413 |
return None |
| 414 |
|
| 415 |
state_value = (state_var.value or "").strip().upper() |
| 416 |
try: |
| 417 |
return TransportState[state_value] |
| 418 |
except KeyError: |
| 419 |
# Unknown state; return VENDOR_DEFINED. |
| 420 |
return TransportState.VENDOR_DEFINED |
| 421 |
|
| 422 |
@property |
| 423 |
def _has_current_transport_actions(self) -> bool: |
| 424 |
state_var = self._state_variable("AVT", "CurrentTransportActions") |
| 425 |
if not state_var: |
| 426 |
return False |
| 427 |
return state_var.value is not None or state_var.updated_at is not None |
| 428 |
|
| 429 |
@property |
| 430 |
def _current_transport_actions(self) -> set[str]: |
| 431 |
state_var = self._state_variable("AVT", "CurrentTransportActions") |
| 432 |
if not state_var: |
| 433 |
return set() |
| 434 |
return _lower_split_commas(state_var.value or "") |
| 435 |
|
| 436 |
def _can_transport_action(self, action: str) -> bool: |
| 437 |
current_transport_actions = self._current_transport_actions |
| 438 |
return not current_transport_actions or action in current_transport_actions |
| 439 |
|
| 440 |
def _supports(self, var_name: str) -> bool: |
| 441 |
return self._state_variable("RC", var_name) is not None and self._action("RC", f"Set{var_name}") is not None |
| 442 |
|
| 443 |
def _level(self, var_name: str) -> float | None: |
| 444 |
state_var = self._state_variable("RC", var_name) |
| 445 |
if state_var is None: |
| 446 |
_LOGGER.debug("Missing StateVariable RC/%s", var_name) |
| 447 |
return None |
| 448 |
|
| 449 |
value: float | None = state_var.value |
| 450 |
if value is None: |
| 451 |
_LOGGER.debug("Got no value for %s", var_name) |
| 452 |
return None |
| 453 |
|
| 454 |
max_value = state_var.max_value or 100.0 |
| 455 |
return min(value / max_value, 1.0) |
| 456 |
|
| 457 |
async def _async_set_level(self, var_name: str, level: float, **kwargs: Any) -> None: |
| 458 |
action = self._action("RC", f"Set{var_name}") |
| 459 |
if not action: |
| 460 |
raise UpnpError(f"Missing Action RC/Set{var_name}") |
| 461 |
|
| 462 |
arg_name = f"Desired{var_name}" |
| 463 |
argument = action.argument(arg_name) |
| 464 |
if not argument: |
| 465 |
raise UpnpError(f"Missing Argument {arg_name} for Action RC/Set{var_name}") |
| 466 |
state_variable = argument.related_state_variable |
| 467 |
|
| 468 |
min_ = state_variable.min_value or 0 |
| 469 |
max_ = state_variable.max_value or 100 |
| 470 |
desired_level = int(min_ + level * (max_ - min_)) |
| 471 |
|
| 472 |
args = kwargs.copy() |
| 473 |
args[arg_name] = desired_level |
| 474 |
await action.async_call(InstanceID=0, **args) |
| 475 |
|
| 476 |
# region RC/Picture |
| 477 |
@property |
| 478 |
def has_brightness_level(self) -> bool: |
| 479 |
"""Check if device has brightness level controls.""" |
| 480 |
return self._supports("Brightness") |
| 481 |
|
| 482 |
@property |
| 483 |
def brightness_level(self) -> float | None: |
| 484 |
"""Brightness level of the media player (0..1).""" |
| 485 |
return self._level("Brightness") |
| 486 |
|
| 487 |
async def async_set_brightness_level(self, brightness: float) -> None: |
| 488 |
"""Set brightness level, range 0..1.""" |
| 489 |
await self._async_set_level("Brightness", brightness) |
| 490 |
|
| 491 |
@property |
| 492 |
def has_contrast_level(self) -> bool: |
| 493 |
"""Check if device has contrast level controls.""" |
| 494 |
return self._supports("Contrast") |
| 495 |
|
| 496 |
@property |
| 497 |
def contrast_level(self) -> float | None: |
| 498 |
"""Contrast level of the media player (0..1).""" |
| 499 |
return self._level("Contrast") |
| 500 |
|
| 501 |
async def async_set_contrast_level(self, contrast: float) -> None: |
| 502 |
"""Set contrast level, range 0..1.""" |
| 503 |
await self._async_set_level("Contrast", contrast) |
| 504 |
|
| 505 |
@property |
| 506 |
def has_sharpness_level(self) -> bool: |
| 507 |
"""Check if device has sharpness level controls.""" |
| 508 |
return self._supports("Sharpness") |
| 509 |
|
| 510 |
@property |
| 511 |
def sharpness_level(self) -> float | None: |
| 512 |
"""Sharpness level of the media player (0..1).""" |
| 513 |
return self._level("Sharpness") |
| 514 |
|
| 515 |
async def async_set_sharpness_level(self, sharpness: float) -> None: |
| 516 |
"""Set sharpness level, range 0..1.""" |
| 517 |
await self._async_set_level("Sharpness", sharpness) |
| 518 |
|
| 519 |
@property |
| 520 |
def has_color_temperature_level(self) -> bool: |
| 521 |
"""Check if device has color temperature level controls.""" |
| 522 |
return self._supports("ColorTemperature") |
| 523 |
|
| 524 |
@property |
| 525 |
def color_temperature_level(self) -> float | None: |
| 526 |
"""Color temperature level of the media player (0..1).""" |
| 527 |
return self._level("ColorTemperature") |
| 528 |
|
| 529 |
async def async_set_color_temperature_level(self, color_temperature: float) -> None: |
| 530 |
"""Set color temperature level, range 0..1.""" |
| 531 |
# pylint: disable=invalid-name |
| 532 |
await self._async_set_level("ColorTemperature", color_temperature) |
| 533 |
|
| 534 |
# endregion |
| 535 |
|
| 536 |
# region RC/Volume |
| 537 |
@property |
| 538 |
def has_volume_level(self) -> bool: |
| 539 |
"""Check if device has Volume level controls.""" |
| 540 |
return self._supports("Volume") |
| 541 |
|
| 542 |
@property |
| 543 |
def volume_level(self) -> float | None: |
| 544 |
"""Volume level of the media player (0..1).""" |
| 545 |
return self._level("Volume") |
| 546 |
|
| 547 |
async def async_set_volume_level(self, volume: float) -> None: |
| 548 |
"""Set volume level, range 0..1.""" |
| 549 |
await self._async_set_level("Volume", volume, Channel="Master") |
| 550 |
|
| 551 |
@property |
| 552 |
def has_volume_mute(self) -> bool: |
| 553 |
"""Check if device has Volume mute controls.""" |
| 554 |
return self._supports("Mute") |
| 555 |
|
| 556 |
@property |
| 557 |
def is_volume_muted(self) -> bool | None: |
| 558 |
"""Boolean if volume is currently muted.""" |
| 559 |
state_var = self._state_variable("RC", "Mute") |
| 560 |
if not state_var: |
| 561 |
return None |
| 562 |
value: bool | None = state_var.value |
| 563 |
if value is None: |
| 564 |
_LOGGER.debug("Got no value for Volume_mute") |
| 565 |
return None |
| 566 |
|
| 567 |
return value |
| 568 |
|
| 569 |
async def async_mute_volume(self, mute: bool) -> None: |
| 570 |
"""Mute the volume.""" |
| 571 |
action = self._action("RC", "SetMute") |
| 572 |
if not action: |
| 573 |
raise UpnpError("Missing action RC/SetMute") |
| 574 |
desired_mute = bool(mute) |
| 575 |
await action.async_call(InstanceID=0, Channel="Master", DesiredMute=desired_mute) |
| 576 |
|
| 577 |
# endregion |
| 578 |
|
| 579 |
# region RC/Preset |
| 580 |
@property |
| 581 |
def has_presets(self) -> bool: |
| 582 |
"""Check if device has control for rendering presets.""" |
| 583 |
return ( |
| 584 |
self._state_variable("RC", "PresetNameList") is not None and self._action("RC", "SelectPreset") is not None |
| 585 |
) |
| 586 |
|
| 587 |
@property |
| 588 |
def preset_names(self) -> list[str]: |
| 589 |
"""List of valid preset names.""" |
| 590 |
state_var = self._state_variable("RC", "PresetNameList") |
| 591 |
if state_var is None: |
| 592 |
_LOGGER.debug("Missing StateVariable RC/PresetNameList") |
| 593 |
return [] |
| 594 |
|
| 595 |
value: str | None = state_var.value |
| 596 |
if value is None: |
| 597 |
_LOGGER.debug("Got no value for PresetNameList") |
| 598 |
return [] |
| 599 |
|
| 600 |
return split_commas(value) |
| 601 |
|
| 602 |
async def async_select_preset(self, preset_name: str) -> None: |
| 603 |
"""Send SelectPreset command.""" |
| 604 |
action = self._action("RC", "SelectPreset") |
| 605 |
if not action: |
| 606 |
raise UpnpError("Missing action RC/SelectPreset") |
| 607 |
await action.async_call(InstanceID=0, PresetName=preset_name) |
| 608 |
|
| 609 |
# endregion |
| 610 |
|
| 611 |
# region AVT/Transport actions |
| 612 |
@property |
| 613 |
def has_pause(self) -> bool: |
| 614 |
"""Check if device has Pause controls.""" |
| 615 |
return self._action("AVT", "Pause") is not None |
| 616 |
|
| 617 |
@property |
| 618 |
def can_pause(self) -> bool: |
| 619 |
"""Check if the device can currently Pause.""" |
| 620 |
return self.has_pause and self._can_transport_action("pause") |
| 621 |
|
| 622 |
async def async_pause(self) -> None: |
| 623 |
"""Send pause command.""" |
| 624 |
if not self._can_transport_action("pause"): |
| 625 |
_LOGGER.debug("Cannot do Pause") |
| 626 |
return |
| 627 |
|
| 628 |
action = self._action("AVT", "Pause") |
| 629 |
if not action: |
| 630 |
raise UpnpError("Missing action AVT/Pause") |
| 631 |
await action.async_call(InstanceID=0) |
| 632 |
|
| 633 |
@property |
| 634 |
def has_play(self) -> bool: |
| 635 |
"""Check if device has Play controls.""" |
| 636 |
return self._action("AVT", "Play") is not None |
| 637 |
|
| 638 |
@property |
| 639 |
def can_play(self) -> bool: |
| 640 |
"""Check if the device can currently play.""" |
| 641 |
return self.has_play and self._can_transport_action("play") |
| 642 |
|
| 643 |
async def async_play(self) -> None: |
| 644 |
"""Send play command.""" |
| 645 |
if not self._can_transport_action("play"): |
| 646 |
_LOGGER.debug("Cannot do Play") |
| 647 |
return |
| 648 |
|
| 649 |
action = self._action("AVT", "Play") |
| 650 |
if not action: |
| 651 |
raise UpnpError("Missing action AVT/Play") |
| 652 |
await action.async_call(InstanceID=0, Speed="1") |
| 653 |
|
| 654 |
@property |
| 655 |
def can_stop(self) -> bool: |
| 656 |
"""Check if the device can currently stop.""" |
| 657 |
return self.has_stop and self._can_transport_action("stop") |
| 658 |
|
| 659 |
@property |
| 660 |
def has_stop(self) -> bool: |
| 661 |
"""Check if device has Play controls.""" |
| 662 |
return self._action("AVT", "Stop") is not None |
| 663 |
|
| 664 |
async def async_stop(self) -> None: |
| 665 |
"""Send stop command.""" |
| 666 |
if not self._can_transport_action("stop"): |
| 667 |
_LOGGER.debug("Cannot do Stop") |
| 668 |
return |
| 669 |
|
| 670 |
action = self._action("AVT", "Stop") |
| 671 |
if not action: |
| 672 |
raise UpnpError("Missing action AVT/Stop") |
| 673 |
await action.async_call(InstanceID=0) |
| 674 |
|
| 675 |
@property |
| 676 |
def has_previous(self) -> bool: |
| 677 |
"""Check if device has Previous controls.""" |
| 678 |
return self._action("AVT", "Previous") is not None |
| 679 |
|
| 680 |
@property |
| 681 |
def can_previous(self) -> bool: |
| 682 |
"""Check if the device can currently Previous.""" |
| 683 |
return self.has_previous and self._can_transport_action("previous") |
| 684 |
|
| 685 |
async def async_previous(self) -> None: |
| 686 |
"""Send previous track command.""" |
| 687 |
if not self._can_transport_action("previous"): |
| 688 |
_LOGGER.debug("Cannot do Previous") |
| 689 |
return |
| 690 |
|
| 691 |
action = self._action("AVT", "Previous") |
| 692 |
if not action: |
| 693 |
raise UpnpError("Missing action AVT/Previous") |
| 694 |
await action.async_call(InstanceID=0) |
| 695 |
|
| 696 |
@property |
| 697 |
def has_next(self) -> bool: |
| 698 |
"""Check if device has Next controls.""" |
| 699 |
return self._action("AVT", "Next") is not None |
| 700 |
|
| 701 |
@property |
| 702 |
def can_next(self) -> bool: |
| 703 |
"""Check if the device can currently Next.""" |
| 704 |
return self.has_next and self._can_transport_action("next") |
| 705 |
|
| 706 |
async def async_next(self) -> None: |
| 707 |
"""Send next track command.""" |
| 708 |
if not self._can_transport_action("next"): |
| 709 |
_LOGGER.debug("Cannot do Next") |
| 710 |
return |
| 711 |
|
| 712 |
action = self._action("AVT", "Next") |
| 713 |
if not action: |
| 714 |
raise UpnpError("Missing action AVT/Next") |
| 715 |
await action.async_call(InstanceID=0) |
| 716 |
|
| 717 |
def _has_seek_with_mode(self, mode: str) -> bool: |
| 718 |
"""Check if device has Seek mode.""" |
| 719 |
action = self._action("AVT", "Seek") |
| 720 |
state_var = self._state_variable("AVT", "A_ARG_TYPE_SeekMode") |
| 721 |
if action is None or state_var is None: |
| 722 |
return False |
| 723 |
return mode.lower() in state_var.normalized_allowed_values |
| 724 |
|
| 725 |
@property |
| 726 |
def has_seek_abs_time(self) -> bool: |
| 727 |
"""Check if device has Seek controls, by ABS_TIME.""" |
| 728 |
return self._has_seek_with_mode("ABS_TIME") |
| 729 |
|
| 730 |
@property |
| 731 |
def can_seek_abs_time(self) -> bool: |
| 732 |
"""Check if the device can currently Seek with ABS_TIME.""" |
| 733 |
return self.has_seek_abs_time and self._can_transport_action("seek") |
| 734 |
|
| 735 |
async def async_seek_abs_time(self, time: timedelta) -> None: |
| 736 |
"""Send seek command with ABS_TIME.""" |
| 737 |
if not self._can_transport_action("seek"): |
| 738 |
_LOGGER.debug("Cannot do Seek by ABS_TIME") |
| 739 |
return |
| 740 |
|
| 741 |
action = self._action("AVT", "Seek") |
| 742 |
if not action: |
| 743 |
raise UpnpError("Missing action AVT/Seek") |
| 744 |
target = time_to_str(time) |
| 745 |
await action.async_call(InstanceID=0, Unit="ABS_TIME", Target=target) |
| 746 |
|
| 747 |
@property |
| 748 |
def has_seek_rel_time(self) -> bool: |
| 749 |
"""Check if device has Seek controls, by REL_TIME.""" |
| 750 |
return self._has_seek_with_mode("REL_TIME") |
| 751 |
|
| 752 |
@property |
| 753 |
def can_seek_rel_time(self) -> bool: |
| 754 |
"""Check if the device can currently Seek with REL_TIME.""" |
| 755 |
return self.has_seek_rel_time and self._can_transport_action("seek") |
| 756 |
|
| 757 |
async def async_seek_rel_time(self, time: timedelta) -> None: |
| 758 |
"""Send seek command with REL_TIME.""" |
| 759 |
if not self._can_transport_action("seek"): |
| 760 |
_LOGGER.debug("Cannot do Seek by REL_TIME") |
| 761 |
return |
| 762 |
|
| 763 |
action = self._action("AVT", "Seek") |
| 764 |
if not action: |
| 765 |
raise UpnpError("Missing action AVT/Seek") |
| 766 |
target = time_to_str(time) |
| 767 |
await action.async_call(InstanceID=0, Unit="REL_TIME", Target=target) |
| 768 |
|
| 769 |
@property |
| 770 |
def has_play_media(self) -> bool: |
| 771 |
"""Check if device has Play controls.""" |
| 772 |
return self._action("AVT", "SetAVTransportURI") is not None |
| 773 |
|
| 774 |
@property |
| 775 |
def current_track_uri(self) -> str | None: |
| 776 |
"""Return the URI of the currently playing track.""" |
| 777 |
state_var = self._state_variable("AVT", "CurrentTrackURI") |
| 778 |
if state_var is None: |
| 779 |
_LOGGER.debug("Missing StateVariable AVT/CurrentTrackURI") |
| 780 |
return None |
| 781 |
|
| 782 |
return state_var.value |
| 783 |
|
| 784 |
@property |
| 785 |
def av_transport_uri(self) -> str | None: |
| 786 |
"""Return the URI of the currently playing resource (playlist or track).""" |
| 787 |
state_var = self._state_variable("AVT", "AVTransportURI") |
| 788 |
if state_var is None: |
| 789 |
_LOGGER.debug("Missing StateVariable AVT/AVTransportURI") |
| 790 |
return None |
| 791 |
|
| 792 |
return state_var.value |
| 793 |
|
| 794 |
async def async_set_transport_uri( |
| 795 |
self, |
| 796 |
media_url: str, |
| 797 |
media_title: str, |
| 798 |
meta_data: None | str | Mapping = None, |
| 799 |
) -> None: |
| 800 |
"""Play a piece of media.""" |
| 801 |
# escape media_url |
| 802 |
_LOGGER.debug("Set transport uri: %s", media_url) |
| 803 |
|
| 804 |
# queue media |
| 805 |
if not isinstance(meta_data, str): |
| 806 |
meta_data = await self.construct_play_media_metadata(media_url, media_title, meta_data=meta_data) |
| 807 |
action = self._action("AVT", "SetAVTransportURI") |
| 808 |
if not action: |
| 809 |
raise UpnpError("Missing action AVT/SetAVTransportURI") |
| 810 |
await action.async_call(InstanceID=0, CurrentURI=media_url, CurrentURIMetaData=meta_data) |
| 811 |
|
| 812 |
@property |
| 813 |
def has_next_transport_uri(self) -> bool: |
| 814 |
"""Check if device has controls to set the next item for playback.""" |
| 815 |
return ( |
| 816 |
self._state_variable("AVT", "NextAVTransportURI") is not None |
| 817 |
and self._action("AVT", "SetNextAVTransportURI") is not None |
| 818 |
) |
| 819 |
|
| 820 |
async def async_set_next_transport_uri( |
| 821 |
self, |
| 822 |
media_url: str, |
| 823 |
media_title: str, |
| 824 |
meta_data: None | str | Mapping = None, |
| 825 |
) -> None: |
| 826 |
"""Enqueue a piece of media for playing immediately after the current media.""" |
| 827 |
# escape media_url |
| 828 |
_LOGGER.debug("Set next transport uri: %s", media_url) |
| 829 |
|
| 830 |
# queue media |
| 831 |
if not isinstance(meta_data, str): |
| 832 |
meta_data = await self.construct_play_media_metadata(media_url, media_title, meta_data=meta_data) |
| 833 |
action = self._action("AVT", "SetNextAVTransportURI") |
| 834 |
if not action: |
| 835 |
raise UpnpError("Missing action AVT/SetNextAVTransportURI") |
| 836 |
await action.async_call(InstanceID=0, NextURI=media_url, NextURIMetaData=meta_data) |
| 837 |
|
| 838 |
async def async_wait_for_can_play(self, max_wait_time: float = 5) -> None: |
| 839 |
"""Wait for play command to be ready.""" |
| 840 |
loop_time = 0.25 |
| 841 |
end_time = monotonic_timer() + max_wait_time |
| 842 |
|
| 843 |
while monotonic_timer() <= end_time: |
| 844 |
if self._can_transport_action("play"): |
| 845 |
break |
| 846 |
await asyncio.sleep(loop_time) |
| 847 |
# Check again before trying to poll, in case variable change event received |
| 848 |
if self._can_transport_action("play"): |
| 849 |
break |
| 850 |
# Poll current transport actions, even if we're subscribed, just in |
| 851 |
# case the device isn't eventing properly. |
| 852 |
await self._async_poll_state_variables("AVT", "GetCurrentTransportActions", InstanceID=0) |
| 853 |
else: |
| 854 |
_LOGGER.debug("break out of waiting game") |
| 855 |
|
| 856 |
async def _fetch_headers(self, url: str, headers: Mapping[str, str]) -> Mapping[str, str] | None: |
| 857 |
"""Do a HEAD/GET to get resources headers.""" |
| 858 |
requester = self.profile_device.requester |
| 859 |
|
| 860 |
# try a HEAD first |
| 861 |
request = HttpRequest("HEAD", url, headers, None) |
| 862 |
response = await requester.async_http_request(request) |
| 863 |
if 200 <= response.status_code < 300: |
| 864 |
return response.headers |
| 865 |
|
| 866 |
if response.status_code == HTTPStatus.NOT_FOUND: |
| 867 |
# Give up when the item doesn't exist, otherwise try GET below |
| 868 |
return None |
| 869 |
|
| 870 |
# then try a GET request for only the first byte of content |
| 871 |
get_headers = dict(headers) |
| 872 |
get_headers["Range"] = "bytes=0-0" |
| 873 |
request = HttpRequest("GET", url, get_headers, None) |
| 874 |
response = await requester.async_http_request(request) |
| 875 |
if 200 <= response.status_code < 300: |
| 876 |
return response.headers |
| 877 |
|
| 878 |
# finally try a plain GET, which might return a lot of data |
| 879 |
request = HttpRequest("GET", url, headers, None) |
| 880 |
response = await requester.async_http_request(request) |
| 881 |
if 200 <= response.status_code < 300: |
| 882 |
return response.headers |
| 883 |
|
| 884 |
return None |
| 885 |
|
| 886 |
async def construct_play_media_metadata( |
| 887 |
self, |
| 888 |
media_url: str, |
| 889 |
media_title: str, |
| 890 |
default_mime_type: str | None = None, |
| 891 |
default_upnp_class: str | None = None, |
| 892 |
override_mime_type: str | None = None, |
| 893 |
override_upnp_class: str | None = None, |
| 894 |
override_dlna_features: str | None = None, |
| 895 |
meta_data: Mapping[str, Any] | None = None, |
| 896 |
) -> str: |
| 897 |
""" |
| 898 |
Construct the metadata for play_media command. |
| 899 |
|
| 900 |
This queries the source and takes mime_type/dlna_features from it. |
| 901 |
|
| 902 |
The base metadata is updated with key:values from meta_data, e.g. |
| 903 |
`meta_data = {"artist": "Singer X"}` |
| 904 |
""" |
| 905 |
# pylint: disable=too-many-arguments, too-many-positional-arguments, too-many-locals, too-many-branches |
| 906 |
mime_type = override_mime_type or "" |
| 907 |
upnp_class = override_upnp_class or "" |
| 908 |
dlna_features = override_dlna_features or "*" |
| 909 |
meta_data = meta_data or {} |
| 910 |
|
| 911 |
if None in (override_mime_type, override_dlna_features): |
| 912 |
# do a HEAD/GET, to retrieve content-type/mime-type |
| 913 |
try: |
| 914 |
headers = await self._fetch_headers(media_url, {"GetContentFeatures.dlna.org": "1"}) |
| 915 |
if headers: |
| 916 |
if not override_mime_type and "Content-Type" in headers: |
| 917 |
mime_type = headers["Content-Type"] |
| 918 |
if not override_dlna_features and "ContentFeatures.dlna.org" in headers: |
| 919 |
dlna_features = headers["ContentFeatures.dlna.org"] |
| 920 |
except Exception: # pylint: disable=broad-except |
| 921 |
pass |
| 922 |
|
| 923 |
if not mime_type: |
| 924 |
_type = guess_type(media_url.split("?")[0]) |
| 925 |
mime_type = _type[0] or "" |
| 926 |
if not mime_type: |
| 927 |
mime_type = default_mime_type or "application/octet-stream" |
| 928 |
|
| 929 |
# use CM/GetProtocolInfo to improve on dlna_features |
| 930 |
if not override_dlna_features and dlna_features != "*" and self.has_get_protocol_info: |
| 931 |
protocol_info_entries = await self._async_get_sink_protocol_info_for_mime_type(mime_type) |
| 932 |
for entry in protocol_info_entries: |
| 933 |
if entry[3] == "*": |
| 934 |
# device accepts anything, send this |
| 935 |
dlna_features = "*" |
| 936 |
|
| 937 |
# Try to derive a basic upnp_class from mime_type |
| 938 |
if not override_upnp_class: |
| 939 |
mime_type = mime_type.lower() |
| 940 |
for _mime, _class in MIME_TO_UPNP_CLASS_MAPPING.items(): |
| 941 |
if mime_type.startswith(_mime): |
| 942 |
upnp_class = _class |
| 943 |
break |
| 944 |
else: |
| 945 |
upnp_class = default_upnp_class or "object.item" |
| 946 |
|
| 947 |
# build DIDL-Lite item + resource |
| 948 |
didl_item_type = didl_lite.type_by_upnp_class(upnp_class) |
| 949 |
if not didl_item_type: |
| 950 |
raise UpnpError("Unknown DIDL-lite type") |
| 951 |
|
| 952 |
protocol_info = f"http-get:*:{mime_type}:{dlna_features}" |
| 953 |
resource = didl_lite.Resource(uri=media_url, protocol_info=protocol_info) |
| 954 |
item = didl_item_type( |
| 955 |
id="0", |
| 956 |
parent_id="-1", |
| 957 |
title=media_title or meta_data.get("title"), |
| 958 |
restricted="false", |
| 959 |
resources=[resource], |
| 960 |
) |
| 961 |
|
| 962 |
# Set any metadata properties that are supported by the DIDL item |
| 963 |
for key, value in meta_data.items(): |
| 964 |
setattr(item, key, str(value)) |
| 965 |
|
| 966 |
xml_string: bytes = didl_lite.to_xml_string(item) |
| 967 |
return xml_string.decode("utf-8") |
| 968 |
|
| 969 |
async def _async_get_sink_protocol_info_for_mime_type(self, mime_type: str) -> list[list[str]]: |
| 970 |
"""Get protocol_info for a specific mime type.""" |
| 971 |
# example entry: |
| 972 |
# http-get:*:video/mpeg:DLNA.ORG_PN=MPEG_TS_HD_KO_ISO;DLNA.ORG_FLAGS=ED100000000000000000... |
| 973 |
return [ |
| 974 |
entry.split(":") |
| 975 |
for entry in self.source_protocol_info |
| 976 |
if ":" in entry and entry.split(":")[2] == mime_type |
| 977 |
] |
| 978 |
|
| 979 |
# endregion |
| 980 |
|
| 981 |
# region: AVT/PlayMode |
| 982 |
@property |
| 983 |
def has_play_mode(self) -> bool: |
| 984 |
"""Check if device supports setting the play mode.""" |
| 985 |
return ( |
| 986 |
self._state_variable("AVT", "CurrentPlayMode") is not None |
| 987 |
and self._action("AVT", "SetPlayMode") is not None |
| 988 |
) |
| 989 |
|
| 990 |
@property |
| 991 |
def valid_play_modes(self) -> set[PlayMode]: |
| 992 |
"""Return a set of play modes that can be used.""" |
| 993 |
play_modes: set[PlayMode] = set() |
| 994 |
state_var = self._state_variable("AVT", "CurrentPlayMode") |
| 995 |
if state_var is None: |
| 996 |
return play_modes |
| 997 |
|
| 998 |
for normalized_allowed_value in state_var.normalized_allowed_values: |
| 999 |
try: |
| 1000 |
mode = PlayMode[normalized_allowed_value.upper()] |
| 1001 |
except KeyError: |
| 1002 |
# Unknown mode, don't report it as valid |
| 1003 |
continue |
| 1004 |
play_modes.add(mode) |
| 1005 |
|
| 1006 |
return play_modes |
| 1007 |
|
| 1008 |
@property |
| 1009 |
def play_mode(self) -> PlayMode | None: |
| 1010 |
"""Get play mode.""" |
| 1011 |
state_var = self._state_variable("AVT", "CurrentPlayMode") |
| 1012 |
if not state_var: |
| 1013 |
return None |
| 1014 |
|
| 1015 |
state_value = (state_var.value or "").strip().upper() |
| 1016 |
try: |
| 1017 |
return PlayMode[state_value] |
| 1018 |
except KeyError: |
| 1019 |
# Unknown mode; return VENDOR_DEFINED. |
| 1020 |
return PlayMode.VENDOR_DEFINED |
| 1021 |
|
| 1022 |
async def async_set_play_mode(self, mode: PlayMode) -> None: |
| 1023 |
"""Send SetPlayMode command.""" |
| 1024 |
action = self._action("AVT", "SetPlayMode") |
| 1025 |
if not action: |
| 1026 |
raise UpnpError("Missing action AVT/SetPlayMode") |
| 1027 |
await action.async_call(InstanceID=0, NewPlayMode=mode.name) |
| 1028 |
|
| 1029 |
# endregion |
| 1030 |
|
| 1031 |
# region AVT/Media info |
| 1032 |
def _update_current_track_meta_data(self, state_var: UpnpStateVariable) -> None: |
| 1033 |
"""Update the cached parsed value of AVT/CurrentTrackMetaData.""" |
| 1034 |
xml = state_var.value |
| 1035 |
if not xml or xml == "NOT_IMPLEMENTED": |
| 1036 |
self._current_track_meta_data = None |
| 1037 |
return |
| 1038 |
|
| 1039 |
items = _cached_from_xml_string(xml) |
| 1040 |
if not items: |
| 1041 |
self._current_track_meta_data = None |
| 1042 |
return |
| 1043 |
|
| 1044 |
item = items[0] |
| 1045 |
if not isinstance(item, didl_lite.DidlObject): |
| 1046 |
self._current_track_meta_data = None |
| 1047 |
return |
| 1048 |
|
| 1049 |
self._current_track_meta_data = item |
| 1050 |
|
| 1051 |
def _get_current_track_meta_data(self, attr: str) -> str | None: |
| 1052 |
"""Return a metadata attribute if it exists, None otherwise.""" |
| 1053 |
if not self._current_track_meta_data: |
| 1054 |
return None |
| 1055 |
|
| 1056 |
if not hasattr(self._current_track_meta_data, attr): |
| 1057 |
return None |
| 1058 |
|
| 1059 |
value: str = getattr(self._current_track_meta_data, attr) |
| 1060 |
return value |
| 1061 |
|
| 1062 |
@property |
| 1063 |
def media_class(self) -> str | None: |
| 1064 |
"""DIDL-Lite class of currently playing media.""" |
| 1065 |
if not self._current_track_meta_data: |
| 1066 |
return None |
| 1067 |
media_class: str = self._current_track_meta_data.upnp_class |
| 1068 |
return media_class |
| 1069 |
|
| 1070 |
@property |
| 1071 |
def media_title(self) -> str | None: |
| 1072 |
"""Title of current playing media.""" |
| 1073 |
return self._get_current_track_meta_data("title") |
| 1074 |
|
| 1075 |
@property |
| 1076 |
def media_program_title(self) -> str | None: |
| 1077 |
"""Title of current playing media.""" |
| 1078 |
return self._get_current_track_meta_data("program_title") |
| 1079 |
|
| 1080 |
@property |
| 1081 |
def media_artist(self) -> str | None: |
| 1082 |
"""Artist of current playing media.""" |
| 1083 |
return self._get_current_track_meta_data("artist") |
| 1084 |
|
| 1085 |
@property |
| 1086 |
def media_album_name(self) -> str | None: |
| 1087 |
"""Album name of current playing media.""" |
| 1088 |
return self._get_current_track_meta_data("album") |
| 1089 |
|
| 1090 |
@property |
| 1091 |
def media_album_artist(self) -> str | None: |
| 1092 |
"""Album artist of current playing media.""" |
| 1093 |
return self._get_current_track_meta_data("album_artist") |
| 1094 |
|
| 1095 |
@property |
| 1096 |
def media_track_number(self) -> int | None: |
| 1097 |
"""Track number of current playing media.""" |
| 1098 |
state_var = self._state_variable("AVT", "CurrentTrack") |
| 1099 |
if state_var is None: |
| 1100 |
_LOGGER.debug("Missing StateVariable AVT/CurrentTrack") |
| 1101 |
return None |
| 1102 |
|
| 1103 |
value: int | None = state_var.value |
| 1104 |
return value |
| 1105 |
|
| 1106 |
@property |
| 1107 |
def media_series_title(self) -> str | None: |
| 1108 |
"""Title of series of currently playing media.""" |
| 1109 |
return self._get_current_track_meta_data("series_title") |
| 1110 |
|
| 1111 |
@property |
| 1112 |
def media_season_number(self) -> str | None: |
| 1113 |
"""Season of series of currently playing media.""" |
| 1114 |
return self._get_current_track_meta_data("episode_season") |
| 1115 |
|
| 1116 |
@property |
| 1117 |
def media_episode_number(self) -> str | None: |
| 1118 |
"""Episode number, within the series, of current playing media. |
| 1119 |
|
| 1120 |
Note: This is usually the absolute number, starting at 1, of the episode |
| 1121 |
within the *series* and not the *season*. |
| 1122 |
""" |
| 1123 |
return self._get_current_track_meta_data("episode_number") |
| 1124 |
|
| 1125 |
@property |
| 1126 |
def media_episode_count(self) -> str | None: |
| 1127 |
"""Total number of episodes in series to which currently playing media belongs.""" |
| 1128 |
return self._get_current_track_meta_data("episode_count") |
| 1129 |
|
| 1130 |
@property |
| 1131 |
def media_channel_name(self) -> str | None: |
| 1132 |
"""Name of currently playing channel.""" |
| 1133 |
return self._get_current_track_meta_data("channel_name") |
| 1134 |
|
| 1135 |
@property |
| 1136 |
def media_channel_number(self) -> str | None: |
| 1137 |
"""Channel number of currently playing channel.""" |
| 1138 |
return self._get_current_track_meta_data("channel_number") |
| 1139 |
|
| 1140 |
@property |
| 1141 |
def media_image_url(self) -> str | None: |
| 1142 |
"""Image url of current playing media.""" |
| 1143 |
state_var = self._state_variable("AVT", "CurrentTrackMetaData") |
| 1144 |
if state_var is None: |
| 1145 |
return None |
| 1146 |
|
| 1147 |
xml = state_var.value |
| 1148 |
if not xml or xml == "NOT_IMPLEMENTED": |
| 1149 |
return None |
| 1150 |
|
| 1151 |
items = _cached_from_xml_string(xml) |
| 1152 |
if not items: |
| 1153 |
return None |
| 1154 |
|
| 1155 |
device_url = self.profile_device.device_url |
| 1156 |
for item in items: |
| 1157 |
# Some players use Item.albumArtURI, |
| 1158 |
# though not found in the UPnP-av-ConnectionManager-v1-Service spec. |
| 1159 |
if hasattr(item, "album_art_uri") and item.album_art_uri is not None: |
| 1160 |
return absolute_url(device_url, item.album_art_uri) |
| 1161 |
|
| 1162 |
for res in item.resources: |
| 1163 |
protocol_info = res.protocol_info or "" |
| 1164 |
if protocol_info.startswith("http-get:*:image/") and res.uri: |
| 1165 |
return absolute_url(device_url, res.uri) |
| 1166 |
|
| 1167 |
return None |
| 1168 |
|
| 1169 |
@property |
| 1170 |
def media_duration(self) -> int | None: |
| 1171 |
"""Duration of current playing media in seconds.""" |
| 1172 |
state_var = self._state_variable("AVT", "CurrentTrackDuration") |
| 1173 |
if state_var is None or state_var.value is None or state_var.value == "NOT_IMPLEMENTED": |
| 1174 |
return None |
| 1175 |
|
| 1176 |
time = str_to_time(state_var.value) |
| 1177 |
if time is None: |
| 1178 |
return None |
| 1179 |
|
| 1180 |
return time.seconds |
| 1181 |
|
| 1182 |
@property |
| 1183 |
def media_position(self) -> int | None: |
| 1184 |
"""Position of current playing media in seconds.""" |
| 1185 |
state_var = self._state_variable("AVT", "RelativeTimePosition") |
| 1186 |
if state_var is None or state_var.value is None or state_var.value == "NOT_IMPLEMENTED": |
| 1187 |
return None |
| 1188 |
|
| 1189 |
time = str_to_time(state_var.value) |
| 1190 |
if time is None: |
| 1191 |
return None |
| 1192 |
|
| 1193 |
return time.seconds |
| 1194 |
|
| 1195 |
@property |
| 1196 |
def media_position_updated_at(self) -> datetime | None: |
| 1197 |
"""When was the position of the current playing media valid.""" |
| 1198 |
state_var = self._state_variable("AVT", "RelativeTimePosition") |
| 1199 |
if state_var is None: |
| 1200 |
return None |
| 1201 |
|
| 1202 |
return state_var.updated_at |
| 1203 |
|
| 1204 |
# endregion |
| 1205 |
|
| 1206 |
# region AVT/Playlist info |
| 1207 |
def _update_av_transport_uri_metadata(self, state_var: UpnpStateVariable) -> None: |
| 1208 |
"""Update the cached parsed value of AVT/AVTransportURIMetaData.""" |
| 1209 |
xml = state_var.value |
| 1210 |
if not xml or xml == "NOT_IMPLEMENTED": |
| 1211 |
self._av_transport_uri_meta_data = None |
| 1212 |
return |
| 1213 |
|
| 1214 |
items = _cached_from_xml_string(xml) |
| 1215 |
if not items: |
| 1216 |
self._av_transport_uri_meta_data = None |
| 1217 |
return |
| 1218 |
|
| 1219 |
item = items[0] |
| 1220 |
if not isinstance(item, didl_lite.DidlObject): |
| 1221 |
self._av_transport_uri_meta_data = None |
| 1222 |
return |
| 1223 |
|
| 1224 |
self._av_transport_uri_meta_data = item |
| 1225 |
|
| 1226 |
def _get_av_transport_meta_data(self, attr: str) -> str | None: |
| 1227 |
"""Return an attribute of AVTransportURIMetaData if it exists, None otherwise.""" |
| 1228 |
if not self._av_transport_uri_meta_data: |
| 1229 |
return None |
| 1230 |
|
| 1231 |
if not hasattr(self._av_transport_uri_meta_data, attr): |
| 1232 |
return None |
| 1233 |
|
| 1234 |
value: str = getattr(self._av_transport_uri_meta_data, attr) |
| 1235 |
return value |
| 1236 |
|
| 1237 |
@property |
| 1238 |
def media_playlist_title(self) -> str | None: |
| 1239 |
"""Title of currently playing playlist, if a playlist is playing.""" |
| 1240 |
if self.av_transport_uri == self.current_track_uri: |
| 1241 |
# A single track is playing, no playlist to report |
| 1242 |
return None |
| 1243 |
|
| 1244 |
return self._get_av_transport_meta_data("title") |
| 1245 |
|
| 1246 |
# endregion |
| 1247 |
|
| 1248 |
|
| 1249 |
class DmsDevice(ConnectionManagerMixin, UpnpProfileDevice): |
| 1250 |
"""Representation of a DLNA DMS device.""" |
| 1251 |
|
| 1252 |
DEVICE_TYPES = [ |
| 1253 |
"urn:schemas-upnp-org:device:MediaServer:1", |
| 1254 |
"urn:schemas-upnp-org:device:MediaServer:2", |
| 1255 |
"urn:schemas-upnp-org:device:MediaServer:3", |
| 1256 |
"urn:schemas-upnp-org:device:MediaServer:4", |
| 1257 |
] |
| 1258 |
|
| 1259 |
SERVICE_IDS = frozenset( |
| 1260 |
( |
| 1261 |
"urn:upnp-org:serviceId:ConnectionManager", |
| 1262 |
"urn:upnp-org:serviceId:ContentDirectory", |
| 1263 |
) |
| 1264 |
) |
| 1265 |
|
| 1266 |
_SERVICE_TYPES = { |
| 1267 |
"CD": { |
| 1268 |
"urn:schemas-upnp-org:service:ContentDirectory:4", |
| 1269 |
"urn:schemas-upnp-org:service:ContentDirectory:3", |
| 1270 |
"urn:schemas-upnp-org:service:ContentDirectory:2", |
| 1271 |
"urn:schemas-upnp-org:service:ContentDirectory:1", |
| 1272 |
}, |
| 1273 |
**ConnectionManagerMixin._SERVICE_TYPES, |
| 1274 |
} |
| 1275 |
|
| 1276 |
METADATA_FILTER_ALL = "*" |
| 1277 |
DEFAULT_METADATA_FILTER = METADATA_FILTER_ALL |
| 1278 |
DEFAULT_SORT_CRITERIA = "" |
| 1279 |
|
| 1280 |
__did_first_update: bool = False |
| 1281 |
|
| 1282 |
async def async_update(self, do_ping: bool = False) -> None: |
| 1283 |
"""Retrieve the latest data.""" |
| 1284 |
# pylint: disable=arguments-differ |
| 1285 |
await super().async_update() |
| 1286 |
|
| 1287 |
# Retrieve unevented changeable values |
| 1288 |
if not self.is_subscribed or not self.__did_first_update: |
| 1289 |
await self._async_poll_state_variables("CD", "GetSystemUpdateID") |
| 1290 |
elif do_ping: |
| 1291 |
await self.profile_device.async_ping() |
| 1292 |
|
| 1293 |
# Retrieve unchanging state variables only once |
| 1294 |
if not self.__did_first_update: |
| 1295 |
await self._async_poll_state_variables("CD", ["GetSearchCapabilities", "GetSortCapabilities"]) |
| 1296 |
self.__did_first_update = True |
| 1297 |
|
| 1298 |
def get_absolute_url(self, url: str) -> str: |
| 1299 |
"""Resolve a URL returned by the device into an absolute URL.""" |
| 1300 |
return absolute_url(self.device.device_url, url) |
| 1301 |
|
| 1302 |
# region CD |
| 1303 |
@property |
| 1304 |
def search_capabilities(self) -> list[str]: |
| 1305 |
"""List of capabilities that are supported for search.""" |
| 1306 |
state_var = self._state_variable("CD", "SearchCapabilities") |
| 1307 |
if state_var is None or state_var.value is None: |
| 1308 |
return [] |
| 1309 |
|
| 1310 |
return split_commas(state_var.value) |
| 1311 |
|
| 1312 |
@property |
| 1313 |
def sort_capabilities(self) -> list[str]: |
| 1314 |
"""List of meta-data tags that can be used in sort_criteria.""" |
| 1315 |
state_var = self._state_variable("CD", "SortCapabilities") |
| 1316 |
if state_var is None or state_var.value is None: |
| 1317 |
return [] |
| 1318 |
|
| 1319 |
return split_commas(state_var.value) |
| 1320 |
|
| 1321 |
@property |
| 1322 |
def system_update_id(self) -> int | None: |
| 1323 |
"""Return the latest update SystemUpdateID. |
| 1324 |
|
| 1325 |
Changes to this ID indicate that changes have occurred in the Content |
| 1326 |
Directory. |
| 1327 |
""" |
| 1328 |
state_var = self._state_variable("CD", "SystemUpdateID") |
| 1329 |
if state_var is None or state_var.value is None: |
| 1330 |
return None |
| 1331 |
|
| 1332 |
return int(state_var.value) |
| 1333 |
|
| 1334 |
@property |
| 1335 |
def has_container_update_ids(self) -> bool: |
| 1336 |
"""Check if device supports the ContainerUpdateIDs variable.""" |
| 1337 |
return self._action("CD", "ContainerUpdateIDs") is not None |
| 1338 |
|
| 1339 |
@property |
| 1340 |
def container_update_ids(self) -> dict[str, int] | None: |
| 1341 |
"""Return latest list of changed containers. |
| 1342 |
|
| 1343 |
This variable is evented only, and optional. If it's None, use the |
| 1344 |
system_update_id to track container changes instead. |
| 1345 |
|
| 1346 |
:return: Mapping of container IDs to container update IDs |
| 1347 |
""" |
| 1348 |
state_var = self._state_variable("CD", "ContainerUpdateIDs") |
| 1349 |
if state_var is None or state_var.value is None: |
| 1350 |
return None |
| 1351 |
|
| 1352 |
# Convert list of containerID,updateID,containerID,updateID pairs to dict |
| 1353 |
id_list = split_commas(state_var.value) |
| 1354 |
return {id_list[i]: int(id_list[i + 1]) for i in range(0, len(id_list), 2)} |
| 1355 |
|
| 1356 |
class BrowseResult(NamedTuple): |
| 1357 |
"""Result returned from a Browse or Search action.""" |
| 1358 |
|
| 1359 |
result: list[didl_lite.DidlObject | didl_lite.Descriptor] |
| 1360 |
number_returned: int |
| 1361 |
total_matches: int |
| 1362 |
update_id: int |
| 1363 |
|
| 1364 |
async def async_browse( |
| 1365 |
self, |
| 1366 |
object_id: str, |
| 1367 |
browse_flag: str, |
| 1368 |
metadata_filter: Iterable[str] | str = DEFAULT_METADATA_FILTER, |
| 1369 |
starting_index: int = 0, |
| 1370 |
requested_count: int = 0, |
| 1371 |
sort_criteria: Iterable[str] | str = DEFAULT_SORT_CRITERIA, |
| 1372 |
) -> BrowseResult: |
| 1373 |
"""Retrieve an object's metadata or its children.""" |
| 1374 |
# pylint: disable=too-many-arguments,too-many-positional-arguments |
| 1375 |
action = self._action("CD", "Browse") |
| 1376 |
if not action: |
| 1377 |
raise UpnpError("Missing action CD/Browse") |
| 1378 |
|
| 1379 |
if not isinstance(metadata_filter, str): |
| 1380 |
metadata_filter = ",".join(metadata_filter) |
| 1381 |
|
| 1382 |
if not isinstance(sort_criteria, str): |
| 1383 |
sort_criteria = ",".join(sort_criteria) |
| 1384 |
|
| 1385 |
result = await action.async_call( |
| 1386 |
ObjectID=object_id, |
| 1387 |
BrowseFlag=browse_flag, |
| 1388 |
Filter=metadata_filter, |
| 1389 |
StartingIndex=starting_index, |
| 1390 |
RequestedCount=requested_count, |
| 1391 |
SortCriteria=sort_criteria, |
| 1392 |
) |
| 1393 |
|
| 1394 |
return DmsDevice.BrowseResult( |
| 1395 |
didl_lite.from_xml_string(result["Result"], strict=False), |
| 1396 |
int(result["NumberReturned"]), |
| 1397 |
int(result["TotalMatches"]), |
| 1398 |
int(result["UpdateID"]), |
| 1399 |
) |
| 1400 |
|
| 1401 |
async def async_browse_metadata( |
| 1402 |
self, |
| 1403 |
object_id: str, |
| 1404 |
metadata_filter: Iterable[str] | str = DEFAULT_METADATA_FILTER, |
| 1405 |
) -> didl_lite.DidlObject: |
| 1406 |
"""Get the metadata (properties) of an object.""" |
| 1407 |
_LOGGER.debug("browse_metadata(%r, %r)", object_id, metadata_filter) |
| 1408 |
result = await self.async_browse( |
| 1409 |
object_id, |
| 1410 |
"BrowseMetadata", |
| 1411 |
metadata_filter, |
| 1412 |
) |
| 1413 |
metadata = result.result[0] |
| 1414 |
assert isinstance(metadata, didl_lite.DidlObject) |
| 1415 |
_LOGGER.debug("browse_metadata -> %r", metadata) |
| 1416 |
return metadata |
| 1417 |
|
| 1418 |
async def async_browse_direct_children( |
| 1419 |
self, |
| 1420 |
object_id: str, |
| 1421 |
metadata_filter: Iterable[str] | str = DEFAULT_METADATA_FILTER, |
| 1422 |
starting_index: int = 0, |
| 1423 |
requested_count: int = 0, |
| 1424 |
sort_criteria: Iterable[str] | str = DEFAULT_SORT_CRITERIA, |
| 1425 |
) -> BrowseResult: |
| 1426 |
"""Get the direct children of an object.""" |
| 1427 |
# pylint: disable=too-many-arguments,too-many-positional-arguments |
| 1428 |
_LOGGER.debug("browse_direct_children(%r, %r)", object_id, metadata_filter) |
| 1429 |
result = await self.async_browse( |
| 1430 |
object_id, |
| 1431 |
"BrowseDirectChildren", |
| 1432 |
metadata_filter, |
| 1433 |
starting_index, |
| 1434 |
requested_count, |
| 1435 |
sort_criteria, |
| 1436 |
) |
| 1437 |
_LOGGER.debug("browse_direct_children -> %r", result) |
| 1438 |
return result |
| 1439 |
|
| 1440 |
@property |
| 1441 |
def has_search_directory(self) -> bool: |
| 1442 |
"""Check if device supports the Search action.""" |
| 1443 |
return self._action("CD", "Search") is not None |
| 1444 |
|
| 1445 |
async def async_search_directory( |
| 1446 |
self, |
| 1447 |
container_id: str, |
| 1448 |
search_criteria: str, |
| 1449 |
metadata_filter: Iterable[str] | str = DEFAULT_METADATA_FILTER, |
| 1450 |
starting_index: int = 0, |
| 1451 |
requested_count: int = 0, |
| 1452 |
sort_criteria: Iterable[str] | str = DEFAULT_SORT_CRITERIA, |
| 1453 |
) -> BrowseResult: |
| 1454 |
"""Search ContentDirectory for objects that match some criteria. |
| 1455 |
|
| 1456 |
NOTE: This is not UpnpProfileDevice.async_search, which searches for |
| 1457 |
matching UPnP devices. |
| 1458 |
""" |
| 1459 |
# pylint: disable=too-many-arguments,too-many-positional-arguments |
| 1460 |
_LOGGER.debug( |
| 1461 |
"search_directory(%r, %r, %r)", |
| 1462 |
container_id, |
| 1463 |
search_criteria, |
| 1464 |
metadata_filter, |
| 1465 |
) |
| 1466 |
|
| 1467 |
action = self._action("CD", "Search") |
| 1468 |
if not action: |
| 1469 |
raise UpnpError("Missing action CD/Search") |
| 1470 |
|
| 1471 |
if not isinstance(metadata_filter, str): |
| 1472 |
metadata_filter = ",".join(metadata_filter) |
| 1473 |
if not isinstance(sort_criteria, str): |
| 1474 |
sort_criteria = ",".join(sort_criteria) |
| 1475 |
|
| 1476 |
result = await action.async_call( |
| 1477 |
ContainerID=container_id, |
| 1478 |
SearchCriteria=search_criteria, |
| 1479 |
Filter=metadata_filter, |
| 1480 |
StartingIndex=starting_index, |
| 1481 |
RequestedCount=requested_count, |
| 1482 |
SortCriteria=sort_criteria, |
| 1483 |
) |
| 1484 |
|
| 1485 |
browse_result = DmsDevice.BrowseResult( |
| 1486 |
didl_lite.from_xml_string(result["Result"], strict=False), |
| 1487 |
int(result["NumberReturned"]), |
| 1488 |
int(result["TotalMatches"]), |
| 1489 |
int(result["UpdateID"]), |
| 1490 |
) |
| 1491 |
|
| 1492 |
_LOGGER.debug("search_directory -> %r", browse_result) |
| 1493 |
|
| 1494 |
return browse_result |
| 1495 |
|
| 1496 |
# endregion |
| 1497 |
|
| 1498 |
|
| 1499 |
class ContentDirectoryErrorCode(IntEnum): |
| 1500 |
"""Error codes specific to DLNA Content Directory actions.""" |
| 1501 |
|
| 1502 |
NO_SUCH_OBJECT = 701 |
| 1503 |
INVALID_CURRENT_TAG_VALUE = 702 |
| 1504 |
INVALID_NEW_TAG_VALUE = 703 |
| 1505 |
REQUIRED_TAG = 704 |
| 1506 |
READ_ONLY_TAG = 705 |
| 1507 |
PARAMETER_MISMATCH = 706 |
| 1508 |
INVALID_SEARCH_CRITERIA = 708 |
| 1509 |
INVALID_SORT_CRITERIA = 709 |
| 1510 |
NO_SUCH_CONTAINER = 710 |
| 1511 |
RESTRICTED_OJECT = 711 |
| 1512 |
BAD_METADATA = 712 |
| 1513 |
RESTRICTED_PARENT_OBJECT = 713 |
| 1514 |
NO_SUCH_SOURCE_RESOURCES = 714 |
| 1515 |
SOURCE_RESOURCE_ACCESS_DENIED = 715 |
| 1516 |
TRANSFER_BUSY = 716 |
| 1517 |
NO_SUCH_FILE_TRANSFER = 717 |
| 1518 |
NO_SUCH_DESTINATION_SOURCE = 718 |
| 1519 |
DESTINATION_RESOURCE_ACCESS_DENIED = 719 |
| 1520 |
CANNOT_PROCESS_REQUEST = 720 |