Coverage for custom_components/supernotify/methods/media_player_image.py: 91%

33 statements  

« prev     ^ index     » next       coverage.py v7.6.8, created at 2024-12-28 14:21 +0000

1import logging 

2import re 

3import urllib.parse 

4 

5from custom_components.supernotify import METHOD_MEDIA 

6from custom_components.supernotify.delivery_method import DeliveryMethod 

7from custom_components.supernotify.envelope import Envelope 

8 

9RE_VALID_MEDIA_PLAYER = r"media_player\.[A-Za-z0-9_]+" 

10 

11_LOGGER = logging.getLogger(__name__) 

12 

13 

14class MediaPlayerImageDeliveryMethod(DeliveryMethod): 

15 method = METHOD_MEDIA 

16 default_action = "media_player.play_media" 

17 

18 def __init__(self, *args, **kwargs) -> None: 

19 super().__init__(*args, **kwargs) 

20 

21 def select_target(self, target: str) -> bool: 

22 return re.fullmatch(RE_VALID_MEDIA_PLAYER, target) is not None 

23 

24 def validate_action(self, action: str | None) -> bool: 

25 return action is None or action == "media_player.play_media" 

26 

27 async def deliver(self, envelope: Envelope) -> bool: 

28 _LOGGER.info("SUPERNOTIFY notify_media: %s", envelope.data) 

29 

30 data = envelope.data or {} 

31 media_players = envelope.targets or [] 

32 if not media_players: 

33 _LOGGER.debug("SUPERNOTIFY skipping media show, no targets") 

34 return False 

35 

36 snapshot_url = data.get("snapshot_url") 

37 if snapshot_url is None: 

38 _LOGGER.debug("SUPERNOTIFY skipping media player, no image url") 

39 return False 

40 # absolutize relative URL for external URl, probably preferred by Alexa Show etc 

41 snapshot_url = urllib.parse.urljoin(self.context.hass_external_url, snapshot_url) 

42 

43 action_data = {"media_content_id": snapshot_url, "media_content_type": "image", "entity_id": media_players} 

44 if data and data.get("data"): 

45 action_data["extra"] = data.get("data") 

46 

47 return await self.call_action(envelope, action_data=action_data)