Debian Codegraph @

async_upnp_client/profiles/dlna.py

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